国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

微信小程序調用微信登陸獲取openid及java做為服務端示例

2024-07-13 10:17:29
字體:
來源:轉載
供稿:網友

一、微信小程序
第一步:調用 wx.login獲取code 文檔地址
第二步:判斷用戶是否授權讀取用戶信息 文檔地址
第三步:調用wx.getUserInfo讀取用戶數據 文檔地址
第四步:由于小程序后臺授權域名無法授權微信的域名,所以我們只能通過我們自己的服務器去調用微信服務器去獲取用戶信息,故我們將wx.login獲取code 和 wx.getUserInfo 獲取的encryptedData與iv 通過wx.request 請求傳入后臺

微信小程序,openid,微信小程序登錄openid

服務器返回的數據:

微信小程序,openid,微信小程序登錄openid

小程序代碼:

//調用登錄接口,獲取 code wx.login({  success: function (res) {   wx.getSetting({    success(setRes) {     // 判斷是否已授權     if (!setRes.authSetting['scope.userInfo']) {      // 授權訪問      wx.authorize({       scope: 'scope.userInfo',       success() {        //獲取用戶信息        wx.getUserInfo({         lang: "zh_CN",         success: function (userRes) {          //發起網絡請求          wx.request({           url: config.loginWXUrl,           data: {            code: res.code,            encryptedData: userRes.encryptedData,            iv: userRes.iv           },           header: {            "Content-Type": "application/x-www-form-urlencoded"           },           method: 'POST',           //服務端的回掉           success: function (result) {            var data = result.data.result;            data.expireTime = nowDate + EXPIRETIME;            wx.setStorageSync("userInfo", data);            userInfo = data;           }          })         }        })       }      })     } else {      //獲取用戶信息      wx.getUserInfo({       lang: "zh_CN",       success: function (userRes) {        //發起網絡請求        wx.request({         url: config.loginWXUrl,         data: {          code: res.code,          encryptedData: userRes.encryptedData,          iv: userRes.iv         },         header: {          "Content-Type": "application/x-www-form-urlencoded"         },         method: 'POST',         success: function (result) {          var data = result.data.result;          data.expireTime = nowDate + EXPIRETIME;          wx.setStorageSync("userInfo", data);          userInfo = data;         }        })       }      })     }    }   })  } }) 

二、java服務端

根據code獲取openid與解碼用戶信息 代碼

所需要的jar包

<dependency>   <groupId>org.codehaus.xfire</groupId>   <artifactId>xfire-core</artifactId>   <version>1.2.6</version> </dependency> <dependency>   <groupId>org.bouncycastle</groupId>   <artifactId>bcprov-jdk16</artifactId>   <version>1.46</version> </dependency> 
/**  * 微信小程序信息獲取  *  * @author zhy  */ public class WXAppletUserInfo {   private static Logger log = Logger.getLogger(WXAppletUserInfo.class);      /**    * 獲取微信小程序 session_key 和 openid    *    * @author zhy    * @param code 調用微信登陸返回的Code    * @return    */   public static JSONObject getSessionKeyOropenid(String code){     //微信端登錄code值     String wxCode = code;     ResourceBundle resource = ResourceBundle.getBundle("weixin");  //讀取屬性文件     String requestUrl = resource.getString("url"); //請求地址 https://api.weixin.qq.com/sns/jscode2session     Map<String,String> requestUrlParam = new HashMap<String,String>();     requestUrlParam.put("appid", resource.getString("appId")); //開發者設置中的appId     requestUrlParam.put("secret", resource.getString("appSecret")); //開發者設置中的appSecret     requestUrlParam.put("js_code", wxCode); //小程序調用wx.login返回的code     requestUrlParam.put("grant_type", "authorization_code");  //默認參數          //發送post請求讀取調用微信 https://api.weixin.qq.com/sns/jscode2session 接口獲取openid用戶唯一標識     JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(requestUrl, requestUrlParam));     return jsonObject;   }      /**    * 解密用戶敏感數據獲取用戶信息    *    * @author zhy    * @param sessionKey 數據進行加密簽名的密鑰    * @param encryptedData 包括敏感數據在內的完整用戶信息的加密數據    * @param iv 加密算法的初始向量    * @return    */   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 JSON.parseObject(result);       }     } catch (NoSuchAlgorithmException e) {       log.error(e.getMessage(), e);     } catch (NoSuchPaddingException e) {       log.error(e.getMessage(), e);     } catch (InvalidParameterSpecException e) {       log.error(e.getMessage(), e);     } catch (IllegalBlockSizeException e) {       log.error(e.getMessage(), e);     } catch (BadPaddingException e) {       log.error(e.getMessage(), e);     } catch (UnsupportedEncodingException e) {       log.error(e.getMessage(), e);     } catch (InvalidKeyException e) {       log.error(e.getMessage(), e);     } catch (InvalidAlgorithmParameterException e) {       log.error(e.getMessage(), e);     } catch (NoSuchProviderException e) {       log.error(e.getMessage(), e);     }     return null;   } } 

發送請求的代碼

   /** * 向指定 URL 發送POST方法的請求 * * @param url 發送請求的 URL * @param param 請求參數 * @return 所代表遠程資源的響應結果 */ ublic static String sendPost(String url, Map<String, ?> paramMap) {    PrintWriter out = null;    BufferedReader in = null;    String result = "";        String param = ""; Iterator<String> it = paramMap.keySet().iterator();  while(it.hasNext()) {   String key = it.next();   param += key + "=" + paramMap.get(key) + "&"; }     try {      URL realUrl = new URL(url);      // 打開和URL之間的連接      URLConnection conn = realUrl.openConnection();      // 設置通用的請求屬性      conn.setRequestProperty("accept", "*/*");      conn.setRequestProperty("connection", "Keep-Alive");      conn.setRequestProperty("Accept-Charset", "utf-8");      conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");      // 發送POST請求必須設置如下兩行      conn.setDoOutput(true);      conn.setDoInput(true);      // 獲取URLConnection對象對應的輸出流      out = new PrintWriter(conn.getOutputStream());      // 發送請求參數      out.print(param);      // flush輸出流的緩沖      out.flush();      // 定義BufferedReader輸入流來讀取URL的響應      in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));      String line;      while ((line = in.readLine()) != null) {        result += line;      }    } catch (Exception e) {     log.error(e.getMessage(), e);    }    //使用finally塊來關閉輸出流、輸入流    finally{      try{        if(out!=null){          out.close();        }        if(in!=null){          in.close();        }      }      catch(IOException ex){        ex.printStackTrace();      }    }    return result;  } 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 望城县| 南陵县| 清流县| 文安县| 哈尔滨市| 平度市| 色达县| 明星| 石景山区| 武宣县| 洛宁县| 枞阳县| 天峻县| 巴东县| 沙湾县| 安图县| 南康市| 邹城市| 镇安县| 乡宁县| 吉首市| 广水市| 巧家县| 达孜县| 景德镇市| 汝州市| 长子县| 新源县| 理塘县| 东莞市| 高雄市| 奉节县| 平邑县| 扶沟县| 横山县| 宁蒗| 乾安县| 隆德县| 新丰县| 盖州市| 连山|