微信小程序調(diào)用微信登陸獲取openid及java做為服務(wù)端示例
一、微信小程序
第一步:調(diào)用 wx.login獲取code 文檔地址
第二步:判斷用戶是否授權(quán)讀取用戶信息 文檔地址
第三步:調(diào)用wx.getUserInfo讀取用戶數(shù)據(jù) 文檔地址
第四步:由于小程序后臺(tái)授權(quán)域名無(wú)法授權(quán)微信的域名,所以我們只能通過(guò)我們自己的服務(wù)器去調(diào)用微信服務(wù)器去獲取用戶信息,故我們將wx.login獲取code 和 wx.getUserInfo 獲取的encryptedData與iv 通過(guò)wx.request 請(qǐng)求傳入后臺(tái)
服務(wù)器返回的數(shù)據(jù):
小程序代碼:
//調(diào)用登錄接口,獲取 code wx.login({ success: function (res) { wx.getSetting({ success(setRes) { // 判斷是否已授權(quán) if (!setRes.authSetting['scope.userInfo']) { // 授權(quán)訪問(wèn) wx.authorize({ scope: 'scope.userInfo', success() { //獲取用戶信息 wx.getUserInfo({ lang: "zh_CN", success: function (userRes) { //發(fā)起網(wǎng)絡(luò)請(qǐ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', //服務(wù)端的回掉 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)絡(luò)請(qǐ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服務(wù)端
根據(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"); //請(qǐng)求地址 https://api.weixin.qq.com/sns/jscode2session Map<String,String> requestUrlParam = new HashMap<String,String>(); requestUrlParam.put("appid", resource.getString("appId")); //開發(fā)者設(shè)置中的appId requestUrlParam.put("secret", resource.getString("appSecret")); //開發(fā)者設(shè)置中的appSecret requestUrlParam.put("js_code", wxCode); //小程序調(diào)用wx.login返回的code requestUrlParam.put("grant_type", "authorization_code"); //默認(rèn)參數(shù) //發(fā)送post請(qǐng)求讀取調(diào)用微信 https://api.weixin.qq.com/sns/jscode2session 接口獲取openid用戶唯一標(biāo)識(shí) JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(requestUrl, requestUrlParam)); return jsonObject; } /** * 解密用戶敏感數(shù)據(jù)獲取用戶信息 * * @author zhy * @param sessionKey 數(shù)據(jù)進(jìn)行加密簽名的密鑰 * @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位,那么就補(bǔ)足. 這個(gè)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ā)送請(qǐng)求的代碼
/** * 向指定 URL 發(fā)送POST方法的請(qǐng)求 * * @param url 發(fā)送請(qǐng)求的 URL * @param param 請(qǐng)求參數(shù) * @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果 */ 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(); // 設(shè)置通用的請(qǐng)求屬性 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請(qǐng)求必須設(shè)置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發(fā)送請(qǐng)求參數(shù) out.print(param); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來(lái)讀取URL的響應(yīng) 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塊來(lái)關(guān)閉輸出流、輸入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 微信小程序 wx.request(接口調(diào)用方式)詳解及實(shí)例
- 微信小程序調(diào)用攝像頭隱藏式拍照功能
- 微信小程序頁(yè)面調(diào)用自定義組件內(nèi)的事件詳解
- 微信小程序如何調(diào)用json數(shù)據(jù)接口并解析
- 微信小程序調(diào)用攝像頭實(shí)現(xiàn)拍照功能
- 微信小程序調(diào)用支付接口的完整流程記錄
- 使用微信小程序API,調(diào)用微信的各種內(nèi)置能力。
- 微信小程序頁(yè)面與組件之間信息傳遞與函數(shù)調(diào)用
- 微信小程序開發(fā)打開另一個(gè)小程序的實(shí)現(xiàn)方法
- 微信外喚起微信小程序的方法詳解
相關(guān)文章
springmvc HttpServletRequest 如何獲取c:forEach的值
這篇文章主要介紹了springmvc HttpServletRequest 如何獲取c:forEach的值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08Springboot實(shí)現(xiàn)根據(jù)條件切換注入不同實(shí)現(xiàn)類的示例代碼
這篇文章主要介紹了Springboot實(shí)現(xiàn)根據(jù)條件切換注入不同實(shí)現(xiàn)類的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08淺談選擇、冒泡排序,二分查找法以及一些for循環(huán)的靈活運(yùn)用
下面小編就為大家?guī)?lái)一篇淺談選擇、冒泡排序,二分查找法以及一些for循環(huán)的靈活運(yùn)用。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06SpringBoot3實(shí)現(xiàn)webclient的通用方法詳解
Spring Boot WebClient 是 Spring Framework 5 中引入的一個(gè)新的響應(yīng)式 Web 客戶端,用于異步和響應(yīng)式地與外部服務(wù)進(jìn)行通信,下面我們就來(lái)看看SpringBoot3實(shí)現(xiàn)webclient的通用方法吧2024-04-04SpringCloud:feign對(duì)象傳參和普通傳參及遇到的坑解決
這篇文章主要介紹了SpringCloud:feign對(duì)象傳參和普通傳參及遇到的坑解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03MyBatis學(xué)習(xí)教程(八)-Mybatis3.x與Spring4.x整合圖文詳解
這篇文章主要介紹了MyBatis學(xué)習(xí)教程(八)-Mybatis3.x與Spring4.x整合圖文詳解的相關(guān)資料,需要的朋友可以參考下2016-05-05GraalVM?native-image編譯后quarkus的超音速啟動(dòng)
這篇文章主要介紹了經(jīng)過(guò)GraalVM?native-image編譯后的quarkus,來(lái)帶大家驗(yàn)證一下號(hào)稱超音速亞原子的quarkus是否名副其實(shí),有需要的朋友可以借鑒參考下,希望能夠有所包幫助2022-02-02SpringBoot RestTemplate GET POST請(qǐng)求的實(shí)例講解
這篇文章主要介紹了SpringBoot RestTemplate GET POST請(qǐng)求的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09