參數(shù)名
http://m.miracleart.cn/wiki/835.html" target="_blank">width="346" valign="top" style="word-break:break-all">? | 描述 |
appId | 應(yīng)用ID 登錄微信公眾號管理平臺可查詢 |
timestamp | ?必填,生成簽名的時間戳? |
nonceStr | 必填,生成簽名的隨機串? |
signature | 必填,簽名,見附錄1? |
上述表格中的參數(shù),我們在前一章節(jié)已經(jīng)說的很明白,之所以做出一個表格是因為如果想要成功接入微信jsapi這四個參數(shù)是憑證,也就是相當(dāng)于一個門必須要有四把鑰匙才能打開,缺一不可 。
接下來的案例采用java的servlet做的跳轉(zhuǎn)頁面,沒有用到springMVC,大家可把請求的路徑更換成controller路徑即可。
WxJsAPIServlet代碼:
package?com.test; import?java.io.IOException; import?java.io.PrintWriter; import?java.util.Map; import?javax.servlet.ServletException; import?javax.servlet.http.HttpServlet; import?javax.servlet.http.HttpServletRequest; import?javax.servlet.http.HttpServletResponse; import?com.test.util.JsapiTicketUtil; import?com.test.util.Sign; public?class?WxJsAPIServlet?extends?HttpServlet?{ /** ?????*?Constructor?of?the?object. ?????*/ ????public?WxJsAPIServlet()?{ ????????super(); ????} /** ?????*?Destruction?of?the?servlet.? ?????*/ ????public?void?destroy()?{ ????????super.destroy();?//?Just?puts?"destroy"?string?in?log ????????//?Put?your?code?here ????} ????/** ?????*?The?doGet?method?of?the?servlet.? ?????* ?????*?This?method?is?called?when?a?form?has?its?tag?value?method?equals?to?get. ?????*? ?????*?@param?request?the?request?send?by?the?client?to?the?server ?????*?@param?response?the?response?send?by?the?server?to?the?client ?????*?@throws?ServletException?if?an?error?occurred ?????*?@throws?IOException?if?an?error?occurred ?????*/ ????public?void?doGet(HttpServletRequest?request,?HttpServletResponse?response) ????????????throws?ServletException,?IOException?{ ????????System.out.println("wxJSAPI===================="); ????????String?jsapi_ticket?=JsapiTicketUtil.getJSApiTicket();; ????????Map ????????String?timestamp?=?map.get("timestamp"); ????????String?nonceStr?=?map.get("nonceStr"); ????????String?signature?=?map.get("signature"); ????????String?appId?=?"應(yīng)用Id"; ????????request.setAttribute("appId",?appId); ????????request.setAttribute("timestamp",?timestamp); ????????request.setAttribute("signature",signature); ????????request.setAttribute("nonceStr",?nonceStr); ????????request.getRequestDispatcher("jsapi/jsapi.jsp").forward(request,?response); ????} ????/** ?????*?The?doPost?method?of?the?servlet.? ?????* ?????*?This?method?is?called?when?a?form?has?its?tag?value?method?equals?to?post. ?????*? ?????*?@param?request?the?request?send?by?the?client?to?the?server ?????*?@param?response?the?response?send?by?the?server?to?the?client ?????*?@throws?ServletException?if?an?error?occurred ?????*?@throws?IOException?if?an?error?occurred ?????*/ ????public?void?doPost(HttpServletRequest?request,?HttpServletResponse?response) ????????????throws?ServletException,?IOException?{ ???????this.doGet(request,?response); ???????} /** ?????*?Initialization?of?the?servlet.? ?????* ?????*?@throws?ServletException?if?an?error?occurs ?????*/ ????public?void?init()?throws?ServletException?{ ????????//?Put?your?code?here ????} } |
第44行是生成?jsapi_ticket的工具類,在下面有貼出工具類的代碼。
第45行?Sign類的sign方法,把表格中的最后三個參數(shù)封裝放到Map集合中了。其中參數(shù)就是請求的servlet地址并跳轉(zhuǎn)到調(diào)用微信jsapi的jsp界面。
第49行?appId替換成你自己的應(yīng)用id,如果不知道應(yīng)用id 可登陸微信公眾平臺管理中心查詢。
servlet對應(yīng)的web.xml代碼
???? ????<display-name>This?is?the?display?name?of?my?J2EE?component ???? ???? ?? ???? ???? ?? |
生成簽名算法類Sign代碼:
package?com.test.util; /*** ?*?V型知識庫?www.vxzsk.com ?*/ 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?Map ????????Map ????????String?nonce_str?=?create_nonce_str(); ????????String?timestamp?=?create_timestamp(); ????????String?string1; ????????String?signature?=?""; ????????//注意這里參數(shù)名必須全部小寫,且必須有序 ????????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("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); ????} ????public?static?void?main(String[]?args)?{ ????????String?jsapi_ticket?=JsapiTicketUtil.getJSApiTicket(); ????????//?注意?URL?一定要動態(tài)獲取,不能?hardcode ????????String?url?=?"http://www.vxzsk.com/xx/x.do";//url是你請求的一個action或者controller地址,并且方法直接跳轉(zhuǎn)到使用jsapi的jsp界面 ????????Map ????????for?(Map.Entry?entry?:?ret.entrySet())?{ ????????????System.out.println(entry.getKey()?+?",?"?+?entry.getValue()); ????????} ????}; } |
生成jsapi_ticket參數(shù)的工具類JsapiTicketUtil代碼
package?com.test.util; import?java.io.BufferedReader; import?java.io.IOException; import?java.io.InputStreamReader; import?java.net.MalformedURLException; import?java.net.URL; import?java.net.URLConnection; import?net.sf.json.JSONObject; import?com.test.weixin.TestAcessToken; public?class?JsapiTicketUtil?{ ????/*** ?????*?模擬get請求 ?????*?@param?url ?????*?@param?charset ?????*?@param?timeout ?????*?@return ?????*/ ?????public?static?String?sendGet(String?url,?String?charset,?int?timeout) ??????{ ????????String?result?=?""; ????????try ????????{ ??????????URL?u?=?new?URL(url); ??????????try ??????????{ ????????????URLConnection?conn?=?u.openConnection(); ????????????conn.connect(); ????????????conn.setConnectTimeout(timeout); ????????????BufferedReader?in?=?new?BufferedReader(new?InputStreamReader(conn.getInputStream(),?charset)); ????????????String?line=""; ????????????while?((line?=?in.readLine())?!=?null) ????????????{ ??????????????result?=?result?+?line; ????????????} ????????????in.close(); ??????????}?catch?(IOException?e)?{ ????????????return?result; ??????????} ????????} ????????catch?(MalformedURLException?e) ????????{ ??????????return?result; ????????} ????????return?result; ??????} ?????public?static?String?getAccessToken(){ ????????????String?appid="你公眾號基本設(shè)置里的應(yīng)用id";//應(yīng)用ID ????????????String?appSecret="你公眾號基本設(shè)置里的應(yīng)用密鑰";//(應(yīng)用密鑰) ????????????String?url?="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret+""; ????????????String?backData=TestAcessToken.sendGet(url,?"utf-8",?10000); ????????????String?accessToken?=?(String)?JSONObject.fromObject(backData).get("access_token");?? ????????????return?accessToken; ?????} ????public?static?String?getJSApiTicket(){? ????????//獲取token ????????String?acess_token=?JsapiTicketUtil.getAccessToken(); ????????String?urlStr?=?"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+acess_token+"&type=jsapi";?? ????????String?backData=TestAcessToken.sendGet(urlStr,?"utf-8",?10000);?? ????????String?ticket?=?(String)?JSONObject.fromObject(backData).get("ticket");?? ????????return??ticket;?? ????}?? ????public?static?void?main(String[]?args)?{ ????????String?jsapiTicket?=?JsapiTicketUtil.getJSApiTicket(); ????????System.out.println("調(diào)用微信jsapi的憑證票為:"+jsapiTicket); ????} } |
上述代碼中有個獲取access_token的方法,請讀者更換自己的參數(shù)即可
jsapi.jsp代碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> W3C//DTD HTML 4.01 Transitional//EN"> ??<head> ???? ???? ????viewport" content="width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> ???? ?? ?? ?? 歡迎來到微信jsapi測試界面-V型知識庫?? ????? timestamp:${?timestamp} ??????? nonceStr:${?nonceStr} ??????? signature:${?signature} ??????? appId:${?appId} ??????onclick="uploadImg();"/>?? ????獲取當(dāng)前位置" onclick="getLocation();"/>?? ?? ?? ?? |