微信小程序获取用户手机号

view部分代码写法:

<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">立即登录</button>

编写WXBizDataCrypt.js用于对用户电话号码进行解密:

var crypto = require('crypto')

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode
  var sessionKey = new Buffer(this.sessionKey, 'base64')
  encryptedData = new Buffer(encryptedData, 'base64')
  iv = new Buffer(iv, 'base64')

  try {
     // 解密
    var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
    // 设置自动 padding 为 true,删除填充补位
    decipher.setAutoPadding(true)
    var decoded = decipher.update(encryptedData, 'binary', 'utf8')
    decoded += decipher.final('utf8')
    
    decoded = JSON.parse(decoded)

  } catch (err) {
    throw new Error('Illegal Buffer')
  }

  if (decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer')
  }

  return decoded
}

module.exports = WXBizDataCrypt

获取电话号码核心代码:

//获取电话号码
import WXBizDataCrypt from "@/common/WXBizDataCrypt.js"
			getPhoneNumber(e){
				uni.login({
					provider:"weixin",
					scopes:"auth_base",
					onlyAuthorize:true,
					success:res=> {
						userMessage(res.code).then((res)=>{
							this.openid = res.data.openid
							this.sessionkey = res.data.session_key
							if(e.detail.errMsg=='getPhoneNumber:ok'){
								this.iv=e.detail.iv;
								this.encryptedData=e.detail.encryptedData
								//对用户的电话号进行解密,这里的WXBizDataCrypt需要引入
								let sessionkey = new WXBizDataCrypt(this.appid,this.sessionkey);
								let data = sessionkey.decryptData(this.encryptedData,this.iv);
								this.countryCode=data.countryCode;
								this.phoneNumber=data.phoneNumber;
							}
						})
					}
				})
			}

api.js中userMessage写法:appid和secret在微信公众平台上有

//获取微信的接口凭证openid 和 sessionkey
export function userMessage(code) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://api.weixin.qq.com/sns/jscode2session',
			method: 'GET',
			data: {
				appid: '你的appid',
				secret: '你的secret',
				js_code: `${code}`,
				grant_type: 'authorization_code'
			},
			success: res => {
				resolve(res);
			}
		})
	})
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值