小程序js:
//获取手机号
getPhoneNumber(e) {
wx.login({
success(res2) {
if (e.detail.errMsg == "getPhoneNumber:ok") {
wx.request({
url: urls + '/api/Common/getPhoneNumber',
method: 'post',
dataType : 'json',
data: {
code: res2.code,
encryptedData: encodeURI(e.detail.encryptedData),
iv: e.detail.iv,
sessionKey: '',
},
success: function (res) {
// console.log(res.data)
if(res.data){
wx.setStorageSync('uid', res.data);
// console.log('手机号获取成功');
wx.navigateBack({
delta: 1,
})
}else{
console.log('手机号获取失败');
wx.showToast({
title: '获取失败,请重试',
icon: 'none',
duration: 2000
})
}
}
})
}
}
});
},
后端:
需要引入微信解密文件wxBizDataCrypt,网上可以下载到
namespace app\api\controller;
use think\Controller;
use app\common\wechat\wxBizDataCrypt;
//授权手机号存入数据库
public function getPhoneNumber() {
$routineAppId = '';//小程序appID
$routineAppSecret = '';//小程序AppSecret
$post=input('post.');
$encryptedData = $post['encryptedData'];
$js_code = $post ['code'];
$iv = $post ['iv'];
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $routineAppId . '&secret=' . $routineAppSecret . '&js_code=' . $js_code . '&grant_type=authorization_code';
$data = "";
$rest = file_get_contents($url, $data);
// return $rest;
if ($rest) {
$recod = json_decode($rest);
$crr['open_id'] = $recod->openid;
$wx = new wxBizDataCrypt($routineAppId, $recod->session_key); //微信解密函数,微信提供了php代码dome
$errCode = $wx->decryptData($encryptedData, $iv, $data1); //微信解密函数
// return $data1;
if ($errCode == 0) {
$data1 = json_decode($data1, true);
$phoneNumber = $data1['phoneNumber'];
// return $phoneNumber;
$id = db('users')->where(['mobile'=>$phoneNumber])->value('id');
if(!$id){
$id = db('users')->insertGetId(['mobile'=>$phoneNumber]);
}
return $id;
} else {
return json(false);
}
} else {
return json(false);
}
}