當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot微信小程序授权登录
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot微信小程序授权登录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SpringBoot微信小程序授權登錄
一、appId
1.1、自己是管理者:微信公眾平臺,申請或登錄自己的微信小程序,在開發者管理中即可看到
2.2、自己是開發者:讓管理員將自己加入到小程序開發者管理中,用管理者提供的appId和secret,否則沒有開發權限
二、小程序登錄頁面
2.1、打開HBuilderX開發工具,新建一個uni-app項目
2.2、在項目根目錄下新建config文件夾,創建config.js文件,配置后臺訪問路徑
2.3、新建簡單的login.vue頁面,調用前端方法獲取后臺登錄需要用的code信息
<button @click="toLogin">獲取登錄code</button> // 可以將后臺接口統一寫在common.js中,頁面統一引入 import { } from "@/api/common.js" methods:{toLogin(){uni.getProvider({service:'oauth',success:(provider) => {uni.login({success:(loginCode) =>{console.log("loginCode",loginCode);// todo 調用后臺登錄接口,參數code}})}})}, }2.4、下載微信開發者工具,并安裝
2.5、配置HBuilderX,點擊manifest.json,再點擊微信小程序配置appid
2.6、配置運行小程序需要用到的微信開發開發者工具,點擊HBuilder上面工具欄中的:工具—設置—運行配置,找到微信開發者工具工具路徑,配置2.4中安裝安裝時的路徑
三、java代碼部分
1.新建微信小程序公用配置文件
@Component @Slf4j public class WxDataConfigure {/**小程序appId*/public static String appId = "";/**小程序的秘鑰*/public static String ** = "";/**商戶號*/public static String mch_id = "";/**商戶支付秘鑰V2*/public static String key = "";/**商戶支付秘鑰V3*/public static String keyV3 = "";/**退款用到*/public static String certUrl = "";/**商家轉賬到零錢*/public static String pemUrl = "";public static String privateKeyPath = "";public static String privateCertPath = "";public static String sn = "";/**商戶證書序列號*/public static String serial_no = "";/**回調通知地址(需內網穿透測試)*/public static String notify_url = "";/**交易類型*/public static String trade_type = "JSAPI";/**統一下單API接口鏈接*/public static String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";/**查詢訂單API接口鏈接*/public static String query_url = "https://api.mch.weixin.qq.com/pay/orderquery";/**退款接口*/public static String refund_url = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds";/**退款回調接口*/public static String refund_notify_url = "";/**商家轉賬到零錢*/public static String batches_url = "https://api.mch.weixin.qq.com/v3/transfer/batches";/*** 預支付* @return*/public static WxPayService unifiedOrderWxPayService() {log.info("======================初始化微信支付接口服務開始======================");WxPayConfig payConfig = new WxPayConfig();payConfig.setAppId(appId);payConfig.setMchId(mch_id);payConfig.setMchKey(key);payConfig.setKeyPath(certUrl);payConfig.setTradeType(trade_type);WxPayService wxPayService = new WxPayServiceImpl();wxPayService.setConfig(payConfig);log.info("======================初始化微信支付接口服務完成======================");return wxPayService;}/*** 退款* @return*/public static WxPayService wxPayService() {//logger.info("======================初始化微信支付接口服務開始======================");WxPayConfig payConfig = new WxPayConfig();payConfig.setAppId(appId);payConfig.setMchId(mch_id);payConfig.setPrivateKeyPath(privateKeyPath);payConfig.setNotifyUrl(refund_notify_url);payConfig.setApiV3Key(keyV3);payConfig.setPrivateCertPath(privateCertPath);payConfig.setCertSerialNo(serial_no);payConfig.setMchKey(key);payConfig.setKeyPath(certUrl);payConfig.setTradeType(trade_type);WxPayService wxPayService = new WxPayServiceImpl();wxPayService.setConfig(payConfig);//logger.info("======================初始化微信支付接口服務完成======================");return wxPayService;}2.調用微信服務器接口的請求方法類
public class HttpRequest {//連接超時時間,默認10秒private static final int socketTimeout = 10000;//傳輸超時時間,默認30秒private static final int connectTimeout = 30000;/*** 向指定URL發送GET方法的請求** @param url 發送請求的URL* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。* @return URL 所代表遠程資源的響應結果*/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();// 設置通用的請求屬性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();// 獲取所有響應頭字段Map<String, List<String>> map = connection.getHeaderFields();// 遍歷所有的響應頭字段for (String key : map.keySet()) {System.out.println(key + "--->" + map.get(key));}// 定義 BufferedReader輸入流來讀取URL的響應in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("發送GET請求出現異常!" + e);e.printStackTrace();}// 使用finally塊來關閉輸入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}/*** post請求** @throws IOException* @throws ClientProtocolException* @throws NoSuchAlgorithmException* @throws KeyStoreException* @throws KeyManagementException* @throws UnrecoverableKeyException*/public static String sendPost(String url, Object xmlObj) throws ClientProtocolException, IOException, UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException {HttpPost httpPost = new HttpPost(url);//解決XStream對出現雙下劃線的bugXStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));xStreamForRequestPostData.alias("xml", xmlObj.getClass());//將要提交給API的數據對象轉換成XML格式數據Post給APIString postDataXML = xStreamForRequestPostData.toXML(xmlObj);System.out.println(postDataXML);//得指明使用UTF-8編碼,否則到API服務器XML的中文不能被成功識別StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");httpPost.addHeader("Content-Type", "text/xml");httpPost.setEntity(postEntity);//設置請求器的配置RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();httpPost.setConfig(requestConfig);HttpClient httpClient = HttpClients.createDefault();HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity, "UTF-8");return result;}/*** http POST 請求** @param url:請求地址* @param body: body實體字符串* @param certPath: 證書路徑* @param password: 證書密碼* @return*/public static String httpPostReflect(String url, String body, InputStream certPath, String password) {String xmlRes = "{}";HttpClient client = createSSLClientCert(certPath, password);HttpPost httpost = new HttpPost(url);try {//所有請求的body都需采用UTF-8編碼 // StringEntity entity = new StringEntity(body,"UTF-8"); // httpost.setEntity(entity);//支付平臺所有的API僅支持JSON格式的請求調用,HTTP請求頭Content-Type設為application/jsonhttpost.addHeader("Connection", "keep-alive");httpost.addHeader("Accept", "*/*");httpost.addHeader("Content-Type", "application/json; charset=UTF-8");httpost.addHeader("Host", "api.mch.weixin.qq.com");httpost.addHeader("X-Requested-With", "XMLHttpRequest");httpost.addHeader("Cache-Control", "max-age=0");httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");//httpost.addHeader("Authorization",Configure.sn + " " + data);httpost.setEntity(new StringEntity(body, "UTF-8"));HttpResponse response = client.execute(httpost);//所有響應也采用UTF-8編碼String result = EntityUtils.toString(response.getEntity(), "UTF-8");xmlRes = result;} catch (ClientProtocolException e) {System.out.println(e);} catch (UnknownHostException e) {System.out.println(e);} catch (IOException e) {System.out.println(e);}return xmlRes;}/*** 創建帶證書的實例** @param certPath* @return*/public static CloseableHttpClient createSSLClientCert(InputStream certPath, String password) {try {KeyStore keyStore = KeyStore.getInstance("PKCS12");keyStore.load(certPath, password.toCharArray());certPath.close();SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {//信任所有public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {return true;}}).loadKeyMaterial(keyStore, password.toCharArray()).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (KeyManagementException e) {System.out.println(e);} catch (NoSuchAlgorithmException e) {System.out.println(e);} catch (KeyStoreException e) {System.out.println(e);} catch (FileNotFoundException e) {System.out.println(e);} catch (Exception e) {System.out.println(e);}return HttpClients.createDefault();}/*** 自定義證書管理器,信任所有證書** @author pc*/public static class MyX509TrustManager implements X509TrustManager {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)throws CertificateException {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)throws CertificateException {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}} }3.微信登錄方法,返回用戶信息至前端
@Slf4j @RestController @RequestMapping("/wx/user") public class WxController {/*** //GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code* //https://api.weixin.qq.com/sns/jscode2session*/@GetMapping("/wxLogin")public Map<String,String> wxLogin(@RequestParam(name = "code",required = true) String code){//小程序登錄參數Get請求String openidParams = "appid=" + WxDataConfigure.appId + "&secret=" + WxDataConfigure.secret + "&js_code=" + code + "&grant_type=" + "authorization_code";String openidUrl = "https://api.weixin.qq.com/sns/jscode2session";//獲取接口調用憑證參數Get請求String accessTokenParams = "appid=" + WxDataConfigure.appId + "&secret=" + WxDataConfigure.secret + "&grant_type=" + "client_credential";String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";//http請求微信服務器String openIdResult = HttpRequest.sendGet(openidUrl, openidParams);String accessTokenResult = HttpRequest.sendGet(accessTokenUrl, accessTokenParams);JSONObject openIdJson = JSONObject.parseObject(openIdResult);JSONObject accessTokenJson = JSONObject.parseObject(accessTokenResult);//獲取openIdString openid =(String) openIdJson.get("openid");//會話秘鑰String session_key =(String) openIdJson.get("session_key");//獲取到的憑證String access_token =(String) accessTokenJson.get("access_token");Integer expiresIn =(Integer) accessTokenJson.get("expires_in");Map<String, String> infoMap = new HashMap<>();infoMap.put("openid",openid);infoMap.put("session_key",session_key);infoMap.put("access_token",access_token);infoMap.put("expiresIn",expiresIn.toString());return infoMap;} }一個在學習的開發者,勿噴,歡迎交流
總結
以上是生活随笔為你收集整理的SpringBoot微信小程序授权登录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Altair的离散元分析工具EDEM软件
- 下一篇: 使用JS获取客户端的IP地址