流程图

创建授权按钮,向后台获取unionid

<template><view style="margin-top: 60%;">  <!-- <button type="default" open-type="getUserInfo" @getuserinfo='getuserinfo'>微信授权</button> --><view style="text-align: center;">申请获取你的公开信息(昵称,头像等)</view><buttonopen-type="getUserInfo"withCredentials="true"class="mc btn-auth"@getuserinfo="getUserInfo">授权登录</button></view></template><script>export default {data() {return {code:"",next:"",}},onLoad(e) {this.next=e.next;},onReady() {},methods: {getUserInfo() {// let = {};// var that= thislet _this = this;uni.login({provider: "weixin",success: (res) => {let code = res.code;uni.getUserInfo({provider: "weixin",lang: "zh_CN",success: function(res) {uni.request({url: getApp().globalData.url+'/wechat/login', data: {rawData:res.rawData,//用户信息signature:"111",code: code,encryptedData:res.encryptedData,iv:res.iv,},method:'POST',header: {'Content-Type': 'application/json',},success: (res) => {if(res.data.status==200){// 添加缓存uni.setStorage({key: 'unionId',data: res.data.data.userInfo.unionId,success: function () {console.log('缓存unionId 成功');}});uni.setStorage({key: 'nickName',data: res.data.data.userInfo.nickName,success: function () {console.log('缓存昵称 成功');}});if(_this.next.length>0){uni.redirectTo({//跳转页面url:_this.next,})  }else{// 返回上一个页面uni.navigateBack()}}else{uni.showToast({title:"授权失败,请重新在试" })}}, fail: function(err) {uni.showToast({title:"授权失败,请重新在试" })},})},fail: function(err) {uni.showModal({title: "提示",content: "需要通过授权才能继续,请重新点击并授权!",showCancel: false,success: function (res) {if (res.confirm) {} else if (res.cancel) { return}         }});},});},});}}}</script><style>
</style>

后台处理

 /*** 微信授权,获取微信服务器unionId等等信息* @param loginDTO* @return*/@PostMapping("/login")public Object login(@RequestBody  LoginDTO loginDTO){Map map = new HashMap();try{//获取openid和session_keySessionDTO sessionDTO=wechatAdapter.jscode2session(loginDTO.getCode());try {//对encryptedData加密数据进行AES解密String result = AesCbcUtil.decrypt(loginDTO.getEncryptedData(), sessionDTO.getSessionKey() ,loginDTO.getIv(), "UTF-8");
//                System.out.println(result);if (null != result && result.length() > 0) {map.put("status", 1);map.put("msg", "解密成功");JSONObject userInfoJSON = JSON.parseObject(result);Map userInfo = new HashMap();userInfo.put("openId", userInfoJSON.get("openId"));userInfo.put("nickName", userInfoJSON.get("nickName"));userInfo.put("gender", userInfoJSON.get("gender"));userInfo.put("city", userInfoJSON.get("city"));userInfo.put("province", userInfoJSON.get("province"));userInfo.put("country", userInfoJSON.get("country"));userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));// 解密unionId & openId;userInfo.put("unionId", userInfoJSON.get("unionId"));map.put("userInfo", userInfo);} else {map.put("status", 0);map.put("msg", "解密失败");}} catch (Exception e) {return ResultDTO.fail(CommonErrorCode.Wechat_SIGNATURE_ERROR);}return ResultDTO.ok(map);}catch (ErrorCodeException e){return ResultDTO.fail(e);}catch (Exception e){System.out.println(e.toString());return ResultDTO.fail(CommonErrorCode.UNKOWN_ERROR);}}

获取openid和session_key

   @Value("${wechat.appid}")private String appid;@Value("${wechat.secret}")private String secret;public SessionDTO jscode2session(String code) {String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().addHeader("content-type", "application/json").url(String.format(url, appid, secret, code)).build();try {Response execute = okHttpClient.newCall(request).execute();if (execute.isSuccessful()) {SessionDTO sessionDTO = JSON.parseObject(execute.body().string(), SessionDTO.class);return sessionDTO;} else {throw new ErrorCodeException(CommonErrorCode.OBTAIN_OPENID_ERROR);}} catch (IOException e) {throw new ErrorCodeException(CommonErrorCode.OBTAIN_OPENID_ERROR);}}

解密类

package com.fusdom.utils;import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;public class AesCbcUtil {static {//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/Security.addProvider(new BouncyCastleProvider());}/*** AES解密** @param data           //密文,被加密的数据* @param key            //秘钥* @param iv             //偏移量* @param encodingFormat //解密后的结果需要进行的编码* @return* @throws Exception*/public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
//        initialize();//被加密的数据byte[] dataByte = Base64.decodeBase64(data);//加密秘钥byte[] keyByte = Base64.decodeBase64(key);//偏移量byte[] ivByte = Base64.decodeBase64(iv);try {Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");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, encodingFormat);return result;}return null;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidParameterSpecException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (InvalidAlgorithmParameterException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}}

LoginDTO 实体类

package com.fusdom.DTO;/*** Created by codedrinker on 2018/11/24.*///这里的数据根据文档创建的
public class LoginDTO {// 用户信息原始数据private String rawData;// 用于验证用户信息是否被篡改过private String signature;// 用户获取 session_key 的 codeprivate String code;private String encryptedData;private  String iv;public String getEncryptedData() {return encryptedData;}public void setEncryptedData(String encryptedData) {this.encryptedData = encryptedData;}public String getIv() {return iv;}public void setIv(String iv) {this.iv = iv;}public String getRawData() {return rawData;}public void setRawData(String rawData) {this.rawData = rawData;}public String getSignature() {return signature;}public void setSignature(String signature) {this.signature = signature;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}}

SessionDTO  实体类

package com.fusdom.DTO;import com.alibaba.fastjson.annotation.JSONField;/*** Created by codedrinker on 2018/11/24.*/public class SessionDTO {private String openid;@JSONField(name = "session_key")private String sessionKey;public String getOpenid() {return openid;}public void setOpenid(String openid) {this.openid = openid;}public String getSessionKey() {return sessionKey;}public void setSessionKey(String sessionKey) {this.sessionKey = sessionKey;}
}

springboot微信小程序 获取微信unionid相关推荐

  1. 微信小程序-获取微信收货地址

    微信小程序获取微信收货地址 文章目录 微信小程序获取微信收货地址 一.在小程序管理后台( 小程序管理后台),「开发」-「开发管理」-「接口设置」中自助开通该接口权限. 二.开通之后直接调用接口. // ...

  2. 微信小程序获取微信公众号文章2

    微信小程序获取微信公众号文章2 前面介绍了一篇微信小程序打开微信公众号中的文章实战教程,主要介绍了实现的具体原理,但是实际去做的时候,发现了更多的坑,所以这里再补充一下. 原先的思路是不完整的 原先我 ...

  3. .Net之微信小程序获取用户UnionID

    前言: 在实际项目开发中我们经常会遇到账号统一的问题,如何在不同端或者是不同的登录方式下保证同一个会员或者用户账号唯一(便于用户信息的管理).这段时间就有一个这样的需求,之前有个客户做了一个微信小程序 ...

  4. 微信小程序获取微信运动数据并解密

    官方API 官方API 步骤 1,APP端拉起微信小程序 2,小程序端获取微信运动数据 3,后台解密获取的微信运动数据 实现 1,APP端调起微信小程序 准备工作: 1)微信开放平台,微信公众平台注册 ...

  5. 微信小程序获取微信头像、微信昵称

    微信小程序获取头像昵称 <template><view class="top-user"><view class="top-content& ...

  6. 小程序步数解密php,微信小程序--获取微信运动步数的实例代码

    如今运动计步很火,不管是蚂蚁森林,仍是微信上都很火爆,本文介绍了微信小程序微信运动步数的实例代码,分享给你们php 思路:wx.login获取的code请求获取的session_key,wx.getW ...

  7. php 小程序 运动步数_微信小程序获取微信运动步数的实例代码

    现在运动计步很火,无论是蚂蚁森林,还是微信上都很火爆,本文介绍了微信小程序微信运动步数的实例代码,分享给大家 微信小程序API-微信运动 https://mp.weixin.qq.com/debug/ ...

  8. 微信小程序获取微信名和头像登录

    小程序获取用户信息使用 wx.getUserProfile()方法 wx.getUserProfile()方法的用处:获取用户信息,页面上有点击事件button后才可以调用,每次请求都会弹出授权窗口, ...

  9. php获取微信uninoid_微信小程序获取用户unionId

    unionId 一个微信开放平台下的相同主体的App.公众号.小程序的unionid是相同的,这样就可以锁定是不是同一个用户 微信针对不同的用户在不同的应用下都有唯一的一个openId, 但是要想确定 ...

  10. 微信小程序——获取用户unionId

    1.操作步骤 1)获取code 2)获取openid 3)获取access_token 4)获取unionid 2.在获取用户unionid过程中有遇到任何问题或者不明白的地方,可以添加我的微信进行咨 ...

最新文章

  1. android9怎样适配nfc,android – 如何使用NFC动作
  2. PCM设备能在公网使用吗?
  3. linux的bash脚本
  4. 河南省2020年计算机高考真题,2020年最新版对口高考试卷(计算机).docx
  5. 【实践】Embedding在腾讯应用宝的推荐实践
  6. 一个人开始变富时,会有这4个征兆,坚持下去,路越走越宽
  7. 简单的横向ListView实现(version 4.0)
  8. 电商价格战 谁才是最大受益者
  9. 码农谷 找出N之内的所有完数
  10. mybatis官网下载
  11. android axis2 webservice实例,Axis2创建WebService实例.doc
  12. 终于解决了html中img标签图片不显示问题
  13. 年轻时放纵享乐,不要指望年老时一念向善
  14. 【论文浅读】《Deep Pyramidal Residual Networks for Spectral–Spatial Hyperspectral Image Classification》
  15. 服务器不改变系统怎么清理c盘,服务器c盘满了怎么清理(清理c盘最简单的方法)...
  16. Latex排版,表格标题总是出现在下方的解决方案
  17. Fleck For Web Socket
  18. IE浏览器提示无法显示网页的三种情况
  19. 手把手教你开发一款简单的AR软件
  20. linux下做笔记的软件下载,Write一款梦幻般的Linux手机笔记应用程序

热门文章

  1. Java学习需要多长时间?
  2. 显卡天梯图2022年4月 最新显卡性能排行天梯图
  3. linux oracle 强制覆盖_赤兔Oracle数据库恢复软件下载-赤兔Oracle数据库恢复软件v11.6免费版...
  4. 小米进军欧洲智能手机市场:一面是狂欢,一面是考验
  5. 445端口爆破试验 net use IPC$
  6. 【敏捷开发每日一贴】测试驱动开发
  7. ID2021安装教程【科技猿说】
  8. php tp框架,TP框架
  9. GISAXS和GIWAXS的分析
  10. Cadence输出Gerber文件