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

javascript 复制代码
微信小程序获取用户手机号有2种,一种是前端自己解密,一种是获取后发给后端,后端去解密
重点:要在微信公众平台设置里面绑定微信开放平台账号,不然反解不出来用户手机号

上代码:
<button style="font-size: 16px;" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">授权并获取手机号</button>
import WXBizDataCrypt from "@/util/WXBizDataCrypt.js"
onGetPhoneNumber(e){
	uni.login({
					 provider: 'weixin',
					 success: function ({ code }) {
						uni.request({
							url: 'https://api.weixin.qq.com/sns/jscode2session', // 请求微信服务器
							method: 'GET',
							data: {
								appid: '', //你的小程序的APPID
								secret: '', //你的小程序秘钥secret,  
								js_code: code, //uni.login 登录成功后的code
								grant_type: 'authorization_code' //此处为固定值
							},
							success: (res) => {
								console.log('获取信息', res.data);
								console.log(e, "获取手机号需要的参数");
								let pc = new WXBizDataCrypt('你的小程序的APPID', res.data.session_key);
								let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
								if (data.phoneNumber != '') {
									console.log(data.phoneNumber)
								}
							}
						});
					 },
					 fail: function (err) {
						 uni.showToast({ title: '请前往小程序使用完整服务', icon: 'none' });
						 reject(err);
					 },
				 })
}

官网文件获取路径

javascript 复制代码
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
相关推荐
小小王app小程序开发5 小时前
盲盒小程序一番赏衍生玩法:魔王赏、非酋赏、狂欢赏差异化分析
小程序
2501_915106327 小时前
iOS App 测试工具全景分析,构建从开发调试到线上监控的多阶段工具链体系
android·测试工具·ios·小程序·uni-app·iphone·webview
头发还在的女程序员1 天前
基于JAVA语言的短剧小程序-抖音短剧小程序
java·开发语言·小程序
2501_916007471 天前
iOS 应用性能测试的工程化流程,构建从指标采集到问题归因的多工具协同测试体系
android·ios·小程序·https·uni-app·iphone·webview
源码_V_saaskw1 天前
JAVA国际版同城跑腿源码快递代取帮买帮送同城服务源码支持Android+IOS+H5
android·java·ios·微信小程序
tbit1 天前
fluwx 拉起小程序WXLog:Error:fail to load Keychain status:-25300, keyData null:1
flutter·ios·微信小程序
book多得1 天前
刷题专用微信小程序推荐
微信小程序·小程序
00后程序员张1 天前
iOS 抓不到包怎么办?从 HTTPS 解密、QUIC 排查到 TCP 数据流分析的完整解决方案
android·tcp/ip·ios·小程序·https·uni-app·iphone
技术与健康1 天前
微信小程序云开发实践:共享环境与LLM整合经验
微信小程序·小程序
老华带你飞2 天前
社区养老保障|智慧养老|基于springboot+小程序社区养老保障系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序·毕设·社区养老保障