由于微信获取手机号安全模式的升级,直接在在微信小程序里面调用微信后台,是获取不到用户手号,获取用户手机号需要后台服务器和微后台交互才能获得。
1.获取access_token
请求路径
GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
这个比较简单,只要问前端拿到appid和secret就可以直接访问获取token,用浏览器访问都能拿的到
接口会返回
access_token
和 token凭证有效时间expires_in
,单位:秒。目前是7200秒之内的值。
2.获取手机号
直接上全部代码
yml
# 微信小程序配置
wx:
miniapp:
configs:
- appid: ******aa486******
secret: ******a770bb******
pom.xml
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.57</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
<!-- 阿里fastjson包JSON转换-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
controller
@ApiOperation("获取手机号")
@RequestMapping(value = "/getPhone", method = RequestMethod.POST)
@ResponseBody
public CommonResult getPhone(@RequestParam String code){
return CommonResult.success(memberService.getPhone(code), "手机号获取成功");
}
service
/**
* 获取手机号
*/
String getPhone(String code);
serviceImpl
@Value("${wx.miniapp.configs.appid}")
private String appid;
@Value("${wx.miniapp.configs.secret}")
private String secret;
@Override
public String getPhone(String code) {
if (code!=null){
//先获取access_token = appid + secret
HttpResponse response = HttpRequest.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "").execute();
JSONObject tokenJson = JSON.parseObject(response.body());
if(!tokenJson.containsKey("access_token")){
return "获取access_token令牌失败";
}
String accessToken = tokenJson.get("access_token").toString();
//用 access_token + code 获取手机号
JSONObject jsonCode = new JSONObject();
jsonCode.put("code",code);
String resPhone = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, jsonCode.toString());
if(StringUtils.isEmpty(resPhone) || !resPhone.contains("phone_info") || !resPhone.contains("phoneNumber")){
return "手机号获取失败";
}
JSONObject resPhoneInfo = JSON.parseObject(resPhone);
JSONObject phoneInfo=resPhoneInfo.getJSONObject("phone_info");
System.out.println(resPhoneInfo);
System.out.println(phoneInfo);
return phoneInfo.get("phoneNumber").toString();
}
return "手机号获取凭证code不能为空";
}
返回结果
{
"errcode":0,
"errmsg":"ok",
"phone_info":
{
"phoneNumber":"18888888888",
"watermark":
{
"appid":"abcdefghijklmnobqrstuvwxyz",
"timestamp":827319823
},
"purePhoneNumber":"18888888888",
"countryCode":"12"
}
}
总结: 本文代码经过本人亲测,并在项目中实施可用,供大家借鉴,但是微信小程序官方说不定哪天就改了接口什么的,所以我只能保证在发文前好使,后面你们在看好不好使就不知道了