功能示例图如下
用户点击一键登录,用户点击允许后获取用户手机号码
前端代码:
<button class="confirm-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" style="background: linear-gradient(55deg, #377ffd, #5db7fb);">
一键登录
</button>
js代码
// 手机号授权
onGetPhoneNumber(e){
// 用户已授权
if (e.detail.errMsg === 'getPhoneNumber:ok') {
const iv = e.detail.iv
const code = e.detail.code
const encryptedData = e.detail.encryptedData
// 将 encryptedData 和 iv 发送到后端解密
this.quickLogin(encryptedData, iv)
} else {
// 用户拒绝授权
uni.showToast({
title: '授权失败',
icon: 'error'
})
}
},
quickLogin(_encryptedData=null, _iv=null){
const that = this
uni.login({
provider: 'weixin',
success: function(loginRes) {
uni.getUserInfo({
success: (userInfoRes) => {
const iv = _iv ?? userInfoRes.iv
const encryptedData = _encryptedData ?? userInfoRes.encryptedData
http.post('/user/login', {
iv: iv,
register: true,
code: loginRes.code,
encryptedData: encryptedData,
}).then(res => {
if(res.code == 0){
//登录成功,设置用户信息
}else{
uni.showModal({
title: '登录失败',
content: res.msg,
showCancel: false,
confirmText: '确定',
})
}
})
},fail: (res) =>{
console.log('失败', res)
}
})
},fail: (res) =>{
console.log('失败', res)
}
})
}
后端使用的是thinkphp6,和easyWeChat的SKD4.0版本
文档:https://easywechat.com/4.x/
/**
* 一键登录
*/
public function quickLogin()
{
$param = $this->request->param();
$code = $param['code'];
$iv = $param['iv'];
$encryptedData = $param['encryptedData'];
$app = Factory::miniProgram($config);
//根据code获取session_key
$wxUserInfo = $this->app->auth->session($code);
//消息解密。比如获取电话等功能,信息是加密的,需要解密。
$data = $this->app->encryptor->decryptData($wxUserInfo['session_key'], $iv, $encryptedData);
//输出
dump($data);
// [
// "phoneNumber" => "手机号"
// "purePhoneNumber" => "手机号"
// "countryCode" => "86"
// "watermark" => array:2 [
// "timestamp" => 1721456497
// "appid" => ""
// ]
// ]
//登录逻辑...
}