一般的微信小程序登录都会先前端调用wx.login生成code传给后端,后端通过code获取到openid和session_key并返回给前端,前端调用wx.getUserInfo获取对象参数等信息。
由于需求问题,我所写的小程序登录直接由前端调用wx.login生成code,wx.getUserProfile获取到iv和encrytedData作为参数进行接口调用。
在这里要注意wx.getUserInfo和wx.getUserProfile做出了调整,具体调整可查看小程序登录、用户信息相关接口调整说明 | 微信开放社区
@ApiOperation(value = "微信授权登录")@PostMapping("weChatLogin")public JsonData weChatLogin(@RequestBody UserAppDTO userAppDTO) {return userService.weChatLogin(userAppDTO.getCode(),userAppDTO.getEncryptedData(),userAppDTO.getIv());}
关键代码如下,即可获取openid和session_key以及对象信息,后续根据业务逻辑写就好
//通过code获取微信授权信息String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AuthUtil.APPID +"&secret=" + AuthUtil.APPSECRET + "&js_code=" + code + "&grant_type=authorization_code";JSONObject jsonObject = AuthUtil.doGetJson(url);String openId = jsonObject.getString("openid");String sessionKey = jsonObject.getString("session_key");JSONObject obj = new AuthUtil().getUserInfo(encryptedData, sessionKey, iv);
APPID和APPAECRET通过登录小程序开发平台获取,前后端务必保持一致。
/*** 微信授权登录调用Util*/
public class AuthUtil {public static final String APPID = "*****";//自己的微信APPIDpublic static final String APPSECRET = "*****";//自己的微信APPSECRETpublic static JSONObject doGetJson(String URL) throws IOException {JSONObject jsonObject = null;HttpURLConnection conn = null;InputStream is = null;BufferedReader br = null;StringBuilder result = new StringBuilder();try {//创建远程url连接对象java.net.URL url = new URL(URL);//通过远程url连接对象打开一个连接,强转成HTTPURLConnection类conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");//设置连接超时时间和读取超时时间conn.setConnectTimeout(15000);conn.setReadTimeout(60000);conn.setRequestProperty("Accept", "application/json");//发送请求conn.connect();//通过conn取得输入流,并使用Reader读取if (200 == conn.getResponseCode()) {is = conn.getInputStream();br = new BufferedReader(new InputStreamReader(is, "UTF-8"));String line;while ((line = br.readLine()) != null) {result.append(line);}} else {System.out.println("ResponseCode is an error code:" + conn.getResponseCode());}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {try {if (br != null) {br.close();}if (is != null) {is.close();}} catch (IOException ioe) {ioe.printStackTrace();}conn.disconnect();}jsonObject = JSONObject.parseObject(result.toString());return jsonObject;}public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv){// 被加密的数据byte[] dataByte = Base64.decode(encryptedData);// 加密秘钥byte[] keyByte = Base64.decode(sessionKey);// 偏移量byte[] ivByte = Base64.decode(iv);try {// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要int base = 16;if (keyByte.length % base != 0) {int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);byte[] temp = new byte[groups * base];Arrays.fill(temp, (byte) 0);System.arraycopy(keyByte, 0, temp, 0, keyByte.length);keyByte = temp;}// 初始化Security.addProvider(new BouncyCastleProvider());Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");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, "UTF-8");return JSONObject.parseObject(result);}} catch (Exception e) {e.printStackTrace();}return null;}}
就完成了!