微信小程序:授权登录获取手机号及获取基本信息等

1、授权获取code,换取open_id

wx.login({
	success(res) {
		console.log(res.code)
		if (res.code) {
		//调自己后台接口换取open_id
		}
	}
})

微信文档1
微信文档

2、获取手机号

1)需要将 button 组件 open-type 的值设置为 getPhoneNumber,当用户点击并同意之后,通过 getphonenumber 事件获取回调信息;
2)将 getphonenumber 事件回调中的动态令牌code传到开发者后台,并在开发者后台调用微信后台提供的 phonenumber.getPhoneNumber 接口,消费code来换取用户手机号。每个code有效期为5分钟,且只能消费一次。

<button class="add" open-type="getPhoneNumber" @getphonenumber="getphonenumber">微信用户一键登录</button>

getphonenumber(e) {
	console.log(e.detail.code)
	console.log(e)
	//调用自己后台接口获取手机号
}

在这里插入图片描述
微信文档

3、用户头像

需要将 button 组件 open-type 的值设置为 chooseAvatar,当用户选择需要使用的头像之后,可以通过 chooseavatar 事件回调获取到头像信息的临时路径。

<button plain="true" class="button" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
	<image :src="userInfo.accountImg"></image>
</button>

chooseAvatar(e) {
	console.log(e.detail.avatarUrl)
	this.userInfo.accountImg = e.detail.avatarUrl
},

在这里插入图片描述

4、用户昵称

需要将 input 组件 type 的值设置为 nickname,当用户在此input进行输入时,键盘上方会展示微信昵称。

<input v-model="userInfo.name" type="nickname"  placeholder="请填写昵称" />

在这里插入图片描述
微信文档

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用uniapp框架开发微信小程序进行授权登录获取用户手机号的代码: 1. 在项目根目录下的 `manifest.json` 文件中添加微信小程序授权登录的配置: ```json "mp-weixin": { "appid": "你的小程序appid", "scope": "scope.userInfo,scope.userPhoneContact", "settings": { "authSetting": { "scope.userInfo": true, "scope.userPhoneContact": true } } } ``` 2. 在需要进行授权登录的页面中添加以下代码: ```html <template> <button type="primary" @click="getUserInfo">授权登录</button> </template> <script> export default { methods: { getUserInfo() { uni.getUserProfile({ desc: '用于完善会员资料', lang: 'zh_CN', success: (res) => { uni.login({ success: (loginRes) => { uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', data: { appid: '你的小程序appid', secret: '你的小程序secret', js_code: loginRes.code, grant_type: 'authorization_code' }, success: (sessionRes) => { const { openid, session_key } = sessionRes.data uni.request({ url: 'https://api.weixin.qq.com/wxa/getphoneNumber', data: { encryptedData: res.encryptedData, iv: res.iv, sessionKey: session_key }, success: (phoneRes) => { console.log(phoneRes.data.phoneNumber) } }) } }) } }) } }) } } } </script> ``` 说明: - `getUserProfile` 方法用于获取用户信息,包括手机号。 - `uni.login` 方法用于获取临时登录凭证code。 - `uni.request` 方法用于向微信服务器发送请求,获取用户手机号。 - 在 `getUserProfile` 方法中,`desc` 参数用于描述授权窗口的文案,`lang` 参数用于设置授权窗口的语言。 - 在 `uni.request` 方法中,`encryptedData` 参数为加密数据,`iv` 参数为加密算法的初始向量,`sessionKey` 参数为临时登录凭证的会话密钥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值