网友真实露脸自拍10p,成人国产精品秘?久久久按摩,国产精品久久久久久无码不卡,成人免费区一区二区三区

小程序模板網(wǎng)

微信小程序后臺(tái)解密用戶數(shù)據(jù)

發(fā)布時(shí)間:2017-12-21 10:02 所屬欄目:小程序開發(fā)教程
微信小程序API文檔:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html
openId : 用戶在當(dāng)前小程序的唯一標(biāo)識(shí)
因?yàn)樽罱鶕?jù)API調(diào)用https://api.weixin.qq.com/sns/jscode2session所以需要配置以下服務(wù),但是官方是不贊成這種做法的,
而且最近把在服務(wù)器配置的方法給關(guān)閉了。也就是說要獲取用戶openid,地區(qū)等信息只能在后臺(tái)獲取。
一下是官方的流程
 
那么問題來了,代碼怎么實(shí)現(xiàn)呢,以下是用java后臺(tái)的實(shí)現(xiàn)
 
微信客戶端的代碼實(shí)現(xiàn)是這樣的
[html] view plain copy
 
  1. wx.login({  
  2.       success: function (r) {  
  3.         if (r.code) {  
  4.           var code = r.code;//登錄憑證  
  5.           if (code) {  
  6.             //2、調(diào)用獲取用戶信息接口  
  7.             wx.getUserInfo({  
  8.               success: function (res) {  
  9.                 //發(fā)起網(wǎng)絡(luò)請(qǐng)求  
  10.                 wx.request({  
  11.                   url: that.data.net + '/decodeUser.json',  
  12.                   header: {  
  13.                     "content-type": "application/x-www-form-urlencoded"  
  14.                   },  
  15.                   method: "POST",  
  16.                   data: {  
  17.                     encryptedData: res.encryptedData,  
  18.                     iv: res.iv,  
  19.                     code: code  
  20.                   },  
  21.                   success: function (result) {  
  22.                     // wx.setStorage({  
  23.                     //   key: 'openid',  
  24.                     //   data: res.data.openid,  
  25.                     // })  
  26.                     console.log(result)  
  27.                   }  
  28.                 })  
  29.               },  
  30.               fail: function () {  
  31.                 console.log('獲取用戶信息失敗')  
  32.               }  
  33.             })  
  34.           } else {  
  35.             console.log('獲取用戶登錄態(tài)失敗!' + r.errMsg)  
  36.           }  
  37.   
  38.         } else {  
  39.         }  
  40.       }  
  41.     })  
 
(服務(wù)端 java)自己的服務(wù)器發(fā)送code到微信服務(wù)器獲取openid(用戶唯一標(biāo)識(shí))和session_key(會(huì)話密鑰),
最后將encryptedData、iv、session_key通過AES解密獲取到用戶敏感數(shù)據(jù)

  1、獲取秘鑰并處理解密的controller
