后端获取access_token方式:
public static String getAccessToken() {
String result = null;
String baseUrl = "https://api.weixin.qq.com/cgi-bin/token";
HashMap<String, Object> requestParam = new HashMap<>();
// 小程序 固定参数
requestParam.put("grant_type", "client_credential");
// 小程序唯一凭证id
requestParam.put("appid", AppID);
// 小程序 appSecret(小程序的唯一凭证密钥,换成自己的)
requestParam.put("secret", AppSecret);
// 发送GET请求读取调用微信接口获取openid用户唯一标识
String wxback = HttpUtil.get(baseUrl, requestParam);
JSONObject responseJsonObject = JSONUtil.parseObj(wxback);
if (ObjectUtil.isNull(responseJsonObject)) throw new Exception("响应异常:获取信息为空!");
result = responseJsonObject.getStr("access_token");
return result;
}
后端获取手机号方式:
public static String getUserPhone(String accessToken, String code) throws Exception {
String result = null;
// 接口调用凭证:accessToken
String baseUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
HashMap<String, Object> requestParam = new HashMap<>();
// 手机号调用凭证
requestParam.put("code", code);
// 发送post请求读取调用微信接口获取openid用户唯一标识
String jsonStr = JSONUtil.toJsonStr(requestParam);
HttpResponse response = HttpRequest.post(baseUrl)
.header(Header.CONTENT_ENCODING, "UTF-8")
// 发送json数据需要设置contentType
.header(Header.CONTENT_TYPE, "application/json")
.body(jsonStr)
.execute();
if (response.getStatus() == HttpStatus.HTTP_OK) {
result = response.body();
}
// 请求参数解析
JSONObject jsonObject = JSONUtil.parseObj(result);
// 获取errmsg,判断消息发送是否成功
String errmsg = jsonObject.getStr("errmsg");
if (!StrUtil.equals("ok", errmsg)) throw new Exception("消息发送失败!");
Object phoneInfo = jsonObject.get("phone_info");
JSONObject phonepara = JSONUtil.parseObj(jsonObject);
Object phoneNumber = phonepara.get("phoneNumber");
String phoneresult = phoneNumber.toString();
return phoneresult;
}
前端获取code方式:
wx.login({
success: async (res) => {
console.log(res)
})
后端获取一直报40029;appid和secret对比了很多次也没有问题
{"errcode":40029,"errmsg":"invalid code hint: [xxx] rid: xxxx"}
{"errcode":40029,"errmsg":"invalid code hint: [xxxxx] rid: xxxx"}
{"errcode":40029,"errmsg":"invalid code hint: [xxx] rid: xxx"}
应该如何解决,麻烦加急处理下,谢谢!!!
获取手机号看这个https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
无法使用wx.login的code获取手机号
wx.login 和 code2session是一对,login跟获取手机号有啥关系?