微信小程序一次授权获取用户手机号及用户信息

person 少陵野老    watch_later 2024-07-10 20:30:04
visibility 160    class 小程序,微信授权    bookmark 专栏

在微信小程序中,要一步获取用户信息及手机号,您需要通过微信小程序提供的 wx.loginwx.getUserProfile 接口来实现。这需要用户授权获取其个人信息和手机号。以下是详细步骤:

1. 配置 app.json

首先,确保在 app.json 中配置了相关权限:

{
  "pages": [
    "pages/index/index"
  ],
  "window": {
    "navigationBarTitleText": "微信小程序"
  },
  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  },
  "requiredPrivateInfos": [
    "getPhoneNumber"
  ]
}

2. 获取用户信息和手机号

在小程序前端,通过 wx.getUserProfile 获取用户信息,通过 wx.login 获取临时登录凭证(code),再通过 wx.requestcodeencryptedData 发送到服务器解密用户手机号。

前端代码

pages/index/index.js 中:

Page({
  data: {
    userInfo: null,
    phoneNumber: null
  },

  onLoad: function() {
    // 在页面加载时检查用户是否已经授权
    this.checkUserAuthorization();
  },

  checkUserAuthorization() {
    const that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserProfile({
            desc: '获取用户信息',
            success: function(res) {
              that.setData({
                userInfo: res.userInfo
              });
            }
          });
        }
      }
    });
  },

  getUserInfoAndPhoneNumber(e) {
    const that = this;
    wx.login({
      success: function(loginRes) {
        wx.getUserProfile({
          desc: '获取用户信息',
          success: function(userRes) {
            wx.request({
              url: 'https://你的后端接口地址',
              method: 'POST',
              data: {
                code: loginRes.code,
                iv: e.detail.iv,
                encryptedData: e.detail.encryptedData,
                userInfo: userRes.userInfo
              },
              success: function(response) {
                that.setData({
                  userInfo: userRes.userInfo,
                  phoneNumber: response.data.phoneNumber
                });
              }
            });
          }
        });
      }
    });
  }
});

pages/index/index.wxml 中添加按钮:

<view>
  <button open-type="getPhoneNumber" bindgetphonenumber="getUserInfoAndPhoneNumber">获取用户信息及手机号</button>
  <view wx:if="{{userInfo}}">
    <image src="{{userInfo.avatarUrl}}" />
    <text>{{userInfo.nickName}}</text>
    <text>手机号:{{phoneNumber}}</text>
  </view>
</view>

后端代码

在服务器端,通过解密微信返回的数据获取用户手机号,这里以 Node.js 为例:

const axios = require('axios');
const crypto = require('crypto');

async function getPhoneNumber(req, res) {
  const { code, iv, encryptedData, userInfo } = req.body;

  // 获取 session_key
  const sessionData = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
    params: {
      appid: '你的appid',
      secret: '你的secret',
      js_code: code,
      grant_type: 'authorization_code'
    }
  });

  const session_key = sessionData.data.session_key;

  // 解密
  let decodedData;
  try {
    const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(session_key, 'base64'), Buffer.from(iv, 'base64'));
    decipher.setAutoPadding(true);
    decodedData = decipher.update(Buffer.from(encryptedData, 'base64'), 'binary', 'utf8');
    decodedData += decipher.final('utf8');
    decodedData = JSON.parse(decodedData);
  } catch (err) {
    res.status(500).send({ error: '解密失败' });
    return;
  }

  res.send({ phoneNumber: decodedData.phoneNumber, userInfo: userInfo });
}

module.exports = { getPhoneNumber };

3. 结果展示

在用户点击按钮授权后,小程序会通过 wx.loginwx.getUserProfile 获取用户信息和临时登录凭证,并通过 wx.request 将这些数据发送到服务器。服务器通过微信提供的接口和解密算法获取用户手机号并返回给前端进行展示。

这样,实现了一步获取用户信息及手机号的功能。通过这种方法,用户只需要一次授权即可获取到所需的信息,提高了用户体验和操作的便利性。

评论区
评论列表
menu