一·前端页面部分(JSP)
(1)引入微信js
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
(2)JSP页面
$(function() {
$.ajax({type : "post",
dataType : "json",
url : "http://wuasheng.cn/HuanLeJie1/getconfig",
data : {
url : window.location.href //此url必须为当前页面的路径
},complete : function() {},
success : function(msg) {
if (msg) {
console.log(msg)
wx.config({
debug : false, //
appId : msg['appId'], // 必填,公众号的唯一标识
timestamp : msg['timestamp'], // 必填,生成签名的时间戳
nonceStr : msg['nonceStr'], // 必填,生成签名的随机串
signature : msg['signature'], // 必填,签名,见附录1
jsApiList : [ 'onMenuShareTimeline',
'onMenuShareAppMessage', 'showOptionMenu' ]
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}
},
});
});
(3)调用微信分享接口
var shareTitle = "冠发平台";var shareDesc = "最地道最专业的棋牌游戏平台,万人真实在线用户,让玩家痴迷疯狂,让你数钱数到手抽筋。";
var shareImg = "http://wuasheng.cn/HuanLeJie1/page/images/64.jpg";
var url = window.location.href;
wx.ready(function() {
share();
});
function share() {
wx.showOptionMenu();
wx.onMenuShareTimeline({
title : shareTitle, // 分享标题
link : url, // 分享链接
imgUrl : shareImg,
desc : shareDesc, // 分享描述
success : function() {}
});
wx.onMenuShareAppMessage({
title : shareTitle, // 分享标题
link : url, // 分享链接
imgUrl : shareImg,
desc : shareDesc, // 分享描述
success : function() {}
});
}
二·后端业务逻辑处理部分(Java)
(1)ajax请求处理部分
@ResponseBody
@RequestMapping("getconfig")public Map<String, Object> getconf(HttpServletRequest request, String url) {
System.out.println("进来了");
String jsapi = getjssdk();
System.out.println("jsapi"+jsapi);
Map<String, Object> map=WeixinUtil.getWxConfig(request, url, jsapi);
System.out.println("数据"+map);
return map;
}
public String getjssdk() {
String appId = "**************"; // 必填,公众号的唯一标识
String secret = "***************"; // 必填,公众号密钥
Wxtoken token = wxService.selectById(1);
Wxtoken jsapi = wxService.selectById(2);
Date date = new Date();
Date jsdate = jsapi.getDate();
long between = (date.getTime() - jsdate.getTime()) / 1000;
if (between < 6500) {
return jsapi.getStr();
}
Date tokendate = token.getDate();
// 判断时间差 未超时 返回,超时 需要刷新 再次返回
between = (date.getTime() - tokendate.getTime()) / 1000;
String token2 = "";
if (between < 6500) {
token2 = token.getStr();
} else {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId
+ "&secret=" + secret;
JSONObject json = WeixinUtil.httpRequest(url, "GET", null);
token2 = json.getString("access_token");
token.setStr(token2);
wxService.updataNotNull(token);
}
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token2 + "&type=jsapi";
JSONObject json = WeixinUtil.httpRequest(url, "GET", null);
if (json != null) {
jsapi.setStr(json.getString("ticket"));
System.out.println("ticket==============>"+jsapi.getStr());
wxService.updataNotNull(jsapi);
return json.getString("ticket");
}
return null;
}
(2)数据库部分

实体类
package com.game.weixin;
import java.util.Date;
public class Wxtoken {
//id
private String id;
//字符串
private String str;
//上次获取的时间
private Date date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Wxtoken [id=" + id + ", str=" + str + ", date=" + date + "]";
}
}
service层
package com.game.service;
import com.game.weixin.Wxtoken;
public interface WxService {
//通过Id查询
Wxtoken selectById(int id);
//更新token的方法
void updataNotNull(Wxtoken token);
}
package com.game.service.impl;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.game.dao.WxMapper;
import com.game.service.WxService;
import com.game.weixin.Wxtoken;
@Service
public class WxServiceImpl implements WxService {
@Autowired
private WxMapper wxMapper;
//通过Id查询
public Wxtoken selectById(int id){
return wxMapper.selectById(id);
}
//更新token的方法
public void updataNotNull(Wxtoken token){
Date date=new Date();
token.setDate(date);
wxMapper.updataNotNull(token.getId(),token.getStr(),token.getDate());
}
}
dao层
package com.game.dao;
import java.util.Date;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.game.weixin.Wxtoken;
public interface WxMapper {
@Select("select * from wx_table where id=#{0}")
Wxtoken selectById(int id);
@Update("update wx_table set date=#{2},str=#{1} where id=#{0}")
void updataNotNull(String id, String str, Date date);
}
工具类
package com.game.weixin;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
public class WeixinUtil {
public static JSONObject httpRequest(String requestUrl,String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
public static Map<String, Object> getWxConfig(HttpServletRequest request,String urlx,String jsapi) {
Map<String, Object> ret = new HashMap<String, Object>();
@SuppressWarnings("unused")
HttpSession session=request.getSession();
String appId = "*****************"; // 必填,公众号的唯一标识
@SuppressWarnings("unused")
String secret = "**********************";
String requestUrl = urlx;
String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 必填,生成签名的时间戳
String nonceStr = UUID.randomUUID().toString(); // 必填,生成签名的随机串
String signature = "";
// 注意这里参数名必须全部小写,且必须有序
String sign = "jsapi_ticket=" + jsapi + "&noncestr=" + nonceStr+ "×tamp=" + timestamp + "&url=" + requestUrl;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(sign.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ret.put("appId", appId);
ret.put("timestamp", timestamp);
ret.put("nonceStr", nonceStr);
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;
}
}