摘要:開發背景最近在學習,所以從網上看了一些別人的代碼,再加入了自己的一些理解,主要是擔心之后會忘記,所以寫下一篇東西記錄一下思路。
開發背景
最近在學習java,所以從網上看了一些別人的代碼,再加入了自己的一些理解,主要是擔心之后會忘記,所以寫下一篇東西記錄一下思路。
一、 獲取acess_token以及jsapiTicket新建一個類TokenThread,實現線程的Runnable接口,代碼如下:
TokenThread
package util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.gson.Gson; import model.AccessToken; import model.JsapiTicket; /** * Created by xu on 2017/7/10. */ public class TokenThread implements Runnable { public static String appId = "xxx"; public static String appSecret= "xxx"; public static AccessToken accessToken = null; public static JsapiTicket jsapiTicket = null; public final static String js_api_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; @Override public void run() { while (true) { try { accessToken = this.getAccessToken(); jsapiTicket = this.getJsapiTicket(); //獲取到accessToken后,休眠7000秒,保證不會重復的獲取,超過了每天的最大次數 if (null != accessToken) { System.out.println(accessToken.getAccessToken()); System.out.println(jsapiTicket.getJsapiTicket()); Thread.sleep(7000 * 1000); //獲取到access_token 休眠7000秒 } else { Thread.sleep(1000 * 3); //獲取的access_token為空 休眠3秒 } } catch (Exception e) { System.out.println("發生異常:" + e.getMessage()); e.printStackTrace(); try { Thread.sleep(1000 * 10); //發生異常休眠1秒 } catch (Exception e1) { } } } } /** * 獲取access_token * @return */ private AccessToken getAccessToken(){ NetWorkHelper netHelper = new NetWorkHelper(); String Url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",this.appId,this.appSecret); String result = netHelper.getHttpsResponse(Url,""); System.out.println(result); //response.getWriter().println(result); JSONObject json = JSONObject.parseObject(result); System.out.println(json); AccessToken token = new AccessToken(); token.setAccessToken(json.getString("access_token")); token.setExpiresin(json.getInteger("expires_in")); return token; } /** * 獲取jsapi_ticket * @return */ private JsapiTicket getJsapiTicket(){ NetWorkHelper netHelper = new NetWorkHelper(); String Url = js_api_ticket_url.replace("ACCESS_TOKEN",this.getAccessToken().getAccessToken()); String result = netHelper.getHttpsResponse(Url,""); System.out.println(result); JSONObject json = JSONObject.parseObject(result); System.out.println(json); JsapiTicket jsapiTicket = new JsapiTicket(); jsapiTicket.setJsapiTicket(json.getString("ticket")); jsapiTicket.setExpiresin(json.getInteger("expires_in")); return jsapiTicket; } }
這里用到了兩個工具類NetWorkHelper,發起網絡請求網上有封裝好的,我做一下搬運工:
NetWorkHelper
package util; import javax.net.ssl.*; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * Created by xu on 2017/7/10. */ public class NetWorkHelper { public String getHttpsResponse(String hsUrl,String requestMethod) { URL url; InputStream is = null; String resultData = ""; try { url = new URL(hsUrl); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); TrustManager[] tm = {xtm}; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, tm, null); con.setSSLSocketFactory(ctx.getSocketFactory()); con.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); con.setDoInput(true); //允許輸入流,即允許下載 //在android中必須將此項設置為false con.setDoOutput(false); //允許輸出流,即允許上傳 con.setUseCaches(false); //不使用緩沖 if(null!=requestMethod && !requestMethod.equals("")) { con.setRequestMethod(requestMethod); //使用指定的方式 } else{ con.setRequestMethod("GET"); //使用get請求 } is = con.getInputStream(); //獲取輸入流,此時才真正建立鏈接 InputStreamReader isr = new InputStreamReader(is); BufferedReader bufferReader = new BufferedReader(isr); String inputLine = ""; while ((inputLine = bufferReader.readLine()) != null) { resultData += inputLine + " "; } System.out.println(resultData); Certificate[] certs = con.getServerCertificates(); int certNum = 1; for (Certificate cert : certs) { X509Certificate xcert = (X509Certificate) cert; } } catch (Exception e) { e.printStackTrace(); } return resultData; } X509TrustManager xtm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } }; }
上面還引入了阿里巴巴的json解析包import com.alibaba.fastjson.JSONObject;自行上網搜索就好。
上面的獲取accessToken的過程中,new了一個AccessToken和JsapiTicket對象,我把她們放進了一個model類里。
AccessToken
package model; /** * Created by xu on 2017/7/10. */ public class AccessToken { public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public int getExpiresin() { return expiresin; } public void setExpiresin(int expiresin) { this.expiresin = expiresin; } private String accessToken; private int expiresin; }
JsapiTicket
package model; /** * Created by xu on 2017/7/12. */ public class JsapiTicket { private String jsapiTicket; private int expiresin; public String getJsapiTicket() { return jsapiTicket; } public void setJsapiTicket(String jsapiTicket) { this.jsapiTicket = jsapiTicket; } public int getExpiresin() { return expiresin; } public void setExpiresin(int expiresin) { this.expiresin = expiresin; } }
新建一個HttpServlet,AccessTokenServlet,用來執行獲取,初始化的過程中執行,這里需要配置web.xml
web.xml
wechatServlet com.wecahtServlet wechatServlet GetConfigServlet com.GetConfigServlet GetConfigServlet /getConfig ReturnRobotServlet com.ReturnRobotServlet ReturnRobotServlet /doReturn initAccessTokenServlet com.AccessTokenServlet appid xxxx appsecret xxxx 0 returnRobot.jsp
AccessTokenServlet
package com; import util.TokenThread; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by xu on 2017/7/10. */ @WebServlet(name = "AccessTokenServlet") public class AccessTokenServlet extends HttpServlet { public void init() throws ServletException { TokenThread.appId = getInitParameter("appid"); //獲取servlet初始參數appid和appsecret TokenThread.appSecret = getInitParameter("appsecret"); System.out.println("appid:"+TokenThread.appId); System.out.println("appSecret:"+TokenThread.appSecret); new Thread(new TokenThread()).start(); //啟動進程 } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }二、獲取jssdk配置
創建一個GetConfigServlet用以頁面獲取jssdk的配置信息
GetConfigServlet
package com; import com.alibaba.fastjson.JSON; import util.Sign; import util.TokenThread; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /** * Created by xu on 2017/7/12. */ @WebServlet(name = "GetConfigServlet") public class GetConfigServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("url"); String jsapi_tickec = TokenThread.jsapiTicket.getJsapiTicket(); Mapjssdk = Sign.main(jsapi_tickec,url); String str = JSON.toJSONString(jssdk); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.write(str); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("get config test success"); } }
上文中引用了sign工具類:
Sign
package util; import java.util.UUID; import java.util.Map; import java.util.HashMap; import java.util.Formatter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.UnsupportedEncodingException; public class Sign { public static Mapmain(String jsapiTicket,String posturl) { String jsapi_ticket = jsapiTicket; // 注意 URL 一定要動態獲取,不能 hardcode String url = posturl; Map ret = sign(jsapi_ticket, url); // for (Map.Entry entry : ret.entrySet()) { // System.out.println(entry.getKey() + ", " + entry.getValue()); // } return ret; }; public static Map sign(String jsapi_ticket, String url) { Map ret = new HashMap (); String nonce_str = create_nonce_str(); String timestamp = create_timestamp(); String string1; String signature = ""; //注意這里參數名必須全部小寫,且必須有序 string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "×tamp=" + timestamp + "&url=" + url; System.out.println(string1); try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature = byteToHex(crypt.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ret.put("url", url); ret.put("appId", TokenThread.appId); ret.put("jsapi_ticket", jsapi_ticket); ret.put("nonceStr", nonce_str); ret.put("timestamp", timestamp); ret.put("signature", signature); return ret; } private static String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } private static String create_nonce_str() { return UUID.randomUUID().toString(); } private static String create_timestamp() { return Long.toString(System.currentTimeMillis() / 1000); } }
前段js:
$(document).ready(function () { //獲取配置信息 $.ajax({ url : "http://120.77.43.103/wechat/getConfig", type : "post", dataType : "json", contentType : "application/x-www-form-urlencoded; charset=utf-8", data : { "url" : location.href.split("#")[0] }, success : function(data) { console.log(data); wx.config({ debug : true, appId : data.appId, timestamp : data.timestamp, nonceStr : data.nonceStr, signature : data.signature, jsApiList : [ "checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo", "hideMenuItems", "showMenuItems", "hideAllNonBaseMenuItem", "showAllNonBaseMenuItem", "translateVoice", "startRecord", "stopRecord", "onRecordEnd", "playVoice", "pauseVoice", "stopVoice", "uploadVoice", "downloadVoice", "chooseImage", "previewImage", "uploadImage", "downloadImage", "getNetworkType", "openLocation", "getLocation", "hideOptionMenu", "showOptionMenu", "closeWindow", "scanQRCode", "chooseWXPay", "openProductSpecificView", "addCard", "chooseCard", "openCard" ] }); }, error: function (xhr, type) { showAlert("getJSSDKSignature出錯"); }, }); checkUserDeposit(); }); function checkUserDeposit() { wx.ready(function () { scanQRCode(); }); } function scanQRCode() { wx.scanQRCode({ needResult: 1, // 默認為0,掃描結果由微信處理,1則直接返回掃描結果, scanType: ["qrCode", "barCode"], // 可以指定掃二維碼還是一維碼,默認二者都有 success: function (res) { var result = res.resultStr; // 當needResult 為 1 時,掃碼返回的結果 //var result = "linuxserl.honeybot.cn:5120/download/?id=bind@104@10V1BLH100040478054"; //var result = "CODE_128,10V1BLH100261"; var postCode = ""; var robotCodeType = 0; if (result.indexOf(",") > -1) { //條形碼 var codes = result.split(","); if (codes != null && codes.length > 1) { postCode = codes[1]; robotCodeType = 1; } } else { //二維碼 var reg = /@(.*?)@/; var codes = reg.exec(result); if (codes.length > 1) { postCode = codes[1]; robotCodeType = 0; } } showConfirm("是否確認退還?", function () { returnRobot(robotCodeType, postCode); }); } }); } function returnRobot(robotCodeType, robotCodeValue) { var dialogLoading = null; var postData = { robot_code: { robot_code_type: robotCodeType, robot_code_value: robotCodeValue } } $.ajax({ type: "POST", cache: false, url: "http://120.77.43.103/wechat/doReturn", data: "json_body=" + JSON.stringify(postData), dataType: "json", beforeSend: function (XHR) { dialogLoading = showLoading(); }, success: function (data) { if (data.result_code == 0) { setTimeout(function() { showAlert("申請退還機器人成功,請點擊確定支付租金", function () { goTo(config.page_url.return_robot_wait_confrm); }); }, 500); } else { setTimeout(function () { showAlert(data.result_message); }, 500); } }, error: function (xhr, type) { showAlert("error") }, complete: function (xhr, type) { dialogLoading.hide(); } }); } wx.error(function (res) { showAlert("微信接口出錯"); });三、額外的一些簽名,驗證配置
wecahtServlet
package com; import com.sun.tools.classfile.Signature; import util.CheckUtil; import util.Sign; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by xu on 2017/7/10. */ @WebServlet(name = "wecahtServlet") public class wecahtServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); if( CheckUtil.checkSignature(signature,timestamp,nonce)) { response.getWriter().println(echostr); } } }
工具類CheckUtil
package util; import java.util.Arrays; /** * Created by xu on 2017/7/10. */ public class CheckUtil { private static final String token = "test"; public static boolean checkSignature(String signature,String timestamp,String nonce) { String[] arr = new String[]{token,timestamp,nonce}; //排序 Arrays.sort(arr); //生成字符串 StringBuffer content = new StringBuffer(); for (int i=0;isha1
package util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by xu on 2017/7/10. */ public class Decript { public static String SHA1(String decript) { try { MessageDigest digest = MessageDigest .getInstance("SHA-1"); digest.update(decript.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字節數組轉換為 十六進制 數 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } }引用JdbcUtils jdbc連接工具類
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcUtils { private static String url="jdbc:mysql://xxx.xxx.xxx/weixin?useUnicode=true&characterEncoding=utf-8"; private static String user="xxx"; private static String password="xxx"; private JdbcUtils() { } static { try { Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } public static void free(ResultSet resultset,Statement st,Connection conn) { //6.釋放資源 try{ if(resultset!=null) resultset.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(st!=null) st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(conn!=null) try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }完整項目地址:https://github.com/345632699/...
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/70268.html
摘要:最近做個移動端的應用,要實現自定義微信分享功能,實現過程中遇到一些小小的坑,這里分享一下。后來微信放出了,開始對端提供豐富強大的官方接口支持,也逐漸淡出了開發者的視野。 最近做個移動端的H5應用,要實現自定義微信分享功能,實現過程中遇到一些小小的坑,這里分享一下。 以前微信官方是沒有正式支持微信分享的自定義接口(包括圖片、標題、描述)的,然而有一些大神找到了WeixinJSBridge...
摘要:最近做個移動端的應用,要實現自定義微信分享功能,實現過程中遇到一些小小的坑,這里分享一下。后來微信放出了,開始對端提供豐富強大的官方接口支持,也逐漸淡出了開發者的視野。 最近做個移動端的H5應用,要實現自定義微信分享功能,實現過程中遇到一些小小的坑,這里分享一下。 以前微信官方是沒有正式支持微信分享的自定義接口(包括圖片、標題、描述)的,然而有一些大神找到了WeixinJSBridge...
摘要:主要是用,每當用戶第一次進來時,去獲取一次簽名驗證。注意只獲取一次,這樣簽名就解決了。 vue+微信支付目錄+JSSDK簽名解決方案 遇坑如下 注意:此方法僅為個人總結,并非唯一解決方案 微信JSSDK簽名出錯 微信支付 調起支付缺少API參數 微信支付目錄配置,只有5個配置,可能超過5個地方有配置,路由規劃 微信授權回調處理 我所使用的技術 vue路由模式 history 模...
摘要:簽名用的必須是調用接口頁面的完整。出于安全考慮,開發者必須在服務器端實現簽名的邏輯。以上為服務器的步驟,根據以上內容實現了一個簡單的中間件,詳見客戶端使用接口注入權限驗證配置待續 關鍵名詞解釋 安全域名: 用于JSSDK,開發者即可在該域名(包括二級域名)下調用微信開放的JS接口 access_token: · 普通access_token:JSSDK和微信公眾號后臺...
閱讀 2205·2021-10-13 09:39
閱讀 3408·2021-09-30 09:52
閱讀 800·2021-09-26 09:55
閱讀 2775·2019-08-30 13:19
閱讀 1888·2019-08-26 10:42
閱讀 3185·2019-08-26 10:17
閱讀 543·2019-08-23 14:52
閱讀 3631·2019-08-23 14:39