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

528 阅读2分钟

首先,我们需要在小程序的前端页面中获取用户的授权信息,以便在后端请求用户手机号码。前端代码如下:

// pages/index/index.js
Page({
  data: {
    userInfo: null,
    hasPhoneNumber: false,
    canIUse: wx.canIUse('button.open-type.getUserPhoneNumber') // 检查是否支持获取用户手机号
  },

  onLoad: function () {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              this.setData({
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

  getPhoneNumber: function () {
    // 判断是否支持获取用户手机号
    if (this.data.canIUse) {
      // 调用后端接口获取用户手机号
      wx.login({
        success: res => {
          if (res.code) {
            wx.request({
              url: 'https://example.com/api/getPhoneNumber', // 后端接口地址
              data: {
                code: res.code,
                encryptedData: this.data.userInfo.encryptedData, // 解密后的用户数据,用于校验用户身份
                iv: this.data.userInfo.iv // 解密算法的初始向量,用于校验用户身份
              },
              success: res => {
                if (res.data && res.data.phoneNumber) {
                  this.setData({
                    hasPhoneNumber: true,
                    phoneNumber: res.data.phoneNumber // 设置用户手机号到页面数据中
                  })
                } else {
                  wx.showToast({
                    title: '获取手机号失败',
                    icon: 'none'
                  })
                }
              }
            })
          } else {
            console.log('登录失败!' + res.errMsg)
          }
        }
      })
    } else {
      wx.showToast({
        title: '当前微信版本不支持获取用户手机号',
        icon: 'none'
      })
    }
  }
})

接下来,我们需要在后端服务器上处理前端发送的请求,并返回用户的手机号码。后端代码如下:

// UserController.java - 用户控制器类,处理获取用户手机号的请求
package com.example;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.*;
import java.util.*;
import com.example.entity.*; // 引入实体类包,用于操作数据库数据
import com.example.service.*; // 引入服务类包,用于处理业务逻辑
import com.example.utils.*; // 引入工具类包,用于处理加密解密等操作
@RestController // 使用@RestController注解,表示这是一个RESTful风格的控制器类
public class UserController {
  @Autowired // 自动注入服务类实例,用于处理业务逻辑
  private WxService wxService; // 微信小程序服务类实例,用于处理微信小程序相关业务逻辑
  @PostMapping("/api/getPhoneNumber") // 定义处理前端请求的方法,使用POST方式接收请求,路径为/api/getPhoneNumber,返回值为JSON格式数据
  public Map<String, Object> getPhoneNumber(@RequestParam("code") String code, @RequestParam("encryptedData") String encryptedData, @RequestParam("iv") String iv) { // 从请求参数中获取code、encryptedData和iv值,分别对应微信小程序登录时的临时登录码、解密后的用户数据和解密算法的初始向量,用于校验用户身份和解密用户数据(如果需要)
    Map<String, Object> result = new HashMap<>(); // 创建一个空的Map对象,用于存储返回给前端的数据结果
    try {
      // 根据code值查询数据库中的用户信息,并进行解密操作(如果需要)以获取用户的手机号码和其他相关信息,然后将这些信息存储到result中返回给前端页面显示或进行其他操作。具体实现过程请参考您的业务需求和技术选型。