1. 前端获取动态令牌 code
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
2. 后端接收令牌code, 调用微信获取手机号接口
POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
3. controller
/**
* 获取用户手机号
*
* @param code 动态令牌。可通过动态令牌换取用户手机号
* 注:getPhoneNumber 返回的 code 与 wx.login 返回的 code 作用是不一样的,不能混用
* @return
*/
@ApiOperation("获取用户手机号")
@GetMapping("/getPhoneNumber")
public AjaxResult getPhoneNumber(String code){
return lsUserService.getPhoneNumber(code);
}
4. service
/**
* 获取用户手机号
*
* @param code 手机号获取凭证
* @return
*/
@Override
public AjaxResult getPhoneNumber(String code) {
if (StringUtils.isEmpty(code)) {
return AjaxResult.error("手机号获取凭证不能为空 !");
}
log.info("手机号获取凭证: {}", code);
try {
//通过appid和secret来获取token
String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WxPayUtils.appId, WxPayUtils.appSecret);
JSONObject token = JSON.parseObject(HttpUtil.get(tokenUrl));
//通过token和code来获取用户手机号
String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
//封装请求体
Map<String, String> paramMap = new HashMap<>();
paramMap.put("code", code);
//封装请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);
//通过RestTemplate发送请求,获取到用户手机号码
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
String errmsg = response.getBody().getString("errmsg");
if (errmsg.equals("ok")) {
JSONObject phoneInfoJson = response.getBody().getJSONObject("phone_info");
String phoneNumber = phoneInfoJson.getString("phoneNumber");
return AjaxResult.success(phoneNumber);
}
} catch (Exception e) {
e.printStackTrace();
}
return AjaxResult.error("手机号获取失败");
}