package com.yrcn.my.sys.common; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Servlet implementation class WxServlet * 如果想使用JSSDK,必须获取微信认证的签名 WxServlet extends HttpServlet { serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public WxServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String appId = "aaaaaaaaaaaa"; //######1 获取access_token //AppID //AppSecret Object access_tokenObject = request.getServletContext().getAttribute("access_token"); Object ticketObject = request.getServletContext().getAttribute("ticket"); Object timestampObject = request.getServletContext().getAttribute("timestamp"); String access_token = ""; String ticket = ""; if (access_tokenObject != null) { long timestamp = Long.parseLong(timestampObject.toString()); boolean isExpires = new Date().getTime() - timestamp*1000 < 7000*1000; if(isExpires){ access_token = access_tokenObject.toString(); ticket = ticketObject.toString(); } } if ("".equals(access_token)) { String access_tokenResult = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="+appId+"&secret=aaaaaaaaaaaaaaaaaaaaaa"); //{"access_token":"Rd8SiZEaW2SRSZKFVxsh_ZS1adNwWP7zRAGG44HFA9lSNQbxOS-2hySxsJKKzUfEqkTJUsN9l_25po9qtoSJUCquad9C-KBh5vFLWdheL4omiICDMsTXBMIho271Cz-qMHAgADAVQJ","expires_in":7200} // System.out.println(access_tokenResult); JsonParser jsonParser =new JsonParser(); //创建json解析器 JsonObject jsonObject = (JsonObject)jsonParser.parse(access_tokenResult); access_token = jsonObject.get("access_token").getAsString(); //######2 使用access_token获取jsapi_ticket String jsapi_ticketResult = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket", "access_token="+access_token+"&type=jsapi"); //{"errcode":0,"errmsg":"ok","ticket":"kgt8ON7yVITDhtdwci0qefyIxUzYwFqAaiwhEj1TfdJZcuWSLVXoVHUC7V0qEq-tgWJ0OtvFCU5pzpOHylkW-Q","expires_in":7200} System.out.println(jsapi_ticketResult); jsonObject = (JsonObject)jsonParser.parse(jsapi_ticketResult); ticket = jsonObject.get("ticket").getAsString(); // request.getServletContext().setAttribute("access_token", access_token); request.getServletContext().setAttribute("ticket", ticket); request.getServletContext().setAttribute("timestamp", new Date().getTime()); } // System.out.println("access_token="+access_token); System.out.println("ticket="+ticket); //######3 签名算法 //签名生成规则如下:参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的URL,不包含#及其后面部分) 。 //对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。 //这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行URL 转义。 String nonceStr = getRandomString(20); long timestamp = new Date().getTime()/1000; String urlStr = request.getParameter("url"); if(urlStr == null){ urlStr = ""; } String url = URLDecoder.decode(urlStr.trim(), "UTF-8"); String string1 = "jsapi_ticket="+ticket+"&noncestr="+nonceStr+"×tamp="+timestamp+"&url="+url; System.out.println(string1); String signature = getSha1(string1); 必填,公众号的唯一标识 必填,生成签名的时间戳 必填,生成签名的随机串 RetObject retObject = new RetObject(appId, timestamp+"", nonceStr, signature); System.out.println(new Gson().toJson(retObject, RetObject.class)); response.getWriter().append(new Gson().toJson(retObject, RetObject.class)); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } getRandom(int count) { return (int) Math.round(Math.random() * (count)); } private static String string = "abcdefghijklmnopqrstuvwxyz"; private static String getRandomString(int length){ StringBuffer sb = new StringBuffer(); int len = string.length(); for (int i = 0; i < length; i++) { sb.append(string.charAt(getRandom(len-1))); } return sb.toString(); } public static String getSha1(String str){ if (null == str || 0 == str.length()){ return null; } char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA1"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char[] buf = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf]; } return new String(buf); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } } class RetObject{ private String appId; private String timestamp; private String nonceStr; private String signature; public RetObject(String appId, String timestamp, String nonceStr, String signature) { super(); this.appId = appId; this.timestamp = timestamp; this.nonceStr = nonceStr; this.signature = signature; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getNonceStr() { return nonceStr; } public void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } }