当前位置:   article > 正文

微信小程序实现用户登录授权java代码_java微信小程序登录源码

java微信小程序登录源码

1.微信官方文档 auth.code2Session | 微信开放文档

2.我们来实现这个登录功能, 直接上完整代码

 controller

  1. <!-- 工具类-JSONUtil -->
  2. <dependency>
  3. <groupId>cn.hutool</groupId>
  4. <artifactId>hutool-all</artifactId>
  5. <version>5.7.13</version>
  6. </dependency>
  1. /**
  2. * 解密用户敏感数据
  3. *
  4. * @param encryptedData 明文,加密数据
  5. * @param iv 加密算法的初始向量
  6. * @param code 用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key
  7. * @return
  8. */
  9. @ApiOperation("登录")
  10. @GetMapping("/login")
  11. public Map decodeUserInfo(String encryptedData, String iv, String code) {
  12. Map map = new HashMap();
  13. //登录凭证不能为空
  14. if (code == null || code.length() == 0) {
  15. map.put("status", 0);
  16. map.put("msg", "code 不能为空");
  17. return map;
  18. }
  19. //小程序唯一标识 (在微信小程序管理后台获取)
  20. String wxspAppid = "xxxxxx";
  21. //小程序的 app secret (在微信小程序管理后台获取)
  22. String wxspSecret = "xxxxxx";
  23. //授权(必填)
  24. String grant_type = "authorization_code";
  25. // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
  26. //请求参数
  27. String params = "appid="+wxspAppid+"&secret="+wxspSecret+"&js_code="+code+"&grant_type="+grant_type;
  28. //发送请求
  29. String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
  30. //解析相应内容(转换成json对象)
  31. JSONObject json = JSONUtil.parseObj(sr);
  32. //获取会话密钥(session_key)
  33. String session_key = json.get("session_key").toString();
  34. //用户的唯一标识(openid)
  35. String openid = (String) json.get("openid");
  36. // 2、对encryptedData加密数据进行AES解密
  37. try {
  38. String result = WxAesUtils.decryptData(getURLDecoderString(encryptedData), session_key, getURLDecoderString(iv));
  39. if (null != result && result.length() > 0) {
  40. map.put("status", 1);
  41. map.put("msg", "解密成功");
  42. JSONObject userInfoJSON = JSONUtil.parseObj(result);
  43. Map userInfo = new HashMap();
  44. userInfo.put("openId", userInfoJSON.get("openId"));
  45. userInfo.put("nickName", userInfoJSON.get("nickName"));
  46. userInfo.put("gender", userInfoJSON.get("gender"));
  47. userInfo.put("city", userInfoJSON.get("city"));
  48. userInfo.put("province", userInfoJSON.get("province"));
  49. userInfo.put("country", userInfoJSON.get("country"));
  50. userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
  51. userInfo.put("unionId", userInfoJSON.get("unionId"));
  52. map.put("userInfo", userInfo);
  53. return map;
  54. }
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. map.put("status", 0);
  59. map.put("msg", "解密失败");
  60. return map;
  61. }

utils

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.PrintWriter;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import java.util.List;
  8. import java.util.Map;
  9. public class HttpRequest {
  10. /**
  11. * 向指定URL发送GET方法的请求
  12. *
  13. * @param url
  14. * 发送请求的URL
  15. * @param param
  16. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  17. * @return URL 所代表远程资源的响应结果
  18. */
  19. public static String sendGet(String url, String param) {
  20. String result = "";
  21. BufferedReader in = null;
  22. try {
  23. String urlNameString = url + "?" + param;
  24. URL realUrl = new URL(urlNameString);
  25. // 打开和URL之间的连接
  26. URLConnection connection = realUrl.openConnection();
  27. // 设置通用的请求属性
  28. connection.setRequestProperty("accept", "*/*");
  29. connection.setRequestProperty("connection", "Keep-Alive");
  30. connection.setRequestProperty("user-agent",
  31. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  32. // 建立实际的连接
  33. connection.connect();
  34. // 获取所有响应头字段
  35. Map<String, List<String>> map = connection.getHeaderFields();
  36. // 遍历所有的响应头字段
  37. for (String key : map.keySet()) {
  38. System.out.println(key + "--->" + map.get(key));
  39. }
  40. // 定义 BufferedReader输入流来读取URL的响应
  41. in = new BufferedReader(new InputStreamReader(
  42. connection.getInputStream()));
  43. String line;
  44. while ((line = in.readLine()) != null) {
  45. result += line;
  46. }
  47. } catch (Exception e) {
  48. System.out.println("发送GET请求出现异常!" + e);
  49. e.printStackTrace();
  50. }
  51. // 使用finally块来关闭输入流
  52. finally {
  53. try {
  54. if (in != null) {
  55. in.close();
  56. }
  57. } catch (Exception e2) {
  58. e2.printStackTrace();
  59. }
  60. }
  61. return result;
  62. }
  63. /**
  64. * 向指定 URL 发送POST方法的请求
  65. *
  66. * @param url
  67. * 发送请求的 URL
  68. * @param param
  69. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  70. * @return 所代表远程资源的响应结果
  71. */
  72. public static String sendPost(String url, String param) {
  73. PrintWriter out = null;
  74. BufferedReader in = null;
  75. String result = "";
  76. try {
  77. URL realUrl = new URL(url);
  78. // 打开和URL之间的连接
  79. URLConnection conn = realUrl.openConnection();
  80. // 设置通用的请求属性
  81. conn.setRequestProperty("accept", "*/*");
  82. conn.setRequestProperty("connection", "Keep-Alive");
  83. conn.setRequestProperty("user-agent",
  84. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  85. // 发送POST请求必须设置如下两行
  86. conn.setDoOutput(true);
  87. conn.setDoInput(true);
  88. // 获取URLConnection对象对应的输出流
  89. out = new PrintWriter(conn.getOutputStream());
  90. // 发送请求参数
  91. out.print(param);
  92. // flush输出流的缓冲
  93. out.flush();
  94. // 定义BufferedReader输入流来读取URL的响应
  95. in = new BufferedReader(
  96. new InputStreamReader(conn.getInputStream()));
  97. String line;
  98. while ((line = in.readLine()) != null) {
  99. result += line;
  100. }
  101. } catch (Exception e) {
  102. System.out.println("发送 POST 请求出现异常!"+e);
  103. e.printStackTrace();
  104. }
  105. //使用finally块来关闭输出流、输入流
  106. finally{
  107. try{
  108. if(out!=null){
  109. out.close();
  110. }
  111. if(in!=null){
  112. in.close();
  113. }
  114. }
  115. catch(IOException ex){
  116. ex.printStackTrace();
  117. }
  118. }
  119. return result;
  120. }
  121. }
  1. import org.apache.commons.codec.binary.Base64;
  2. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.security.Key;
  7. import java.security.Security;
  8. import java.util.Arrays;
  9. /**
  10. * 微信通讯加解密类
  11. */
  12. public class WxAesUtils {
  13. public static void main(String[] args) {
  14. decryptData("bmdheU9pKVKVyJOH8CR3mqp4mEeKZ1YOuMsVxXJKjRdc47rolEoe85JKAVEWmP2hl4NZB66qxN/NHHGsy0PqCn7hS4cLKqTgERXcYO0dURt2JuLg1myhG+PYhi0AROwfJytGBv77u8yinmMfyyKx6lSegkqnlIJ6TBIDYe2LCvW3kRVDzNDeWT0hOaLiRI6n3TFQwI0b5Tiu48UbFTHDhAtJ6LaZY+wg+PdtrHDgjWtt46pinENV22GFt77a6iIhdT4GzaW7ln45HuENtzXJLR5yM7SwT2pxKMGEknJGJD3yf/DxnR6a8HpXrwxtXHJfDlUzNS+Af51fOS/Z52LpbtvRecoEz8KKUxJ9lpcK1HrO/RMw/iYf+ce1bu5VIpYyMjTNAoLdffZ7V0HGMrVJUGbQMqk7ZjdCk1eqMyPpuIOuektgKE7K5wHqeo3NVo7A",
  15. "6pOQ1+4ca2ATDaSg4gauVA==",
  16. "zzmYGLoLH548Vf0fdJHHvA==");
  17. }
  18. public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
  19. String data = null;
  20. try {
  21. data = new String(
  22. decryptOfDiyIV(
  23. Base64.decodeBase64(encryptDataB64),
  24. Base64.decodeBase64(sessionKeyB64),
  25. Base64.decodeBase64(ivB64)
  26. )
  27. );
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. return data;
  32. }
  33. private static final String KEY_ALGORITHM = "AES";
  34. private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
  35. private static Key key;
  36. private static Cipher cipher;
  37. private static void init(byte[] keyBytes) {
  38. // 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
  39. int base = 16;
  40. if (keyBytes.length % base != 0) {
  41. int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
  42. byte[] temp = new byte[groups * base];
  43. Arrays.fill(temp, (byte) 0);
  44. System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
  45. keyBytes = temp;
  46. }
  47. // 初始化
  48. Security.addProvider(new BouncyCastleProvider());
  49. // 转化成JAVA的密钥格式
  50. key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
  51. try {
  52. // 初始化cipher
  53. cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. /**
  59. * 解密方法
  60. *
  61. * @param encryptedData 要解密的字符串
  62. * @param keyBytes 解密密钥
  63. * @param ivs 自定义对称解密算法初始向量 iv
  64. * @return 解密后的字节数组
  65. */
  66. private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
  67. byte[] encryptedText = null;
  68. init(keyBytes);
  69. try {
  70. cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
  71. encryptedText = cipher.doFinal(encryptedData);
  72. } catch (Exception e) {
  73. e.printStackTrace();
  74. }
  75. return encryptedText;
  76. }
  77. }
  1. /**
  2. * 解码
  3. * @param str
  4. * @return
  5. */
  6. public static String getURLDecoderString(String str) {
  7. String result = "";
  8. if (null == str) {
  9. return "";
  10. }
  11. try {
  12. result = java.net.URLDecoder.decode(str, "GBK");
  13. } catch (UnsupportedEncodingException e) {
  14. e.printStackTrace();
  15. }
  16. return result;
  17. }

获取到的用户信息:

{"nickName":"木笔","gender":0,"language":"zh_CN","city":"","province":"","country":"","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKDKIibHfOlhMmLib2tU491TpbTzvjHtw2TL38LM30ao5KRZL0A20PIeyhJ8ZGWMvHUDSabatHhic1PQ/132","watermark":{"timestamp":1652235161,"appid":"wx6db597cba4914b30"}}

  1. {
  2. "nickName":"木笔",
  3. "gender":0,
  4. "language":"zh_CN",
  5. "city":"",
  6. "province":"",
  7. "country":"",
  8. "avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKDKIibHfOlhMmLib2tU491TpbTzvjHtw2TL38LM30ao5KRZL0A20PIeyhJ8ZGWMvHUDSabatHhic1PQ/132",
  9. "watermark":{
  10. "timestamp":1652235161,
  11. "appid":"wx6db597cba4914b30"
  12. }
  13. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/635699
推荐阅读
相关标签
  

闽ICP备14008679号