当前位置:   article > 正文

Java 微信小程序登录

java 微信小程序登录

1.修改 appId、secret 为自己的
 

  1. package com.rongtong.modules.app.controller;
  2. import cn.hutool.http.HttpUtil;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.rongtong.common.exception.RRException;
  6. import lombok.Data;
  7. import org.apache.commons.codec.binary.Base64;
  8. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestBody;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import javax.crypto.Cipher;
  13. import javax.crypto.NoSuchPaddingException;
  14. import javax.crypto.spec.IvParameterSpec;
  15. import javax.crypto.spec.SecretKeySpec;
  16. import java.io.UnsupportedEncodingException;
  17. import java.security.Key;
  18. import java.security.NoSuchAlgorithmException;
  19. import java.security.Security;
  20. import java.util.Arrays;
  21. @RestController
  22. public class WxLoginController {
  23. // 小程序 appId
  24. private final String appid = "wx75c9572*********";
  25. // 小程序 appSecret
  26. private final String secret = "57fc7766188f86af2e285**********";
  27. // 算法名称
  28. static final String KEY_ALGORITHM = "AES";
  29. // 加解密算法/模式/填充方式
  30. static final String algorithmStr = "AES/CBC/PKCS7Padding";
  31. private static Key key;
  32. private static Cipher cipher;
  33. @Data
  34. public static class WxLoginVo {
  35. //公众号或小程序授权cod
  36. private String code;
  37. //包括敏感数据在内的完整用户信息的加密数据
  38. private String encryptedData;
  39. //加密算法的初始向量
  40. private String iv;
  41. }
  42. @Data
  43. public static class WxClient {
  44. // 用户id 会员存在则返回
  45. private Integer cid;
  46. // 用户唯一标识
  47. private String openId;
  48. // 用户昵称
  49. private String nickName;
  50. // 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
  51. private Integer gender;
  52. // 用户头像
  53. private String avatarUrl;
  54. // 用户在开放平台的唯一标识符,若当前小程序已绑定到微信开放平台账号下会返回,详见 UnionID 机制说明。
  55. private String unionid;
  56. // 会话密钥
  57. private String sessionKey;
  58. }
  59. /**
  60. * 小程序登录
  61. */
  62. @PostMapping("/wx/login")
  63. public void wxLogin(@RequestBody WxLoginVo vo) {
  64. String json = this.codeSession(vo.getCode());
  65. WxClient client = JSON.parseObject(json, WxClient.class);
  66. String openId = client.getOpenId();
  67. System.out.println(openId);
  68. String unionid = client.getUnionid();
  69. System.out.println(unionid);
  70. // 用户信息获取不到头像昵称了
  71. // https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01
  72. WxClient program = this.getProgram(client.getSessionKey(), vo.getEncryptedData(), vo.getIv());
  73. System.out.println(program);
  74. }
  75. private String codeSession(String code) {
  76. String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
  77. String result = HttpUtil.get(url);
  78. JSONObject object = JSONObject.parseObject(result);
  79. return object.toString();
  80. }
  81. /**
  82. * 获取小程序用户对象
  83. *
  84. * @param sessionkey
  85. * @param encryptedData
  86. * @param iv
  87. * @return
  88. */
  89. public WxClient getProgram(String sessionkey, String encryptedData, String iv) {
  90. String result = getStr(encryptedData, sessionkey, iv);
  91. WxClient client = JSON.parseObject(result, WxClient.class);
  92. return client;
  93. }
  94. private static String getStr(String encryptedData, String keys, String iv) {
  95. byte[] data = decrypt(encryptedData, keys, iv);
  96. String dataStr = "";
  97. try {
  98. dataStr = new String(data, "utf-8");
  99. } catch (UnsupportedEncodingException e) {
  100. e.printStackTrace();
  101. throw new RRException("授权失败,请重新授权");
  102. }
  103. return dataStr;
  104. }
  105. /**
  106. * 解密方法
  107. *
  108. * @param encryptedDataStr 要解密的字符串
  109. * @param keyBytesStr 解密密钥
  110. * @return
  111. */
  112. public static byte[] decrypt(String encryptedDataStr, String keyBytesStr, String ivStr) {
  113. byte[] encryptedText = null;
  114. byte[] encryptedData = null;
  115. byte[] sessionkey = null;
  116. byte[] iv = null;
  117. try {
  118. sessionkey = Base64.decodeBase64(keyBytesStr);
  119. encryptedData = Base64.decodeBase64(encryptedDataStr);
  120. iv = Base64.decodeBase64(ivStr);
  121. init(sessionkey);
  122. cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
  123. encryptedText = cipher.doFinal(encryptedData);
  124. } catch (Exception e) {
  125. // TODO Auto-generated catch block
  126. e.printStackTrace();
  127. throw new RRException("授权失败,请重新授权");
  128. }
  129. return encryptedText;
  130. }
  131. public static void init(byte[] keyBytes) {
  132. // 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
  133. int base = 16;
  134. if (keyBytes.length % base != 0) {
  135. int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
  136. byte[] temp = new byte[groups * base];
  137. Arrays.fill(temp, (byte) 0);
  138. System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
  139. keyBytes = temp;
  140. }
  141. // 初始化
  142. Security.addProvider(new BouncyCastleProvider());
  143. // 转化成JAVA的密钥格式
  144. key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
  145. try {
  146. // 初始化cipher
  147. cipher = Cipher.getInstance(algorithmStr);
  148. } catch (NoSuchAlgorithmException e) {
  149. // TODO Auto-generated catch block
  150. e.printStackTrace();
  151. } catch (NoSuchPaddingException e) {
  152. // TODO Auto-generated catch block
  153. e.printStackTrace();
  154. }
  155. }
  156. }

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

闽ICP备14008679号