uniapp微信小程序开发测试获取手机号码

先申请测试号

注意认证但是没有完全认证不要试测试号解密如下

总结我自己的两大坑

1.官网的WXBizDataCrypt需要导入crypto要提前下载但是试了很多次没有效果重新编写这个。将crypto库换成crypto-js库

2.我一直在尝试用下有下面这个界面的测试号不行获取不到用户的code还是啥忘记了s

新建WXBizDataCrypt.js官网也有也可以直接负责下面的内容

javascript 复制代码
import CryptoJS from 'crypto-js';

class WXBizDataCrypt {
  constructor(appId, sessionKey) {
    this.appId = appId;
    this.sessionKey = sessionKey;
  }

  decryptData(encryptedData, iv) {
    // 确保 encryptedData 和 iv 都是 Base64 编码的字符串
    const sessionKey = CryptoJS.enc.Base64.parse(this.sessionKey);
    const encryptedBuffer = CryptoJS.enc.Base64.parse(encryptedData);
    const ivBuffer = CryptoJS.enc.Base64.parse(iv);

    try {
      // 使用 AES 解密
      const decrypted = CryptoJS.AES.decrypt(
        { ciphertext: encryptedBuffer },
        sessionKey,
        {
          iv: ivBuffer,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7,
        }
      );

      // 将解密后的数据转换为 UTF-8 字符串
      const decoded = decrypted.toString(CryptoJS.enc.Utf8);

      // 解析 JSON 数据
      const result = JSON.parse(decoded);

      // 检查解密结果中的 App ID
      if (result.watermark.appid !== this.appId) {
        throw new Error('Illegal Buffer: App ID mismatch');
      }

      return result;
    } catch (err) {
      console.error('解密失败', err);
      throw new Error('Illegal Buffer: ' + err.message);
    }
  }
}

export default WXBizDataCrypt;

npm 下载 crypto-js:将node_modules中 crypto-js文件夹中的 crypto-js.js复制到WXBizDataCrypt同级目录

接下来在生成按钮

html 复制代码
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
	<view class="wx_text">微信授权登录</view>
</button>

接下来在第一张图片中的appid与AppSecret(小程序密钥)复制下来

typescript 复制代码
getPhoneNumber(e) {
		    uni.login({
		        provider: 'weixin', // 使用微信登录
		        success: (res) => {
		            uni.request({
		                url: 'https://api.weixin.qq.com/sns/jscode2session',
		                method: 'GET',
		                data: {
		                    appid: "appid自己的",
		                    secret: "AppSecret(小程序密钥)复制下来",
		                    js_code: res.code, // wx.login 登录成功后的code  
		                    grant_type: 'authorization_code',
		                },
		                success: (res) => {
		                    console.log('Request success:', res);
		                    if (res.data && res.data.session_key) {
		                        let pc = new WXBizDataCrypt('appid自己的', res.data.session_key);
		                        try {
		                            let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
		                            console.log('手机号码信息', data);
		                        } catch (err) {
		                            console.error('解密失败', err);
		                        }
		                    } else {
		                        console.error('未能获取 session_key:', res);
		                    }
		                },
		                fail: (err) => {
		                    console.error('Request failed:', err);
		                }
		            });
		        },
		        fail: (err) => {
		            console.error('Login failed:', err);
		        }
		    });
		}

简写的方法

typescript 复制代码
getPhoneNumber(e) {
				console.log(e)
				// 用户同意授权,拿到code去获取手机号
				uni.login({
					provider: 'weixin', //使用微信登录
					success: (res) => {
						uni.request({
							url: 'https://api.weixin.qq.com/sns/jscode2session',
							method: 'GET',
							data: {
								appid:"appid自己的",
								secret:"ppSecret(小程序密钥)复制下来",
								js_code: res.code, //wx.login 登录成功后的code  
								grant_type: 'authorization_code',
							},
							success: (res) => {
								let pc = new WXBizDataCrypt('appid自己的', res.data.session_key);
								
								try {
								  let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
								  console.log('手机号码信息', data);
								} catch (err) {
								  console.error('解密失败', err);
								}
							}
						});
					}
				})
		
		}
相关推荐
宁夏雨科网4 小时前
文具办公用品小程序商城,开发一个难吗
小程序·商城小程序·文具小程序·文具商城
Rysxt_8 小时前
UniApp获取安卓系统权限教程
android·uni-app
说私域11 小时前
开源链动2+1模式商城小程序在深度分销数字化转型中的应用研究
人工智能·小程序·开源·流量运营·私域运营
咖啡の猫12 小时前
微信小程序案例 - 自定义 tabBar
微信小程序·小程序·notepad++
咖啡の猫12 小时前
微信小程序全局数据共享
微信小程序·小程序
桐溪漂流13 小时前
微信小程序cli脚本预览上传
微信小程序·小程序
咖啡の猫13 小时前
微信小程序使用 npm 包
微信小程序·小程序·npm
说私域13 小时前
开源链动2+1模式商城小程序的营销技术与私域运营策略研究
人工智能·小程序·开源·流量运营·私域运营
木子啊13 小时前
ProCamera 智能水印相机解决方案 (UniApp)
数码相机·uni-app·水印相机·小程序水印
木子啊13 小时前
Uni-app跨页面通信三剑客
前端·uni-app·传参