溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

微信小程序如何實現(xiàn)后臺解密用戶數(shù)據(jù)

發(fā)布時間:2021-07-05 13:13:59 來源:億速云 閱讀:361 作者:小新 欄目:web開發(fā)

這篇文章主要介紹微信小程序如何實現(xiàn)后臺解密用戶數(shù)據(jù),文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

 微信小程序后臺解密用戶數(shù)據(jù)實例詳解

openId : 用戶在當(dāng)前小程序的唯一標(biāo)識

因為最近根據(jù)API調(diào)用https://api.weixin.qq.com/sns/jscode2session所以需要配置以下服務(wù),但是官方是不贊成這種做法的,
而且最近把在服務(wù)器配置的方法給關(guān)閉了。也就是說要獲取用戶openid,地區(qū)等信息只能在后臺獲取。

一下是官方的流程

那么問題來了,代碼怎么實現(xiàn)呢,以下是用java后臺的實現(xiàn)

微信客戶端的代碼實現(xiàn)是這樣的

wx.login({ 
   success: function (r) { 
    if (r.code) { 
     var code = r.code;//登錄憑證 
     if (code) { 
      //2、調(diào)用獲取用戶信息接口 
      wx.getUserInfo({ 
       success: function (res) { 
        //發(fā)起網(wǎng)絡(luò)請求 
        wx.request({ 
         url: that.data.net + '/decodeUser.json', 
         header: { 
          "content-type": "application/x-www-form-urlencoded" 
         }, 
         method: "POST", 
         data: { 
          encryptedData: res.encryptedData, 
          iv: res.iv, 
          code: code 
         }, 
         success: function (result) { 
          // wx.setStorage({ 
          //  key: 'openid', 
          //  data: res.data.openid, 
          // }) 
          console.log(result) 
         } 
        }) 
       }, 
       fail: function () { 
        console.log('獲取用戶信息失敗') 
       } 
      }) 
     } else { 
      console.log('獲取用戶登錄態(tài)失??!' + r.errMsg) 
     } 

    } else { 
    } 
   } 
  })

(服務(wù)端 java)自己的服務(wù)器發(fā)送code到微信服務(wù)器獲取openid(用戶唯一標(biāo)識)和session_key(會話密鑰),
最后將encryptedData、iv、session_key通過AES解密獲取到用戶敏感數(shù)據(jù)

1、獲取秘鑰并處理解密的controller

/** 
   * 解密用戶敏感數(shù)據(jù) 
   * 
   * @param encryptedData 明文,加密數(shù)據(jù) 
   * @param iv      加密算法的初始向量 
   * @param code     用戶允許登錄后,回調(diào)內(nèi)容會帶上 code(有效期五分鐘),開發(fā)者需要將 code 發(fā)送到開發(fā)者服務(wù)器后臺,使用code 換取 session_key api,將 code 換成 openid 和 session_key 
   * @return 
   */ 
  @ResponseBody 
  @RequestMapping(value = "/decodeUser", method = RequestMethod.POST) 
  public Map decodeUser(String encryptedData, String iv, String code) { 

    Map map = new HashMap(); 

    //登錄憑證不能為空 
    if (code == null || code.length() == 0) { 
      map.put("status", 0); 
      map.put("msg", "code 不能為空"); 
      return map; 
    } 

    //小程序唯一標(biāo)識  (在微信小程序管理后臺獲取) 
    String wxspAppid = "wxd8980e77d335c871"; 
    //小程序的 app secret (在微信小程序管理后臺獲取) 
    String wxspSecret = "85d29ab4fa8c797423f2d7da5dd514cf"; 
    //授權(quán)(必填) 
    String grant_type = "authorization_code"; 


    //////////////// 1、向微信服務(wù)器 使用登錄憑證 code 獲取 session_key 和 openid //////////////// 
    //請求參數(shù) 
    String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type; 
    //發(fā)送請求 
    String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params); 
    //解析相應(yīng)內(nèi)容(轉(zhuǎn)換成json對象) 
    JSONObject json = JSONObject.fromObject(sr); 
    //獲取會話密鑰(session_key) 
    String session_key = json.get("session_key").toString(); 
    //用戶的唯一標(biāo)識(openid) 
    String openid = (String) json.get("openid"); 

    //////////////// 2、對encryptedData加密數(shù)據(jù)進(jìn)行AES解密 //////////////// 
    try { 
      String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8"); 
      if (null != result && result.length() > 0) { 
        map.put("status", 1); 
        map.put("msg", "解密成功"); 

        JSONObject userInfoJSON = JSONObject.fromObject(result); 
        Map userInfo = new HashMap(); 
        userInfo.put("openId", userInfoJSON.get("openId")); 
        userInfo.put("nickName", userInfoJSON.get("nickName")); 
        userInfo.put("gender", userInfoJSON.get("gender")); 
        userInfo.put("city", userInfoJSON.get("city")); 
        userInfo.put("province", userInfoJSON.get("province")); 
        userInfo.put("country", userInfoJSON.get("country")); 
        userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl")); 
        userInfo.put("unionId", userInfoJSON.get("unionId")); 
        map.put("userInfo", userInfo); 
        return map; 
      } 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
    map.put("status", 0); 
    map.put("msg", "解密失敗"); 
    return map; 
  }

