微信小程序怎么获取用户手机号完整代码
时间: 2023-11-06 17:05:33 浏览: 106
微信小程序获取用户手机号需要前端进行授权,后端需要进行解密。以下是完整代码:
前端代码:
```
wx.login({
success: function (res) {
if (res.code) {
wx.request({
url: 'https://yourdomain.com/onLogin',
data: {
code: res.code
},
success: function (res) {
if (res.data.code === 0) {
wx.setStorageSync('token', res.data.data.token);
wx.getUserInfo({
success: function (res) {
wx.request({
url: 'https://yourdomain.com/onGetUserInfo',
data: {
encryptedData: res.encryptedData,
iv: res.iv
},
header: {
'Authorization': 'Bearer ' + res.data.data.token
},
success: function (res) {
console.log(res.data);
}
})
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
```
后端代码:
```
<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
use app\api\model\User as UserModel;
use app\api\service\Token as TokenService;
use app\api\service\WxUser as WxUserService;
class User extends Controller
{
public function login()
{
$code = input('post.code');
$wxUser = new WxUserService($code);
$openid = $wxUser->getOpenId();
$user = UserModel::getByOpenId($openid);
if (!user) {
$user = UserModel::create([
'openid' => $openid
]);
}
$token = TokenService::generateToken();
TokenService::saveToCache($token, $user->id);
return [
'code' => 0,
'data' => [
'token' => $token
]
];
}
public function getUserInfo()
{
$encryptedData = input('post.encryptedData');
$iv = input('post.iv');
$token = TokenService::getCurrentToken();
$uid = TokenService::getUidByToken($token);
$user = UserModel::get($uid);
$wxUser = new WxUserService();
$wxUser->setSessionKey($user->session_key);
$wxUserInfo = $wxUser->getUserInfo($encryptedData, $iv);
$user->saveUserInfo($wxUserInfo);
return [
'code' => 0,
'data' => $wxUserInfo
];
}
public function getPhoneNumber()
{
$encryptedData = input('post.encryptedData');
$iv = input('post.iv');
$token = TokenService::getCurrentToken();
$uid = TokenService::getUidByToken($token);
$user = UserModel::get($uid);
$wxUser = new WxUserService();
$wxUser->setSessionKey($user->session_key);
$phoneNumber = $wxUser->getPhoneNumber($encryptedData, $iv);
$user->savePhoneNumber($phoneNumber);
return [
'code' => 0,
'data' => $phoneNumber
];
}
}
```
其中,WxUserService是一个封装了微信小程序登录和解密的服务类,UserModel是一个用户模型类,TokenService是一个封装了Token生成和验证的服务类。
阅读全文