package com.yxd.weixin.action; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Formatter; import java.util.UUID; import com.alibaba.fastjson.JSON; import com.yxd.common.base.BaseAction; //这个接入jssdk使用的是java,框架是SSH。 //这里继承的BaseAction,是我们自己封装的,可以不继承or自己写方法自行继承----------下面很多httpServletRequest以及httpServletResponce,都是封装的 public class WeixinSDK extends BaseAction{ public static String APPID = "wxcxxxxx"; private static String APPSECRET = "d0748xxxxx"; // 获得access_token public String access_token() { String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET; String access_token = null; String expires_in = null; try { URL urlGet = new URL(url); HttpURLConnection http = (HttpURLConnection) urlGet .openConnection(); http.setRequestMethod("GET"); // 必须是get方式请求 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // 连接超时30秒 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒 http.connect(); InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String message = new String(jsonBytes, "UTF-8"); //这里原本是JSONObject demoJson=JSONObject.fromObject(message); 但我这里无辜异常,尝试很久,所以写下面com.alibaba.fastjson.JSONObject这个。可以多次尝试下。 com.alibaba.fastjson.JSONObject demoJson =JSON.parseObject(message); access_token = demoJson.getString("access_token"); expires_in = demoJson.getString("expires_in"); is.close(); } catch (Exception e) { e.printStackTrace(); } return access_token; } public String jsapi_ticket(String access_token) { String str = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi"; String jsapi_ticket = null; String expiresin = null; try { URL url = new URL(str); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setRequestMethod("GET"); // 必须是get方式请求 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // 连接超时30秒 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒 http.connect(); InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String message = new String(jsonBytes, "UTF-8"); //看不懂看上一个方法注释,同理,下面类似都是 com.alibaba.fastjson.JSONObject demoJson =JSON.parseObject(message); jsapi_ticket = demoJson.getString("ticket"); expiresin = demoJson.getString("expires_in"); is.close(); } catch (Exception e) { e.printStackTrace(); } return jsapi_ticket; } public com.alibaba.fastjson.JSONObject sign(String jsapi_ticket, String url) { com.alibaba.fastjson.JSONObject jsons = new com.alibaba.fastjson.JSONObject(); String jsapi_ticket1 = jsapi_ticket; String nonce_str = create_nonce_str(); String timestamp = create_timestamp(); String string1; String signature = ""; // 注意这里参数名必须全部小写,且必须有序 string1 = "jsapi_ticket=" + jsapi_ticket1 + "&noncestr=" + nonce_str + "×tamp=" + timestamp + "&url=" + url; 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(); } //需要返回的参数 jsons.put("appId", APPID); jsons.put("url", url); jsons.put("jsapi_ticket", jsapi_ticket1); jsons.put("nonceStr", nonce_str); jsons.put("timestamp", timestamp); jsons.put("signature", signature); return jsons; } private 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; } // 获得我们的noncestr private String create_nonce_str() { return UUID.randomUUID().toString(); } // 获得我们的timestamp private String create_timestamp() { return Long.toString(System.currentTimeMillis() / 1000); } // 下面是储存和连接ajax的值 public void TokengetValue() throws IOException, ParseException { WeixinSDK jssdk = new WeixinSDK(); // 原有的系统时间 Date time = (Date)httpServletRequest.getSession().getServletContext().getAttribute("time"); // 获得当先系统时间 Date date = Calendar.getInstance().getTime(); String contextToken = (String) httpServletRequest.getSession().getServletContext() .getAttribute("contextToken"); String contextTicket = (String) httpServletRequest.getSession() .getServletContext().getAttribute("contextTicket"); String access_token = ""; String jsapi_ticket = ""; String url = httpServletRequest.getParameter("url"); com.alibaba.fastjson.JSONObject jsons = null; if (time == null) {// 没有存 重新获取并存储 httpServletRequest.getSession().getServletContext().setAttribute("time",Calendar.getInstance().getTime()); access_token = jssdk.access_token(); httpServletRequest.getSession().getServletContext().setAttribute( "contextToken", access_token); jsapi_ticket = jssdk.jsapi_ticket(access_token); httpServletRequest.getSession().getServletContext().setAttribute( "contextTicket", jsapi_ticket); jsons = jssdk.sign(jsapi_ticket, url); httpServletRequest.getSession().getServletContext().setAttribute( "contextjsons", jsons); } if (time != null && date.getTime() > time.getTime() + 6200 * 1000) {// 有数据,但是过期了 httpServletRequest.getSession().getServletContext().setAttribute("time",Calendar.getInstance().getTime()); access_token = jssdk.access_token(); httpServletRequest.getSession().getServletContext().setAttribute( "contextToken", access_token); jsapi_ticket = jssdk.jsapi_ticket(access_token); httpServletRequest.getSession().getServletContext().setAttribute( "contextTicket", jsapi_ticket); jsons = jssdk.sign(jsapi_ticket, url); httpServletRequest.getSession().getServletContext().setAttribute( "contextjsons", jsons); } if (time != null && date.getTime() < time.getTime() + 6200 * 1000) {// 有数据,有效期之内,直接用 access_token = (String) httpServletRequest.getSession().getServletContext() .getAttribute("contextToken"); jsapi_ticket = (String) httpServletRequest.getSession().getServletContext() .getAttribute("contextTicket"); jsons = jssdk.sign(jsapi_ticket, url); httpServletRequest.getSession().getServletContext().setAttribute( "contextjsons", jsons); } httpServletResponse.getWriter().println(jsons.toString()); httpServletResponse.getWriter().flush(); httpServletResponse.getWriter().close(); } } //不用配置web.xml,直接手写一个struts2文件,配置action即可,下面贴出 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="apiGetWxConfig" namespace="/api" extends="struts2" > <!-- 微信JSSDK--> <action name="tokengetValue" class="com.yxd.weixin.action.WeixinSDK" method="TokengetValue"> <result name="success" type="json"> <param name="root">rest</param> </result> </action> </package> </struts>
//路径也在这里了,至此本地项目运行完全没有问题,如有需要自行上传服务器。