第一步:前端写法
从基础库 2.21.2 开始,对获取手机号的接口进行了安全升级,以下是新版本接口使用指南。(旧版本接口目前可以继续使用,但建议开发者使用新版本接口,以增强小程序安全性)
因为需要用户主动触发才能发起获取手机号接口,所以该功能不由 API 来调用,需用 button 组件的点击来触发。另外,新版本接口不再需要提前调用wx.login
进行登录。
<button class="btnValue" open-type="getPhoneNumber" @getphonenumber="OngetPhoneNumber">登录</button>
methods: {
OngetPhoneNumber(e) {
uni.request({
url: this.$pathurl + '/apiwx/getuserphonenumber', //微信接口必须使用可校验域名绑定
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
},
data: {
code: e.detail.code, //wx.login登录成功后的code
},
success: (cts) => {
getApp().globalData.isuserphone = cts.data.phoneNumber;
//后续逻辑省略
第二步 后台代码部分:
/**
* 新版获取手机号方法
* */
@RequestMapping(value = "/getuserphonenumber", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> getuserphonenumber(@RequestParam(required = true) String code) throws IOException {
return this.getuserphonenumberByCode(code);
}
private Map<String, Object> getuserphonenumberByCode(String code) throws IOException {
// 发送请求
String getToken_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
String getToken = HttpUtil.get(getToken_url);
ObjectMapper mappergetToken = new ObjectMapper();
Map<String, Object> jsongetToken = null;
jsongetToken = mappergetToken.readValue(getToken, Map.class);
String access_token = (String) jsongetToken.get("access_token");
//封装请求参数
Map map = new HashMap();
map.put("code",code);
com.alibaba.fastjson.JSONObject jsonObject = HttpUtil.ww("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token,map);
jsonObject.get("phone_info");
return jsonObject;
}
public static JSONObject ww(String url,Map map) throws IOException {
//创建一个获取连接客户端的工具
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建Post请求
HttpPost httpPost = new HttpPost(url);
//添加请求头
httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
JSONObject jsonString = new JSONObject(map);
StringEntity entity = new StringEntity(jsonString.toString(),"UTF-8");
//将封装的参数添加到Post请求中
httpPost.setEntity(entity);
//执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取响应的实体
HttpEntity responseEntity = response.getEntity();
//转化成字符串
String entityString = EntityUtils.toString(responseEntity);
//转换成JSON格式输出
JSONObject jsonObject = JSONObject.parseObject(entityString);
JSONObject phone_info = (JSONObject) jsonObject.get("phone_info");
return phone_info;
}
即可成功获取用户手机号,执行后续操作!