一、微信小程序中app.js中:

    wx.login({
success: res => {
if(res.code){
var code = res.code;
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: res => {
var encryptedData = res.encryptedData;
var iv = res.iv;
wx.request({
url: 'http://localhost:9001/method/decodeUserInfo',//发送到开发者服务器
method: 'post',
data: { code: code, encryptedData:encryptedData,iv:iv },
dataType:'json',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (rs) {
console.log(rs);
},
fail: function (e) {
console.log(e);
wx.showToast({
title: '网络异常!',
duration: 2000
});
}
});
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}else{
console.log("未授权");
}
}
})
}
}
})

二、开发者服务器中进行接收数据并解密数据

1.控制器中代码:

  @RequestMapping("/method/decodeUserInfo")
public String decodeUserInfo(HttpServletRequest request, HttpServletResponse response)throws Exception{
response.setHeader("Access-Control-Allow-Origin", "*");
String code = request.getParameter("code");
String encryptedData = request.getParameter("encryptedData");
String iv = request.getParameter("iv");
if(code.equals("") || code == null){return "failed";}
if(encryptedData.equals("") || encryptedData == null){return "failed";}
if(iv.equals("") || iv == null){return "failed";} //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+APPSECRET+"&js_code="+code+"&grant_type=authorization_code";
String result = HttpHandler.sendGet(url);
//解析相应内容(转换成json对象)
JSONObject json = JSONObject.fromObject(result);
//获取会话密钥(session_key)
String session_key = json.get("session_key").toString();
//用户的唯一标识(openid)
String openid = json.get("openid").toString();
System.out.println("session_key:"+session_key);
System.out.println("openid:"+openid); //////////////// 2、对encryptedData加密数据进行AES解密其中包含这openid和unionid ////////////////
String data = AesCbcUtil.decrypt(encryptedData,session_key,iv,"UTF-8");
JSONObject jsonObject = JSONObject.fromObject(data);
String unionid = jsonObject.get("unionId").toString();
return unionid;
}
2.HttpHandler类中sendGet方法:
  /**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) { }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
3.AesCbcUtil中decrypt方法:
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; /**
* Created by yfs on 2018/2/6.
* <p>
* AES-128-CBC 加密方式
* 注:
* AES-128-CBC可以自己定义“密钥”和“偏移量“。
* AES-128是jdk自动生成的“密钥”。
*/
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;
}
}

完成上面的几步就能成功实现微信小程序获得unionid.

 

微信小程序获得unionid的更多相关文章

  1. 微信小程序获取unionid

    链接:https://blog.csdn.net/a493001894/article/details/80323403

  2. 微信小程序unionid获取问题

    微信小程序使用login获取unionid时可能获取不到,原因可能是该微信账号没有关注小程序所在公众号等.但在微信小程序中使用微信注册,必须要用unionid注册时,大部分用户就会因此无法注册成功. ...

  3. 微信小程序无法获取UnionId的情况及处理

    问题背景:做了微信小程序,一切都还正常,但是最后体验版放出去时,却发现很多用户无法绑定用户,后台返回:参数非法.经过多方排查,发现是微信拿到的code请求返回的数据里没有UnionId,也就是接口返回 ...

  4. 原创:微信小程序java实现AES解密并获取unionId

    来自:微信小程序联盟 如果大家使用小程序的同时还在使用公众号的话,可能会用到unionId这种功能,由于公司业务需要,我们需要使用unionId,具体使用方法,请参考微信开放平台的说明,但是在微信小程 ...

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

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

  6. 微信小程序无法获取到unionId(专业踩坑20年)

    UnionID机制说明如果开发者拥有多个移动应用.网站应用.和公众帐号(包括小程序),可通过unionid来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用.网站应用和公众帐号(包括小程 ...

  7. 微信小程序之用户数据解密(七)

    [未经作者本人同意,请勿以任何形式转载] 经常看到有点的小伙伴在群里问小程序用户数据解密流程,所以打算写一篇关于小程序用户敏感数据解密教程: 加密过程微信服务器完成,解密过程在小程序和自身服务器完成, ...

  8. 微信小程序常见问题集合(长期更新)

    最新更新: 新手跳坑系列:推荐阅读:<二十四>request:fail错误(含https解决方案)(真机预览问题 跳坑指南<七十>如何让微信小程序服务类目审核通过 跳坑六十九: ...

  9. 微信小程序产品定位及功能介绍

    产品定位及功能介绍 微信小程序是一种全新的连接用户与服务的方式,它可以在微信内被便捷地获取和传播,同时具有出色的使用体验. 小程序注册 注册小程序帐号 在微信公众平台官网首页(mp.weixin.qq ...

随机推荐

  1. LinqToSQL2

    扩展方法: 扩展方法是C#3.0的新特性,可以通过为已知类型添加新方法来到到扩展类型的目的,同时不需对此类型做任何改动. 重点记住的是,定义为静态方法的扩展方法只能在通过using指令显示地将名称空间 ...

  2. react的嵌套组件

    react没有vue插槽的概念,但是有嵌套组件,可以用嵌套组件实现类似插槽的功能.下例中,color,name,btn相当于具名插槽,children相当于匿名插槽. import React fro ...

  3. O046、掌握Cinder 的设计思想

    参考https://www.cnblogs.com/CloudMan6/p/5578673.html   从 volume  创建流程看 cinder-* 子服务如何协同工作   对于 Cinder  ...

  4. Editplus code

    网上一大堆,垃圾也是一大堆,保留一个真正的,提高效率 原文链接:https://blog.csdn.net/anhldd/article/details/85088715 Vovan 3AG46-JJ ...

  5. 一个简单的创建xml方式

    , matnr LIKE mara-matnr , maktx LIKE makt-maktx , END OF itab_matnr . , class LIKE m_wwgha-class,&qu ...

  6. Linux下的用户和用户组,文件权限:chown和chmod

    如下图所示,root权限下新建一个用户MasterBai, /etc/passwd文件中新加入一些信息 这个文件中,记录了该服务器的用户信息,如下图红色框起来的用户,就是我们自己创建的用户,而起来2- ...

  7. (九)How to use the audio gadget driver

    Contents [hide]  1 Introduction 2 Audio Gadget Driver 1.0 2.1 Enabling the audio gadget driver 2.2 U ...

  8. 【2017-04-19】C#中String.Format格式使用

    例子: int a =9; string s= a.ToString("000"); Console.Write(s); 打印出来就是009 C#格式化数值结果表 字符 说明 示例 ...

  9. 论文笔记:Integrated Object Detection and Tracking with Tracklet-Conditioned Detection

    概要 JiFeng老师CVPR2019的另一篇大作,真正地把检测和跟踪做到了一起,之前的一篇大作FGFA首次构建了一个非常干净的视频目标检测框架,但是没有实现帧间box的关联,也就是说没有实现跟踪.而 ...

  10. @font-face字图标问题

    链接:http://www.exp99.com/htmlcss/htmlcss_229.html