写一个微信小程序登录获取用户信息+手机号的,详细代码
时间: 2024-06-09 18:11:48 浏览: 10
以下是获取用户手机号的微信小程序登录示例代码:
1. 在 app.json 文件中添加以下内容:
```json
{
"pages": [
"pages/login/login"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "登录",
"navigationBarTextStyle": "black"
}
}
```
2. 在 pages/login/login.wxml 文件中添加以下内容:
```html
<view class="container">
<view class="title">微信登录</view>
<button class="login-btn" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>
</view>
```
3. 在 pages/login/login.js 文件中添加以下内容:
```javascript
Page({
data: {},
onLoad: function () {},
getPhoneNumber: function (e) {
if (e.detail.errMsg === 'getPhoneNumber:ok') {
wx.login({
success: res => {
wx.request({
url: 'https://yourdomain.com/api/login',
method: 'POST',
data: {
code: res.code,
encryptedData: e.detail.encryptedData,
iv: e.detail.iv
},
success: function (res) {
// 登录成功
wx.setStorageSync('token', res.data.token)
wx.switchTab({
url: '/pages/index/index',
})
},
fail: function () {
// 登录失败
wx.showToast({
title: '登录失败',
icon: 'none'
})
}
})
},
fail: function () {
wx.showToast({
title: '登录失败',
icon: 'none'
})
}
})
} else {
wx.showToast({
title: '获取手机号失败',
icon: 'none'
})
}
}
})
```
4. 在后端 API 中解密用户信息,获取手机号码并返回给前端。
注意:需要在小程序管理后台中设置服务器域名和上传安全域名,以及配置 HTTPS 证书。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)