微信小程序得到unionid

1、微信小程序中app.js中:java

 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("未受權"); } } }) } } })

2、開發者服務器中進行接收數據並解密數據apache

1.控制器中代碼:json

  @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";} //////////////// 一、向微信服務器 使用登陸憑證 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); //////////////// 二、對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.小程序

相關文章
相關標籤/搜索