egg 微信小程序获取手机号
时间: 2023-11-27 16:47:12 浏览: 43
根据提供的引用内容,可以看出这个问题涉及到Egg-weapp-sdk和小程序前端的代码。下面是获取微信小程序手机号的步骤:
1.在小程序前端代码中,使用`getPhoneNumber`方法获取用户手机号。代码如下:
```javascript
async getPhoneNumber(e){
if(e.detail.errMsg == "getPhoneNumber:ok"){
//走后端api
uni.showLoading({title: '登录中~', mask: true})
const res = await wxCryptPhone({ session_key: this.session_key, iv:e.detail.iv, encryptedData: e.detail.encryptedData });
// 登录成功
console.log(res)
//还没保存用户信息到vuex
uni.navigateBack({ delta: 1 })
}else{
//console.log('用户点击了拒绝');
this.$u.toast('用户拒绝授权');
}
},
```
2.在后端API中,使用Egg-weapp-sdk获取用户手机号。代码如下:
```javascript
const { Weapp } = require('egg-weapp-sdk');const weapp = new Weapp({
appId: 'your app id',
appSecret: 'your app secret',
});
async function getPhoneNumber(sessionKey, iv, encryptedData) {
const result = await weapp.decryptPhoneNumber(sessionKey, iv, encryptedData);
return result.phoneNumber;
}
```
需要注意的是,获取用户手机号需要用户授权,如果用户拒绝授权,则无法获取手机号。
相关推荐
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)