[java] view plain copy
 
  1. /** 
  2.      * 解密用戶敏感數(shù)據(jù) 
  3.      * 
  4.      * @param encryptedData 明文,加密數(shù)據(jù) 
  5.      * @param iv            加密算法的初始向量 
  6.      * @param code          用戶允許登錄后,回調(diào)內(nèi)容會(huì)帶上 code(有效期五分鐘),開發(fā)者需要將 code 發(fā)送到開發(fā)者服務(wù)器后臺(tái),使用code 換取 session_key api,將 code 換成 openid 和 session_key 
  7.      * @return 
  8.      */  
  9.     @ResponseBody  
  10.     @RequestMapping(value = "/decodeUser", method = RequestMethod.POST)  
  11.     public Map decodeUser(String encryptedData, String iv, String code) {  
  12.   
  13.         Map map = new HashMap();  
  14.   
  15.         //登錄憑證不能為空  
  16.         if (code == null || code.length() == 0) {  
  17.             map.put("status"0);  
  18.             map.put("msg""code 不能為空");  
  19.             return map;  
  20.         }  
  21.   
  22.         //小程序唯一標(biāo)識(shí)   (在微信小程序管理后臺(tái)獲取)  
  23.         String wxspAppid = "wxd8980e77d335c871";  
  24.         //小程序的 app secret (在微信小程序管理后臺(tái)獲取)  
  25.         String wxspSecret = "85d29ab4fa8c797423f2d7da5dd514cf";  
  26.         //授權(quán)(必填)  
  27.         String grant_type = "authorization_code";  
  28.   
  29.   
  30.         //////////////// 1、向微信服務(wù)器 使用登錄憑證 code 獲取 session_key 和 openid ////////////////  
  31.         //請(qǐng)求參數(shù)  
  32.         String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;  
  33.         //發(fā)送請(qǐng)求  
  34.         String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);  
  35.         //解析相應(yīng)內(nèi)容(轉(zhuǎn)換成json對(duì)象)  
  36.         JSONObject json = JSONObject.fromObject(sr);  
  37.         //獲取會(huì)話密鑰(session_key)  
  38.         String session_key = json.get("session_key").toString();  
  39.         //用戶的唯一標(biāo)識(shí)(openid)  
  40.         String openid = (String) json.get("openid");  
  41.   
  42.         //////////////// 2、對(duì)encryptedData加密數(shù)據(jù)進(jìn)行AES解密 ////////////////  
  43.         try {  
  44.             String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");  
  45.             if (null != result && result.length() > 0) {  
  46.                 map.put("status"1);  
  47.                 map.put("msg""解密成功");  
  48.   
  49.                 JSONObject userInfoJSON = JSONObject.fromObject(result);  
  50.                 Map userInfo = new HashMap();  
  51.                 userInfo.put("openId", userInfoJSON.get("openId"));  
  52.                 userInfo.put("nickName", userInfoJSON.get("nickName"));  
  53.                 userInfo.put("gender", userInfoJSON.get("gender"));  
  54.                 userInfo.put("city", userInfoJSON.get("city"));  
  55.                 userInfo.put("province", userInfoJSON.get("province"));  
  56.                 userInfo.put("country", userInfoJSON.get("country"));  
  57.                 userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));  
  58.                 userInfo.put("unionId", userInfoJSON.get("unionId"));  
  59.                 map.put("userInfo", userInfo);  
  60.                 return map;  
  61.             }  
  62.         } catch (Exception e) {  
  63.             e.printStackTrace();  
  64.         }  
  65.         map.put("status"0);  
  66.         map.put("msg""解密失敗");  
  67.         return map;  
  68.     }  

 
 
 
