微信小程序获取用户绑定手机号码完整版

一、准备阶段

创建小程序项目(测试号即可)
创建Java后台项目(此处为SpringBoot 普通项目)

二、前端代码

WXML 代码

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    
 
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
  <label>{{phone}}</label>
  <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"> 获取手机号码</button>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>

JS 代码

//index.js
//获取应用实例
const app = getApp()
 
Page({
  data: {
    motto: ‘Hello World‘,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse(‘button.open-type.getUserInfo‘),
    phone:""
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: ‘../logs/logs‘
    })
  },
  onLoad: function() {
    var  phone = wx.getStorageSync(‘phone‘);
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    this.setData({
      phone: phone
    });
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getPhoneNumber: function (e) {
    console.log(e.detail.iv);
    console.log(e.detail.encryptedData);
    wx.login({
      success: res => {
        console.log(res.code);
        wx.request({
          url: ‘http://192.168.1.28:8070/oauth‘,
          data: {
            ‘encryptedData‘: e.detail.encryptedData,
            ‘iv‘: e.detail.iv,
            ‘codes‘: res.code
          },
          method: ‘GET‘, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          header: {
            ‘content-type‘: ‘application/json‘
          }, // 设置请求的 header
          success: function (res) {
            wx.setStorageSync(‘phone‘, res.data.phoneNumber);
            wx.showToast({
              title: "号码为:"+res.data.phoneNumber,
              icon: ‘none‘
            })
          },
          fail: function (err) {
            console.log(err);
          }
        })
      }
    })
  }
})

三、后台代码

导入依赖

<dependency>
   <groupId>org.bouncycastle</groupId>
   <artifactId>bcprov-jdk16</artifactId>
   <version>1.46</version>
</dependency>

controller

package com.aes.aes.controller;
 
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
 
 
/**
 * 微信小程序code换取微信用户信息
 * @author ban__dian
 *
 */
@Controller
public class HomeController {
    private static Logger logger = LoggerFactory.getLogger(HomeController.class);
    /**
     * 获取微信小程序用户openid等信息
     * @param encryptedData 加密数据
     * @param iv 加密算法初始向量
     * @param codes 微信小程序code码
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return String
     * @throws Exception
     */
    @GetMapping("/oauth")
    @ResponseBody
    public String wxOauth(String encryptedData,String iv,String codes,HttpServletRequest request,HttpServletResponse response) throws Exception{
        Object res = getPhoneNumber(encryptedData,codes,iv);
        logger.info(request.toString());
        return res.toString();
    }
 
    public Object getPhoneNumber(String encryptedData, String code, String iv) {
        //传入code后然后获取openid和session_key的,把他们封装到json里面
        JSONObject json = getSessionKeyOropenid(code);
        String session_key = "";
        if (json != null) {
 
            session_key = json.getString("session_key");
            // 被加密的数据
            byte[] dataByte = Base64.decode(encryptedData);
            // 加密秘钥
            byte[] keyByte = Base64.decode(session_key);
            // 偏移量
            byte[] ivByte = Base64.decode(iv);
            try {
                // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
                int base = 16;
                if (keyByte.length % base != 0) {
                    int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                    byte[] temp = new byte[groups * base];
                    Arrays.fill(temp, (byte) 0);
                    System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                    keyByte = temp;
                }
                // 初始化
                Security.addProvider(new BouncyCastleProvider());
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
                AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
                parameters.init(new IvParameterSpec(ivByte));
                cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
                byte[] resultByte = cipher.doFinal(dataByte);
                if (null != resultByte && resultByte.length > 0) {
                    String result = new String(resultByte, "UTF-8");
                    return JSONObject.parseObject(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    /**
     * 获取微信小程序 session_key 和 openid
     *
     * @param code 调用微信登陆返回的Code
     * @return
     */
    public static JSONObject getSessionKeyOropenid(String code) {
        //微信端登录code值
        String wxCode = code;
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";  //请求地址 https://api.weixin.qq.com/sns/jscode2session
        Map<String, String> requestUrlParam = new HashMap<String, String>();
        requestUrlParam.put("appid", "wx2f7b849acf031253");  //开发者设置中的appId
        requestUrlParam.put("secret", "e8f5e6386b2a221a6760501263b93f7d"); //开发者设置中的appSecret
        requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");    //默认参数 authorization_code
 
        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
        return jsonObject;
    }
 
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
 
        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();
 
        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }
 
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
 
 
 
}

需要修改的地方

微信小程序获取用户绑定手机号码完整版

完成!

【文章转载自:https://blog.csdn.net/qq_39471272/article/details/87272170】

微信小程序获取用户绑定手机号码完整版

上一篇:java之路,IO操作


下一篇:微信群里一道六年级数学题,求阴影面积,那我只能用python代码了