微信小程式後臺java登入和獲取使用者資訊程式碼
上篇博文中說到登入需要兩個介面,一個登入獲取openid一個獲取使用者資訊,並更新資料庫的介面
在此,我為了方便把兩個介面寫在一起了,也沒有寫更新資料庫的操作,這裡只寫如何獲取openid和使用者資訊的操作
/** * d登入介面 * @param encryptedData * @param iv * @param code * @return */ @PostMapping("/onLogin") public ResultData login(String encryptedData, String iv, String code) { if(!StringUtils.isNotBlank(code)){ return ResultData.build(202,"未獲取到使用者憑證code"); } String apiUrl="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code"; System.out.println(apiUrl); String responseBody = HttpClientUtil.doGet(apiUrl); System.out.println(responseBody); JSONObject jsonObject = JSON.parseObject(responseBody); if(StringUtils.isNotBlank(jsonObject.getString("openid"))&&StringUtils.isNotBlank(jsonObject.getString("session_key"))){ //解密獲取使用者資訊 JSONObject userInfoJSON=WechatGetUserInfoUtil.getUserInfo(encryptedData,jsonObject.getString("session_key"),iv); if(userInfoJSON!=null){ //這步應該set進實體類 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")); // 解密unionId & openId; if (userInfoJSON.get("unionId")!=null) { userInfo.put("unionId", userInfoJSON.get("unionId")); } //然後根據openid去資料庫判斷有沒有該使用者資訊,若沒有則存入資料庫,有則返回使用者資料 Map<String,Object> dataMap = new HashMap<>(); dataMap.put("userInfo", userInfo); String uuid=UUID.randomUUID().toString(); dataMap.put("WXTOKEN", uuid); redisTemplate.opsForValue().set(uuid,userInfo); redisTemplate.expire(uuid,appTimeOut,TimeUnit.SECONDS); return ResultData.build(200,"登陸成功",dataMap); }else{ return ResultData.build(202,"解密失敗"); } }else{ return ResultData.build(202,"未獲取到使用者openid 或 session"); } }
這裡用到兩個工具類
1.HttpClientUtil
package com.example.wxdemo.utils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 建立Httpclient物件 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 建立uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 建立http GET請求 HttpGet httpGet = new HttpGet(uri); // 執行請求 response = httpclient.execute(httpGet); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 建立Httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 建立Http Post請求 HttpPost httpPost = new HttpPost(url); // 建立引數列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模擬表單 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 執行http請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 建立Httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 建立Http Post請求 HttpPost httpPost = new HttpPost(url); // 建立請求內容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 執行http請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException { String body = ""; //建立httpclient物件 CloseableHttpClient client = HttpClients.createDefault(); //建立post方式請求物件 HttpPost httpPost = new HttpPost(url); //裝填引數 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(map!=null){ for (Entry<String, String> entry : map.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //設定引數到請求物件中 httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); System.out.println("請求地址:"+url); System.out.println("請求引數:"+nvps.toString()); //設定header資訊 //指定報文頭【Content-type】、【User-Agent】 httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //執行請求操作,並拿到結果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost); //獲取結果實體 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定編碼轉換結果實體為String型別 body = EntityUtils.toString(entity, encoding); } EntityUtils.consume(entity); //釋放連結 response.close(); return body; } }
2.WechatGetUserInfoUtil
package com.example.wxdemo.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Base64Utils; 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; import java.util.Arrays; /** * @author lqx * @create 2018-08-07 8:30 */ public class WechatGetUserInfoUtil { //日誌記錄器 private static final Logger log= LoggerFactory.getLogger(WechatGetUserInfoUtil.class); /** * 解密使用者敏感資料獲取使用者資訊 * * @param sessionKey 資料進行加密簽名的金鑰 * @param encryptedData 包括敏感資料在內的完整使用者資訊的加密資料 * @param iv 加密演算法的初始向量 * @return * */ public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) { // 被加密的資料 byte[] dataByte = Base64Utils.decode(encryptedData.getBytes()); // 加密祕鑰 byte[] keyByte = Base64Utils.decode(sessionKey.getBytes()); // 偏移量 byte[] ivByte = Base64Utils.decode(iv.getBytes()); 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; } }
相關推薦
微信小程式後臺java登入和獲取使用者資訊程式碼
上篇博文中說到登入需要兩個介面,一個登入獲取openid一個獲取使用者資訊,並更新資料庫的介面 在此,我為了方便把兩個介面寫在一起了,也沒有寫更新資料庫的操作,這裡只寫如何獲取openid和使用者資訊的操作 /** * d登入介面 * @param encrypt
微信小程式(表單登入並獲取個人資訊的實現)
首先先建立一個index的目錄和page,在xml裡面通過程式碼設計一個登入頁面,程式碼如下:<view class='container'> <form bindsubmit="formSubmit" bindreset="formReset"&g
微信小程式中使用者登入和登入態維護
提供使用者登入以及維護使用者的登入狀態,是一個擁有使用者系統的軟體應用普遍需要做的事情。像微信這樣的一個社交平臺,如果做一個小程式應用,我們可能很少會去做一個完全脫離和捨棄連線使用者資訊的純工具軟體。讓使用者登入,標識使用者和獲取使用者資訊,以使用者為核心提供服務,是大部分小程式都會做的事情。我們今天就來了解
微信小程式使用百度api獲取天氣資訊
2> 第二步:配置你的request合法域名 配置域名請到微信公眾平臺的後臺裡設定 3> 第三步:下載百度地圖的api ,連結:http://download.csdn.net/detail/michael_ouyang/9754015
微信小程式之使用者登入(獲取使用者資訊,openid,unionld) java後臺版
參考文章:https://blog.csdn.net/guochanof/article/details/80189935;感謝作者給的思路與大部分問題解決辦法由於微信官方api的更改,wx.getuserinfo()方法無法在無授權的情況下直接使用,參考文中作者是直接可以拉
微信小程式與Java後臺的通訊
一、寫在前面最近接觸了小程式的開發,後端選擇Java,因為小程式的程式碼執行在騰訊的伺服器上,而我們自己編寫的Java程式碼執行在我們自己部署的伺服器上,所以一開始不是很明白小程式如何與後臺進行通訊的,然後查詢資料發現結合了官方提供的api後好像和我們普通的web前後端通訊也沒有多大的區別,有想法後就寫了這個
微信小程式後臺登入一直失敗
問題描述:前端呼叫wx.login獲取code後,將code傳遞給後臺,後臺進行登入操作,登入使用的是shiro框架。之前登入的時候一直都很有效,但是今天登入後,當前端再次呼叫其他介面時,一直報401未登入!問題原因:經過不斷的列印日誌及分析排查,終於發現了原因:微信不維持s
微信小程式支付JAVA後臺邏輯
① 小程式前端會通過呼叫wx.login介面獲取得到登陸憑據code。這個code獲取之後5分鐘內如果再次呼叫wx.login獲取code並傳遞給②就會報錯,code非法,這個需要注意下。② 小程式將code登陸憑據和orderId訂單編號穿給後臺服務端,服務端呼叫https
微信小程式 後臺https域名繫結和免費的https證書申請詳解
伺服器配置如下圖 從後臺的伺服器配置可以看出 (1)微信小程式後臺只支援https,如果公司後臺還沒支援https的,趕緊要升級了 (2)API請求,檔案上傳,socket 檔案上傳和下載,必須是在後臺配置的,否則微信不允許你下載 另外,http請求,
簡單的微信小程式與Java後臺的連線
最近接觸了小程式的開發,後端選擇Java,因為小程式的程式碼執行在騰訊的伺服器上,而我們自己編寫的Java程式碼執行在我們自己部署的伺服器上,所以一開始不是很明白小程式如何與後臺進行通訊的,然後查詢資料發現結合了官方提供的api後好像和我們普通的web前後端通訊也沒有多大的區
在微信小程式裡使用 watch 和 computed
在開發 vue 的時候,我們可以使用 watch 和 computed 很方便的檢測資料的變化,從而做出相應的改變,但是在小程式裡,只能在資料改變時手動觸發 this.setData(),那麼如何給小程式也加上這兩個功能呢? 我們知道在 vue 裡是通過 Object.defineProperty 來實現資
微信小程式裡 wx:for和wx:for-item區別(補充下wx:key)
wx:for 一維陣列情況: 在頁面上 view wx:for ="{{list}}" {{item.id}} view 是迴圈list item是List的別名 多維陣列情況: view wx:fo
微信小程式下拉重新整理和上拉載入
example One:如果所有頁面都要開啟下拉重新整理功能: aap.json中: "window":{ "enablePullDownRefresh":true, //開啟下拉重新整理功能 "navigatio
1-微信小程式開發(安裝軟體和執行第一個微信小程式)
https://developers.weixin.qq.com/miniprogram/dev/ 我的 &nbs
微信小程式下拉載入和上拉重新整理兩種實現方法
方法一:onPullDownRefresh和onReachBottom方法實現小程式下拉載入和上拉重新整理 首先要在json檔案裡設定window屬性 屬性
微信小程式上拉重新整理和下拉載入2種方法實現
微信小程式上拉重新整理和下拉載入2種方法實現,onPullDownRefresh,scroll-view使用 一、XXX.json開啟下拉重新整理 { "enablePullDownRefresh": true } 二、XXX.js onP
微信小程式+SpringBoot+Mybatis登入demo(一、小程式端)
現在微信小程式越來越火了,相信不少人都通過各種途徑學習過微信小程式或者嘗試開發,我也是因為新鮮感學習了一下,寫了一個登入demo 前言: 微信小程式開發者註冊API等亂起八糟的東西我這裡就不寫了,是SpringBoot框架不會搭建的可以看我上一篇文章
微信小程式裡面的標籤和html標籤的對比、微信小程式基礎之常用控制元件
微信小程式和html5標籤的區別: HTML5 微信小程式 <h1></h1>...<h6></h6> <p>&l
理解微信小程式的生命週期和執行原理
寫微信小程式,他的生命週期不能不知道,不知道小程式就會出現各種bug而無法解決。小助君公眾號帶你學習小程式的生命週期和執行原理。 小程式由兩大執行緒組成:負責介面的執行緒(view thread)和服務執行緒(appservice thread),各司其職由互相配合 小程式的生命週期借
微信小程式的詳細登入(上)
前段時間釋出了一個微信小程式的簡單登入,那段時間我一直在忙著專案,有一天,我清閒下來準備進入小程式群裡面看一下來著,剛好有人問問題了,我一看這哥們的問題好像是我寫的東西啊,我感覺是時候秀一波了,是時候展現我真正的技術了。我當時正在醞釀如何無形裝逼時。這時候出現了一個打臉的。