解密工具類 AesCbcUtil 
[java] view plain copy
 
  1. import org.apache.commons.codec.binary.Base64;  
  2. import org.bouncycastle.jce.provider.BouncyCastleProvider;  
  3.   
  4. import javax.crypto.BadPaddingException;  
  5. import javax.crypto.Cipher;  
  6. import javax.crypto.IllegalBlockSizeException;  
  7. import javax.crypto.NoSuchPaddingException;  
  8. import javax.crypto.spec.IvParameterSpec;  
  9. import javax.crypto.spec.SecretKeySpec;  
  10. import java.io.UnsupportedEncodingException;  
  11. import java.security.*;  
  12. import java.security.spec.InvalidParameterSpecException;  
  13.   
  14. /** 
  15.  * Created by lsh 
  16.  * AES-128-CBC 加密方式 
  17.  * 注: 
  18.  * AES-128-CBC可以自己定義“密鑰”和“偏移量“。 
  19.  * AES-128是jdk自動(dòng)生成的“密鑰”。 
  20.  */  
  21. public class AesCbcUtil {  
  22.   
  23.   
  24.     static {  
  25.         //BouncyCastle是一個(gè)開源的加解密解決方案,主頁在http://www.bouncycastle.org/  
  26.         Security.addProvider(new BouncyCastleProvider());  
  27.     }  
  28.   
  29.     /** 
  30.      * AES解密 
  31.      * 
  32.      * @param data           //密文,被加密的數(shù)據(jù) 
  33.      * @param key            //秘鑰 
  34.      * @param iv             //偏移量 
  35.      * @param encodingFormat //解密后的結(jié)果需要進(jìn)行的編碼 
  36.      * @return 
  37.      * @throws Exception 
  38.      */  
  39.     public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {  
  40. //        initialize();  
  41.   
  42.         //被加密的數(shù)據(jù)  
  43.         byte[] dataByte = Base64.decodeBase64(data);  
  44.         //加密秘鑰  
  45.         byte[] keyByte = Base64.decodeBase64(key);  
  46.         //偏移量  
  47.         byte[] ivByte = Base64.decodeBase64(iv);  
  48.   
  49.   
  50.         try {  
  51.             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");  
  52.   
  53.             SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");  
  54.   
  55.             AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");  
  56.             parameters.init(new IvParameterSpec(ivByte));  
  57.   
  58.             cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化  
  59.   
  60.             byte[] resultByte = cipher.doFinal(dataByte);  
  61.             if (null != resultByte && resultByte.length > 0) {  
  62.                 String result = new String(resultByte, encodingFormat);  
  63.                 return result;  
  64.             }  
  65.             return null;  
  66.         } catch (NoSuchAlgorithmException e) {  
  67.             e.printStackTrace();  
  68.         } catch (NoSuchPaddingException e) {  
  69.             e.printStackTrace();  
  70.         } catch (InvalidParameterSpecException e) {  
  71.             e.printStackTrace();  
  72.         } catch (InvalidKeyException e) {  
  73.             e.printStackTrace();  
  74.         } catch (InvalidAlgorithmParameterException e) {  
  75.             e.printStackTrace();  
  76.         } catch (IllegalBlockSizeException e) {  
  77.             e.printStackTrace();  
  78.         } catch (BadPaddingException e) {  
  79.             e.printStackTrace();  
  80.         } catch (UnsupportedEncodingException e) {  
  81.             e.printStackTrace();  
  82.         }  
  83.   
  84.         return null;  
  85.     }  
  86.   
  87. }  

