91名师指路-头部
91名师指路

微信小程序获取手机号

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

一:在页面放置按钮

<button class="cu-btn bg-green shadow" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">绑定手机号</button>

二:编写decryptPhoneNumber() 方法

decryptPhoneNumber(e){
console.log(e);
if(e.detail.errMsg=='getPhoneNumber:ok'){
uni.request({ // 绑定手机号
url: config.host+'/wxmini/bind/phone', // 绑定手机号的后端接口
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
code: e.detail.code,
openId: openId // 自己在页面中缓存获取或调接口获取
},
success: (res) => {
// 成功后的逻辑处理
},
fail: (res) => {
// 失败处理
}
});
}
}


三:我们点击绑定手机号后的效果



我们点击允许按钮后,能够获取到的参数信息。




四:后端绑定手机号的方法

/**
* 功能:获取手机号 * 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html
* @Author: zxb * @Date: 2022-03-07 09:12:02
*/
@PostMapping("/bind/phone")
public ReturnMsgUtils bindPhone(String code, String openId){
String phoneNumber=null;

// 1 获取token我进行封装了,大家自己去实现,调用的是这个接口:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xx&secret=xx
String token=WechatMiniTokenUtils.getAccessToken();

// 2 调用小程序获取手机号的接口
String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+token;
JSONObject json=new JSONObject();
json.put("code", code);
String result=HttpClientUtils.sendHttpPost(url, null, json.toJSONString());
log.info("调用小程序获取手机号的接口结果 {}", result);

// 3 解析结果
JSONObject jsonResult=JSON.parseObject(result);
int errcode=jsonResult.getInteger("errcode");
if(errcode==0){
JSONObject phoneInfo=jsonResult.getJSONObject("phone_info");
phoneNumber=phoneInfo.getString("phoneNumber"); // 用户绑定的手机号(国外手机号会有区号)
}

// 4 业务逻辑处理...

ReturnMsgUtils msg=new ReturnMsgUtils(BusinessUtils.BUSINESS_CODE_200, BusinessUtils.BUSINESS_MINI_200_MSG);
return msg;
}


备注:

如果大家想看完整的效果,可以微信搜索小程序 91待办 ,到我的 > 账号信息里面去体验。





2022-04-19 20:48:51     阅读(522)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部