微信小程序开发 通过 java 代码获取 accessToken

1、获取微信小程序AccessToken准备工作?

  1. **请求URL:**https://api.weixin.qq.com/cgi-bin/token
  2. 所需参数: 1、grant_type 默认写死为 client_credential 2、appid 你小程序的APPID 3、secret 你小程序的 secret

2、Java发送Http请求工具类封装

import com.alibaba.fastjson.JSON;
import com.dftcmedia.tckk.microservice.sskx.microapp.util.WeiXinResponseWrapper;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.IOException;

/**
 * WeixinClient
 *
 * @author
 * @date 2019/3/13
 */
public class WeiXinClientUtil {

    private WeiXinClientUtil() {
    }

    public static WeiXinResponseWrapper sendGetRequest(String path, NameValuePair[] pairs) throws IOException {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod();
        method.setPath(path);
        method.setQueryString(pairs);
        client.executeMethod(method);
        byte[] bytes = method.getResponseBody();
        return WeiXinResponseWrapper.wrap(JSON.parseObject(new String(bytes)));
    }

    public static WeiXinResponseWrapper sendPostRequest(String path, NameValuePair[] pairs, String body) throws IOException {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod();
        method.setPath(path);
        method.setQueryString(pairs);
        RequestEntity entity = new StringRequestEntity(body, "application/json", "utf-8");
        method.setRequestEntity(entity);
        client.executeMethod(method);
        byte[] bytes = method.getResponseBody();
        return WeiXinResponseWrapper.wrap(JSON.parseObject(new String(bytes)));
    }

}

WeiXinResponseWrapper 是调用微信url的响应结果分装类

3、WeiXinResponseWrapper 类代码

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * WeiXinResponseWrapper
 *
 * @author
 * @date 2019/3/13
 */
@Data
@AllArgsConstructor
public class WeiXinResponseWrapper {

    private String errCode;
    private String errMsg;
    private JSONObject data;

    public static WeiXinResponseWrapper wrap(JSONObject jo) {
        return new WeiXinResponseWrapper(jo.getString("errcode"), jo.getString("errmsg"), jo);
    }

    public boolean isRequestSucceed() {
        return errCode==null||"0".equals(errCode);
    }

    public String get(String key) {
        return data.getString(key);
    }
}

4、获取AccessToken方法

public String getAccessToken() {
        NameValuePair[] params = new NameValuePair[]{
                new NameValuePair("grant_type", "client_credential"),
                new NameValuePair("appid", properties.getAppId()),
                new NameValuePair("secret", properties.getSecret())
        };
        WeiXinResponseWrapper response = null;
        try {
            response = WeiXinClientUtil.sendGetRequest(WeiXinConstant.ACCESS_TOKEN, params);
        } catch (IOException e) {
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR);
        }
        if (!response.isRequestSucceed()) {
            log.error(response.getErrCode()+response.getErrMsg());
            throw new ApiException(ServiceCodeEnum.LIMIT);
        }
        return response.getData().getString("access_token");
    }




```java
/**
 * WeiXinConstant
 *
 * @author
 * @date 2019/3/13
 */
public class WeiXinConstant {

    public static final String LOGIN_GRAND_TYPE = "authorization_code";
    public static final String ACCESS_TOKEN_GRAND_TYPE = "client_credential";

    public static final String ACCESS_TOKEN_PATH = "https://api.weixin.qq.com/sns/jscode2session";

    public static final String ACCESS_TOKEN= "https://api.weixin.qq.com/cgi-bin/token";
    public static final String IMG_FILTER_URL= "https://api.weixin.qq.com/wxa/img_sec_check";
    public static final Long ACCESS_TOKEN_EXPIRE_TIME=7000L;



}

```java
@EqualsAndHashCode(callSuper = true)
@Data
public class ApiException extends RuntimeException {
    private static final long serialVersionUID = -3005819231762830260L;
    public ApiException(ServiceCodeEnum codeEnum) {
        super(codeEnum.getMessage());
        this.errorCode = codeEnum.getCode();
    }

    public ApiException(Integer code, String message) {
        super(message);
        this.errorCode = code;
        this.data = null;
    }

    public ApiException(Integer code, String message, Object data) {
        super(message);
        this.errorCode = code;
        this.data = data;
    }

    private Integer errorCode;

    private Object data;
}
@Getter
public enum ServiceCodeEnum {
    /**
     *
     */
    SUCCESS(0, "成功"),

    /**
     * 失败
     */
    FAIL(1, "失败"),

    /**
     * 无效请求
     */
    BAD_REQUEST(400, "无效请求"),



    ServiceCodeEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    private Integer code;

    private String message;
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值