發(fā)送請(qǐng)求的工具類HttpRequest
[java] view plain copy
 
  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.   
  10. /** 
  11.  * Created by lsh on 2017/6/22. 
  12.  */  
  13. public class HttpRequest {  
  14.     /** 
  15.      * 向指定URL發(fā)送GET方法的請(qǐng)求 
  16.      * 
  17.      * @param url 
  18.      *            發(fā)送請(qǐng)求的URL 
  19.      * @param param 
  20.      *            請(qǐng)求參數(shù),請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。 
  21.      * @return URL 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果 
  22.      */  
  23.     public static String sendGet(String url, String param) {  
  24.         String result = "";  
  25.         BufferedReader in = null;  
  26.         try {  
  27.             String urlNameString = url + "?" + param;  
  28.             URL realUrl = new URL(urlNameString);  
  29.             // 打開和URL之間的連接  
  30.             URLConnection connection = realUrl.openConnection();  
  31.             // 設(shè)置通用的請(qǐng)求屬性  
  32.             connection.setRequestProperty("accept""*/*");  
  33.             connection.setRequestProperty("connection""Keep-Alive");  
  34.             connection.setRequestProperty("user-agent",  
  35.                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
  36.             // 建立實(shí)際的連接  
  37.             connection.connect();  
  38.             // 獲取所有響應(yīng)頭字段  
  39.             Map<String, List<String>> map = connection.getHeaderFields();  
  40.             // 遍歷所有的響應(yīng)頭字段  
  41.             for (String key : map.keySet()) {  
  42.                 System.out.println(key + "--->" + map.get(key));  
  43.             }  
  44.             // 定義 BufferedReader輸入流來讀取URL的響應(yīng)  
  45.             in = new BufferedReader(new InputStreamReader(  
  46.                     connection.getInputStream()));  
  47.             String line;  
  48.             while ((line = in.readLine()) != null) {  
  49.                 result += line;  
  50.             }  
  51.         } catch (Exception e) {  
  52.             System.out.println("發(fā)送GET請(qǐng)求出現(xiàn)異常!" + e);  
  53.             e.printStackTrace();  
  54.         }  
  55.         // 使用finally塊來關(guān)閉輸入流  
  56.         finally {  
  57.             try {  
  58.                 if (in != null) {  
  59.                     in.close();  
  60.                 }  
  61.             } catch (Exception e2) {  
  62.                 e2.printStackTrace();  
  63.             }  
  64.         }  
  65.         return result;  
  66.     }  
  67.   
  68.     /**  
  69.      * 向指定 URL 發(fā)送POST方法的請(qǐng)求  
  70.      *  
  71.      * @param url  
  72.      *            發(fā)送請(qǐng)求的 URL  
  73.      * @param param  
  74.      *            請(qǐng)求參數(shù),請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。  
  75.      * @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果  
  76.      */  
  77.     public static String sendPost(String url, String param) {  
  78.         PrintWriter out = null;  
  79.         BufferedReader in = null;  
  80.         String result = "";  
  81.         try {  
  82.             URL realUrl = new URL(url);  
  83.             // 打開和URL之間的連接  
  84.             URLConnection conn = realUrl.openConnection();  
  85.             // 設(shè)置通用的請(qǐng)求屬性  
  86.             conn.setRequestProperty("accept""*/*");  
  87.             conn.setRequestProperty("connection""Keep-Alive");  
  88.             conn.setRequestProperty("user-agent",  
  89.                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
  90.             // 發(fā)送POST請(qǐng)求必須設(shè)置如下兩行  
  91.             conn.setDoOutput(true);  
  92.             conn.setDoInput(true);  
  93.             // 獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流  
  94.             out = new PrintWriter(conn.getOutputStream());  
  95.             // 發(fā)送請(qǐng)求參數(shù)  
  96.             out.print(param);  
  97.             // flush輸出流的緩沖  
  98.             out.flush();  
  99.             // 定義BufferedReader輸入流來讀取URL的響應(yīng)  
  100.             in = new BufferedReader(  
  101.                     new InputStreamReader(conn.getInputStream()));  
  102.             String line;  
  103.             while ((line = in.readLine()) != null) {  
  104.                 result += line;  
  105.             }  
  106.         } catch (Exception e) {  
  107.             System.out.println("發(fā)送 POST 請(qǐng)求出現(xiàn)異常!"+e);  
  108.             e.printStackTrace();  
  109.         }  
  110.         //使用finally塊來關(guān)閉輸出流、輸入流  
  111.         finally{  
  112.             try{  
  113.                 if(out!=null){  
  114.                     out.close();  
  115.                 }  
  116.                 if(in!=null){  
  117.                     in.close();  
  118.                 }  
  119.             }  
  120.             catch(IOException ex){  
  121.                 ex.printStackTrace();  
  122.             }  
  123.         }  
  124.         return result;  
  125.     }  
  126. }  

另外由于需求使用解密的工具類所有要在pom文件加上這個(gè)依賴
[java] view plain copy
 
  1. <dependency>  
  2.     <groupId>org.bouncycastle</groupId>  
  3.     <artifactId>bcprov-ext-jdk16</artifactId>  
  4.     <version>1.46</version>  
  5.     <type>jar</type>  
  6.     <scope>compile</scope>  
  7. </dependency>  

這樣才能引入bcprov這個(gè)jar包。網(wǎng)上參考了一下,個(gè)人感覺加這個(gè)依賴是最容易解決問題的。
最近打算弄個(gè)關(guān)于微信運(yùn)動(dòng)的小程序,解密這塊估計(jì)也要用到。大家有疑問可以一起留言交流


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.xiuhaier.com/wxmini/doc/course/18214.html 復(fù)制鏈接 如需定制請(qǐng)聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢
AI智能客服 ×