赞
踩
1.微信官方文档 auth.code2Session | 微信开放文档
2.我们来实现这个登录功能, 直接上完整代码
controller
- <!-- 工具类-JSONUtil -->
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.7.13</version>
- </dependency>
- /**
- * 解密用户敏感数据
- *
- * @param encryptedData 明文,加密数据
- * @param iv 加密算法的初始向量
- * @param code 用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key
- * @return
- */
- @ApiOperation("登录")
- @GetMapping("/login")
- public Map decodeUserInfo(String encryptedData, String iv, String code) {
- Map map = new HashMap();
- //登录凭证不能为空
- if (code == null || code.length() == 0) {
- map.put("status", 0);
- map.put("msg", "code 不能为空");
- return map;
- }
- //小程序唯一标识 (在微信小程序管理后台获取)
- String wxspAppid = "xxxxxx";
- //小程序的 app secret (在微信小程序管理后台获取)
- String wxspSecret = "xxxxxx";
- //授权(必填)
- String grant_type = "authorization_code";
-
- // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
- //请求参数
- String params = "appid="+wxspAppid+"&secret="+wxspSecret+"&js_code="+code+"&grant_type="+grant_type;
- //发送请求
- String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
- //解析相应内容(转换成json对象)
- JSONObject json = JSONUtil.parseObj(sr);
- //获取会话密钥(session_key)
- String session_key = json.get("session_key").toString();
- //用户的唯一标识(openid)
- String openid = (String) json.get("openid");
-
- // 2、对encryptedData加密数据进行AES解密
- try {
- String result = WxAesUtils.decryptData(getURLDecoderString(encryptedData), session_key, getURLDecoderString(iv));
- if (null != result && result.length() > 0) {
- map.put("status", 1);
- map.put("msg", "解密成功");
-
- JSONObject userInfoJSON = JSONUtil.parseObj(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"));
- userInfo.put("unionId", userInfoJSON.get("unionId"));
- map.put("userInfo", userInfo);
- return map;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- map.put("status", 0);
- map.put("msg", "解密失败");
- return map;
- }
utils
- 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.List;
- import java.util.Map;
-
- public class HttpRequest {
-
- /**
- * 向指定URL发送GET方法的请求
- *
- * @param url
- * 发送请求的URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return URL 所代表远程资源的响应结果
- */
- public static String sendGet(String url, String param) {
- String result = "";
- BufferedReader in = null;
- try {
- String urlNameString = url + "?" + param;
- URL realUrl = new URL(urlNameString);
- // 打开和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()) {
- System.out.println(key + "--->" + map.get(key));
- }
- // 定义 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;
- }
-
- /**
- * 向指定 URL 发送POST方法的请求
- *
- * @param url
- * 发送请求的 URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return 所代表远程资源的响应结果
- */
- public static String sendPost(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
- // 打开和URL之间的连接
- URLConnection conn = realUrl.openConnection();
- // 设置通用的请求属性
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- 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()));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!"+e);
- e.printStackTrace();
- }
- //使用finally块来关闭输出流、输入流
- finally{
- try{
- if(out!=null){
- out.close();
- }
- if(in!=null){
- in.close();
- }
- }
- catch(IOException ex){
- ex.printStackTrace();
- }
- }
- return result;
- }
- }
- import org.apache.commons.codec.binary.Base64;
- import org.bouncycastle.jce.provider.BouncyCastleProvider;
-
- import javax.crypto.Cipher;
- import javax.crypto.spec.IvParameterSpec;
- import javax.crypto.spec.SecretKeySpec;
- import java.security.Key;
- import java.security.Security;
- import java.util.Arrays;
-
- /**
- * 微信通讯加解密类
- */
- public class WxAesUtils {
-
-
- public static void main(String[] args) {
- decryptData("bmdheU9pKVKVyJOH8CR3mqp4mEeKZ1YOuMsVxXJKjRdc47rolEoe85JKAVEWmP2hl4NZB66qxN/NHHGsy0PqCn7hS4cLKqTgERXcYO0dURt2JuLg1myhG+PYhi0AROwfJytGBv77u8yinmMfyyKx6lSegkqnlIJ6TBIDYe2LCvW3kRVDzNDeWT0hOaLiRI6n3TFQwI0b5Tiu48UbFTHDhAtJ6LaZY+wg+PdtrHDgjWtt46pinENV22GFt77a6iIhdT4GzaW7ln45HuENtzXJLR5yM7SwT2pxKMGEknJGJD3yf/DxnR6a8HpXrwxtXHJfDlUzNS+Af51fOS/Z52LpbtvRecoEz8KKUxJ9lpcK1HrO/RMw/iYf+ce1bu5VIpYyMjTNAoLdffZ7V0HGMrVJUGbQMqk7ZjdCk1eqMyPpuIOuektgKE7K5wHqeo3NVo7A",
- "6pOQ1+4ca2ATDaSg4gauVA==",
- "zzmYGLoLH548Vf0fdJHHvA==");
- }
-
- public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
- String data = null;
- try {
- data = new String(
- decryptOfDiyIV(
- Base64.decodeBase64(encryptDataB64),
- Base64.decodeBase64(sessionKeyB64),
- Base64.decodeBase64(ivB64)
- )
- );
- } catch (Exception e) {
- e.printStackTrace();
- }
- return data;
-
- }
-
- private static final String KEY_ALGORITHM = "AES";
- private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
- private static Key key;
- private static Cipher cipher;
-
- private static void init(byte[] keyBytes) {
- // 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
- int base = 16;
- if (keyBytes.length % base != 0) {
- int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
- byte[] temp = new byte[groups * base];
- Arrays.fill(temp, (byte) 0);
- System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
- keyBytes = temp;
- }
- // 初始化
- Security.addProvider(new BouncyCastleProvider());
- // 转化成JAVA的密钥格式
- key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
- try {
- // 初始化cipher
- cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 解密方法
- *
- * @param encryptedData 要解密的字符串
- * @param keyBytes 解密密钥
- * @param ivs 自定义对称解密算法初始向量 iv
- * @return 解密后的字节数组
- */
- private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
- byte[] encryptedText = null;
- init(keyBytes);
- try {
- cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
- encryptedText = cipher.doFinal(encryptedData);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return encryptedText;
- }
- }
- /**
- * 解码
- * @param str
- * @return
- */
- public static String getURLDecoderString(String str) {
-
- String result = "";
- if (null == str) {
- return "";
- }
- try {
- result = java.net.URLDecoder.decode(str, "GBK");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return result;
- }
获取到的用户信息:
{"nickName":"木笔","gender":0,"language":"zh_CN","city":"","province":"","country":"","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKDKIibHfOlhMmLib2tU491TpbTzvjHtw2TL38LM30ao5KRZL0A20PIeyhJ8ZGWMvHUDSabatHhic1PQ/132","watermark":{"timestamp":1652235161,"appid":"wx6db597cba4914b30"}}
- {
- "nickName":"木笔",
- "gender":0,
- "language":"zh_CN",
- "city":"",
- "province":"",
- "country":"",
- "avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKDKIibHfOlhMmLib2tU491TpbTzvjHtw2TL38LM30ao5KRZL0A20PIeyhJ8ZGWMvHUDSabatHhic1PQ/132",
- "watermark":{
- "timestamp":1652235161,
- "appid":"wx6db597cba4914b30"
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。