以往我们旧的接口:https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=jscode&grant_type=authorization_code
获取手机号码,需要到服务端引入官方解密方法对手机号进行解密,但是这个解密很不稳定,经常出现-41003: aes 加密数据解密失败问题,现在可以使用下面新的接口获取手机号:
步骤:
1、获取微信凭证access_token
2、动态获取手机号
注:该接口需配合手机号快速验证或手机号实时验证能力一起使用,当用户同意后,可以通过 bindgetphonenumber 或 bindrealtimegetphonenumber 事件回调获取到动态令牌code,再调用该接口将code换取用户手机号。 注意:每个code只能使用一次,code的有效期为5min。
前端代码:
<button class="get_submit" open-type="getPhoneNumber" v-if="!qcode" bindgetphonenumber="getPhoneNumber">授权手机号</button>
js代码:
async getPhoneNumber (e) {
var __that = this
var iv = e.$wx.detail.iv;
var encryptedData = e.$wx.detail.encryptedData;
var code = e.$wx.detail.code;
// 显示加载图标
wx.showLoading({
title: '加载中',
})
const getUserPhones = await getTriageUserPhone({
code: code,
iv: iv,
encryptedData: encodeURIComponent(encryptedData),
})
if(getUserPhones.data.code==200){
wx.hideLoading();
__that.qcode = getUserPhones.data.data
}
}PHP代码:
public function getUserPhone(Request $request){
$appid = Env('WECHAT_MINI_PROGRAM_APPID');
$secret = Env('WECHAT_MINI_PROGRAM_SECRET');
$encryptedData = urldecode($request->encryptedData); //包括敏感数据在内的完整用户信息的加密数据
$code=$request->code; //用户登录授权获取到的code
$iv=$request->iv; //用户登录授权获取到的iv
$access_token_phone = 'https://api.weixin.qq.com/cgi-bin/token?appid='.$appid.'&secret='.$secret.'&grant_type=client_credential';
$access_token = $this->curlOpen($access_token_phone);
$access_token = json_decode($access_token, true);
$url_phone='https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token['access_token'];
$data_phone = [
'code'=>$code
];
$result_phone = $this->curlRequest($url_phone,json_encode($data_phone));
$result_phone = json_decode($result_phone, true);
return response ()->json(['code'=>200,'msg'=>'success','data'=>$result_phone]);
}使用新接口的好处就是不会再出现获取手机号失败问题。
关于简忆
简忆诞生的故事



粤ICP备16092285号
文章评论(0)