一、准备阶段

创建小程序项目(测试号即可)
创建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.userInfothis.setData({userInfo: res.userInfo,hasUserInfo: true})}})}this.setData({phone: phone});},getUserInfo: function(e) {console.log(e)app.globalData.userInfo = e.detail.userInfothis.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, CONNECTheader: {'content-type': 'application/json'}, // 设置请求的 headersuccess: 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")@ResponseBodypublic 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/jscode2sessionMap<String, String> requestUrlParam = new HashMap<String, String>();requestUrlParam.put("appid", "wx2f7b849acf031253");  //开发者设置中的appIdrequestUrlParam.put("secret", "e8f5e6386b2a221a6760501263b93f7d"); //开发者设置中的appSecretrequestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的coderequestUrlParam.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;}}

需要修改的地方

完成!

微信小程序获取用户绑定手机号码完整版(转载)相关推荐

  1. 微信小程序获取用户手机号码,Java后台servlet解密(微信小程序调用微信支付也是大致的流程)

    本篇记录说明 微信小程序获取用户手机号码,Java后台servlet解密(微信小程序调用微信支付也是大致的流程,详细内容可私信交流) (第一次写博客,写得不好的地方见谅,面向新手,大佬请无视,不喜勿喷 ...

  2. 微信小程序获取用户信息

    微信小程序获取用户信息 微信小程序获取用户信息接口做了调整: 2021年4月28日24时后发布的小程序新版本,无法通过wx.getUserInfo与获取用户个人信息(头像.昵称.性别与地区),将直接获 ...

  3. 微信小程序python解析获取用户手机号_微信小程序获取用户手机号

    获取微信用户绑定的手机号,需先调用wx.login接口. 小程序获取code. 后台得到session_key,openid. 组件触发getPhoneNumber 因为需要用户主动触发才能发起获取手 ...

  4. 微信小程序 error 用户绑定的手机号需要验证,请在客户端完成短信

    微信小程序 error 用户绑定的手机号需要验证,请在客户端完成短信 第一步在电脑上点编译 第二步点击预览 再点击自动预览 第三步打开手机上的小程序确认授权 输入短信验证码 之后就可以运行了 我点二维 ...

  5. 微信小程序-获取用户位置(经纬度+所在城市)

    微信小程序-获取用户位置(经纬度+所在城市) 文章目录 微信小程序-获取用户位置(经纬度+所在城市) 一.目标 二.实现思路 三.实现步骤 3.1 用到的接口函数 3.2 具体步骤 3.2.1 创建界 ...

  6. 微信小程序获取用户手机号--官方示例

    微信小程序获取用户手机号–官方示例 https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNu ...

  7. 微信小程序 获取用户信息并保存登录状态

    微信小程序 获取用户信息并保存登录状态:http://www.360doc.com/content/18/0124/11/9200790_724662071.shtml 转载于:https://www ...

  8. 微信小程序获取用户信息-头像、昵称......

    微信小程序获取用户信息-头像.昵称等,并出现弹窗提示授权 目录 微信小程序获取用户信息-头像.昵称等,并出现弹窗提示授权 1.wx.getUserProfile文档 2.代码演示 3.演示过程(图示) ...

  9. 微信公众号/微信小程序获取用户信息以及推送微信模版消息_MQ

    微信公众号/微信小程序获取用户信息以及推送微信模版消息_MQ 一.获取用户信息 1.首先我们需要了解什么是微信用户的OpenID 在关注者与公众号产生消息交互后,公众号可获得关注者的OpenID(加密 ...

最新文章

  1. 与后台通讯,首先要了解AMF协议
  2. Ubuntu 12.10 拨号上网及停用方法
  3. PyTorch分布式训练
  4. 动态添加综合布局---动态添加控件及将某XML动态加入到Activity显示(续)
  5. python requests text content_python requests的content和text方法的区别
  6. MxNet 模型转Tensorflow pb模型
  7. 聚类 | 超详细的性能度量和相似度方法总结
  8. docker镜像制作(一)
  9. 程会玩 | 在.NET Core里操作Git
  10. oracle之数据处理之其他数据库对象练习
  11. php转换excel文件怎么打开方式,用PHP将mysql数据表转换为excel文件格式_php
  12. Web后端学习笔记Flask(3)模板 实例
  13. Java中的HashCode(1)之hash算法基本原理
  14. 解决HP t5335z瘦客户机休眠问题
  15. 游戏筑基开发之printf及利用一维数组输出杨辉三角
  16. java技术学习路线
  17. Changer常用的软件
  18. 【机器人学、机器人控视觉与控制】四足机器人MATLAB仿真
  19. 探索瑞芯微RKNanoD芯片获索尼音箱,采用无线连接稳定无延迟
  20. c语言程序画正八边形,用少儿编程绘制一个正九边形

热门文章

  1. Windows下利用Ghost32一次性完成U盘版PE的制作
  2. Genesis LineHooks特殊指令
  3. [数据库基础篇]——关系数据库
  4. 2019携程技术峰会完美落幕
  5. 字符串 与格式化与基本运算
  6. 魅族16php7.3系统,魅族 16s更新Flyme 7.3稳定版 加入DC软件调光
  7. 涉密计算机能不能链接打印机,涉密打印机与涉密计算机之间是怎么连接的
  8. Android OpenCV实现图片叠加,水印
  9. 异常检测阅读笔记《Inpainting Transformer for Anomaly Detection》CVPR 2021
  10. 已经31岁了,阿里P6还有必要去吗?