微信小程序开发 通过 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;
}

微信小程序是一款非常流行的移动应用程序,它提供了许多功能和API供开发者使用。获取微信运动步数是其的一个功能,以下是一个使用Java编写的微信小程序获取微信运动步数的实例代码。 ```java import java.net.URL; import java.net.HttpURLConnection; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; public class WeChatMiniProgram { public static void main(String[] args) { // 小程序的AppID String appId = "your_app_id"; // 登录凭证code String code = "your_code"; // 小程序的AppSecret String appSecret = "your_app_secret"; // 获取access_token的URL String accessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&grant_type=authorization_code&js_code=" + code; try { // 发送HTTP请求获取access_token URL url = new URL(accessTokenUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 读取返回的数据 InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder response = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { response.append(line); } // 解析返回的数据 String jsonString = response.toString(); // 提取access_token和openid String accessToken = // 从jsonString提取access_token String openId = // 从jsonString提取openId // 获取微信运动步数的URL String stepCountUrl = "https://api.weixin.qq.com/sns/more_info?access_token=" + accessToken + "&openid=" + openId; // 发送HTTP请求获取微信运动步数 URL stepUrl = new URL(stepCountUrl); HttpURLConnection stepConnection = (HttpURLConnection) stepUrl.openConnection(); stepConnection.setRequestMethod("GET"); stepConnection.connect(); // 读取返回的数据 InputStream stepInputStream = stepConnection.getInputStream(); InputStreamReader stepInputStreamReader = new InputStreamReader(stepInputStream, "UTF-8"); BufferedReader stepBufferedReader = new BufferedReader(stepInputStreamReader); StringBuilder stepResponse = new StringBuilder(); String stepLine; while ((stepLine = stepBufferedReader.readLine()) != null) { stepResponse.append(stepLine); } // 解析返回的数据 String stepJsonString = stepResponse.toString(); // 提取微信运动步数 int stepCount = // 从stepJsonString提取微信运动步数 // 输出微信运动步数 System.out.println("微信运动步数:" + stepCount); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码,通过发送HTTP请求获取微信小程序的`access_token`和`openId`,然后使用`access_token`和`openId`来发送第二个HTTP请求,获取微信运动步数。需要注意的是,你需要将代码的`your_app_id`、`your_code`和`your_app_secret`替换为你自己的实际值。此外,代码的JSON解析部分需要进行具体的实现。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值