微信小程序調(diào)用微信登陸獲取openid及java做為服務端示例
一、微信小程序
第一步:調(diào)用 wx.login獲取code 文檔地址
第二步:判斷用戶是否授權讀取用戶信息 文檔地址
第三步:調(diào)用wx.getUserInfo讀取用戶數(shù)據(jù) 文檔地址
第四步:由于小程序后臺授權域名無法授權微信的域名,所以我們只能通過我們自己的服務器去調(diào)用微信服務器去獲取用戶信息,故我們將wx.login獲取code 和 wx.getUserInfo 獲取的encryptedData與iv 通過wx.request 請求傳入后臺
服務器返回的數(shù)據(jù):
小程序代碼:
//調(diào)用登錄接口,獲取 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) { //發(fā)起網(wǎng)絡請求 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) { //發(fā)起網(wǎng)絡請求 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服務端
根據(jù)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 調(diào)用微信登陸返回的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")); //開發(fā)者設置中的appId requestUrlParam.put("secret", resource.getString("appSecret")); //開發(fā)者設置中的appSecret requestUrlParam.put("js_code", wxCode); //小程序調(diào)用wx.login返回的code requestUrlParam.put("grant_type", "authorization_code"); //默認參數(shù) //發(fā)送post請求讀取調(diào)用微信 https://api.weixin.qq.com/sns/jscode2session 接口獲取openid用戶唯一標識 JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(requestUrl, requestUrlParam)); return jsonObject; } /** * 解密用戶敏感數(shù)據(jù)獲取用戶信息 * * @author zhy * @param sessionKey 數(shù)據(jù)進行加密簽名的密鑰 * @param encryptedData 包括敏感數(shù)據(jù)在內(nèi)的完整用戶信息的加密數(shù)據(jù) * @param iv 加密算法的初始向量 * @return */ public static JSONObject getUserInfo(String encryptedData,String sessionKey,String iv){ // 被加密的數(shù)據(jù) byte[] dataByte = Base64.decode(encryptedData); // 加密秘鑰 byte[] keyByte = Base64.decode(sessionKey); // 偏移量 byte[] ivByte = Base64.decode(iv); try { // 如果密鑰不足16位,那么就補足. 這個if 中的內(nèi)容很重要 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; } }
發(fā)送請求的代碼
/** * 向指定 URL 發(fā)送POST方法的請求 * * @param url 發(fā)送請求的 URL * @param param 請求參數(shù) * @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)"); // 發(fā)送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發(fā)送請求參數(shù) 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; }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springmvc HttpServletRequest 如何獲取c:forEach的值
這篇文章主要介紹了springmvc HttpServletRequest 如何獲取c:forEach的值方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Springboot實現(xiàn)根據(jù)條件切換注入不同實現(xiàn)類的示例代碼
這篇文章主要介紹了Springboot實現(xiàn)根據(jù)條件切換注入不同實現(xiàn)類的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08淺談選擇、冒泡排序,二分查找法以及一些for循環(huán)的靈活運用
下面小編就為大家?guī)硪黄獪\談選擇、冒泡排序,二分查找法以及一些for循環(huán)的靈活運用。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06SpringBoot3實現(xiàn)webclient的通用方法詳解
Spring Boot WebClient 是 Spring Framework 5 中引入的一個新的響應式 Web 客戶端,用于異步和響應式地與外部服務進行通信,下面我們就來看看SpringBoot3實現(xiàn)webclient的通用方法吧2024-04-04SpringCloud:feign對象傳參和普通傳參及遇到的坑解決
這篇文章主要介紹了SpringCloud:feign對象傳參和普通傳參及遇到的坑解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03MyBatis學習教程(八)-Mybatis3.x與Spring4.x整合圖文詳解
這篇文章主要介紹了MyBatis學習教程(八)-Mybatis3.x與Spring4.x整合圖文詳解的相關資料,需要的朋友可以參考下2016-05-05GraalVM?native-image編譯后quarkus的超音速啟動
這篇文章主要介紹了經(jīng)過GraalVM?native-image編譯后的quarkus,來帶大家驗證一下號稱超音速亞原子的quarkus是否名副其實,有需要的朋友可以借鑒參考下,希望能夠有所包幫助2022-02-02SpringBoot RestTemplate GET POST請求的實例講解
這篇文章主要介紹了SpringBoot RestTemplate GET POST請求的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09