解密工具類 AesCbcUtil

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 lsh 
 * 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      //密文,被加密的數(shù)據(jù) 
   * @param key      //秘鑰 
   * @param iv       //偏移量 
   * @param encodingFormat //解密后的結(jié)果需要進(jìn)行的編碼 
   * @return 
   * @throws Exception 
   */ 
  public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception { 
//    initialize(); 

    //被加密的數(shù)據(jù) 
    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; 
  } 

}

發(fā)送請求的工具類HttpRequest

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.URL; 
import java.net.URLConnection; 
import java.util.List; 
import java.util.Map; 

/** 
 * Created by lsh on 2017/6/22. 
 */ 
public class HttpRequest { 
  /** 
   * 向指定URL發(fā)送GET方法的請求 
   * 
   * @param url 
   *      發(fā)送請求的URL 
   * @param param 
   *      請求參數(shù),請求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。 
   * @return URL 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果 
   */ 
  public static String sendGet(String url, String param) { 
    String result = ""; 
    BufferedReader in = null; 
    try { 
      String urlNameString = url + "?" + param; 
      URL realUrl = new URL(urlNameString); 
      // 打開和URL之間的連接 
      URLConnection connection = realUrl.openConnection(); 
      // 設(shè)置通用的請求屬性 
      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(); 
      // 獲取所有響應(yīng)頭字段 
      Map<String, List<String>> map = connection.getHeaderFields(); 
      // 遍歷所有的響應(yīng)頭字段 
      for (String key : map.keySet()) { 
        System.out.println(key + "--->" + map.get(key)); 
      } 
      // 定義 BufferedReader輸入流來讀取URL的響應(yīng) 
      in = new BufferedReader(new InputStreamReader( 
          connection.getInputStream())); 
      String line; 
      while ((line = in.readLine()) != null) { 
        result += line; 
      } 
    } catch (Exception e) { 
      System.out.println("發(fā)送GET請求出現(xiàn)異常!" + e); 
      e.printStackTrace(); 
    } 
    // 使用finally塊來關(guān)閉輸入流 
    finally { 
      try { 
        if (in != null) { 
          in.close(); 
        } 
      } catch (Exception e2) { 
        e2.printStackTrace(); 
      } 
    } 
    return result; 
  } 

  /** 
   * 向指定 URL 發(fā)送POST方法的請求 
   * 
   * @param url 
   *      發(fā)送請求的 URL 
   * @param param 
   *      請求參數(shù),請求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。 
   * @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果 
   */ 
  public static String sendPost(String url, String param) { 
    PrintWriter out = null; 
    BufferedReader in = null; 
    String result = ""; 
    try { 
      URL realUrl = new URL(url); 
      // 打開和URL之間的連接 
      URLConnection conn = realUrl.openConnection(); 
      // 設(shè)置通用的請求屬性 
      conn.setRequestProperty("accept", "*/*"); 
      conn.setRequestProperty("connection", "Keep-Alive"); 
      conn.setRequestProperty("user-agent", 
          "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 
      // 發(fā)送POST請求必須設(shè)置如下兩行 
      conn.setDoOutput(true); 
      conn.setDoInput(true); 
      // 獲取URLConnection對象對應(yīng)的輸出流 
      out = new PrintWriter(conn.getOutputStream()); 
      // 發(fā)送請求參數(shù) 
      out.print(param); 
      // flush輸出流的緩沖 
      out.flush(); 
      // 定義BufferedReader輸入流來讀取URL的響應(yīng) 
      in = new BufferedReader( 
          new InputStreamReader(conn.getInputStream())); 
      String line; 
      while ((line = in.readLine()) != null) { 
        result += line; 
      } 
    } catch (Exception e) { 
      System.out.println("發(fā)送 POST 請求出現(xiàn)異常!"+e); 
      e.printStackTrace(); 
    } 
    //使用finally塊來關(guān)閉輸出流、輸入流 
    finally{ 
      try{ 
        if(out!=null){ 
          out.close(); 
        } 
        if(in!=null){ 
          in.close(); 
        } 
      } 
      catch(IOException ex){ 
        ex.printStackTrace(); 
      } 
    } 
    return result; 
  } 
}

另外由于需求使用解密的工具類所有要在pom文件加上這個依賴

<dependency> 
  <groupId>org.bouncycastle</groupId> 
  <artifactId>bcprov-ext-jdk16</artifactId> 
  <version>1.46</version> 
  <type>jar</type> 
  <scope>compile</scope> 
</dependency>

這樣才能引入bcprov這個jar包。

以上是“微信小程序如何實現(xiàn)后臺解密用戶數(shù)據(jù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI