//首先,由于微信中token和ticket两小时过期,所以设一个定时任务,定时获取
@Component
public class MyTask {
@Autowired
private JdbcTemplate jd;
int i=0;
@Scheduled(cron="1 1 * * * ?") //间隔1小时执行
public void taskCycle() throws Exception{
String ticket= weixinhttpRequest.getTicket();
//String ticket=i+"";i++;
String sql ="update wx_ticket set uptdate=sysdate, ticket='"+ticket+"'";
jd.update(sql);
}
}
//然后是工具类weixinhttpRequest
public class weixinhttpRequest {
//测试帐号 这里的appid和AppSecret换成你们自己的
private static String appid="345634563465463456";
private static String AppSecret="342543643634563456346345634"
public static String getAppid(){
return appid;
}
public static String getTicket() throws Exception {
String token="";
String ticket="";
String gettoken=geturl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+AppSecret+"");
Gson gson=new Gson();
HashMap map = gson.fromJson(gettoken, HashMap.class);
token=(String) map.get("access_token");
String getticket = geturl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token="+token);
HashMap hashmap = gson.fromJson(getticket,HashMap.class);
ticket=(String) hashmap.get("ticket");
System.out.println(ticket);
return ticket;
}
private static String geturl(String geturl) throws Exception {
//请求的webservice的url
URL url = new URL(geturl);
//创建http链接
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置请求的方法类型
httpURLConnection.setRequestMethod("POST");
//设置请求的内容类型
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//设置发送数据
httpURLConnection.setDoOutput(true);
//设置接受数据
httpURLConnection.setDoInput(true);
//发送数据,使用输出流
OutputStream outputStream = httpURLConnection.getOutputStream();
//发送的soap协议的数据
// String requestXmlString = requestXml("北京");
String content = "user_id="+ URLEncoder.encode("13846", "gbk");
//发送数据
outputStream.write(content.getBytes());
//接收数据
InputStream inputStream = httpURLConnection.getInputStream();
//定义字节数组
byte[] b = new byte[1024];
//定义一个输出流存储接收到的数据
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//开始接收数据
int len = 0;
while (true) {
len = inputStream.read(b);
if (len == -1) {
//数据读完
break;
}
byteArrayOutputStream.write(b, 0, len);
}
//从输出流中获取读取到数据(服务端返回的)
String response = byteArrayOutputStream.toString();
return response;
}
}
//公众号中调用扫一扫时,需要获得config信息,controller中方法
@Autowired
private JdbcTemplate jd;
private String qrcode;
@RequestMapping(value = "/qrorder")
public String qrorder(HttpServletRequest request, HttpSession session, Model model) throws Exception {
//jsapi_ticket 从数据库中获取,下面这行代码可以根据自己的需求改成service调用,这里我用的是jdbctemplate
String jsapi_ticket = jd.queryForObject("select ticket from wx_ticket", String.class);
System.out.println(jsapi_ticket);
// 注意 URL 一定要动态获取,不能 hardcode
StringBuffer path = request.getRequestURL();
String url = path.toString();
System.out.println(url);
// url=url.split(":")[0];
try {
Sign.putSignToModel(request, model, jsapi_ticket, url);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "weixin/saoyisao";
}
//Sign工具类
public class Sign {
/**
* 获取前台config需要的验证信息
*
* @param jsapi_ticket
* @param url
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static Map<String, String> sign(String jsapi_ticket, String url)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
Map<String, String> ret = new HashMap<String, String>();
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);
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
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);
}
/**
* 将配置信息存入model中,方便前台页面配置初始化验证使用
*
* @param request
* @param model
* @param jsapi_ticket
* @param url
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static void putSignToModel(HttpServletRequest request, Model model, String jsapi_ticket, String url)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
Map<String, String> ret = sign(jsapi_ticket, url);
for (Map.Entry entry : ret.entrySet()) {
model.addAttribute((String) entry.getKey(), entry.getValue());
}
model.addAttribute("appid", weixinhttpRequest.getAppid());
}
}
最后是前台页面saoyisao.jsp
<%
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<script type='text/javascript' src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
$(function() {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '${appid}', // 必填,公众号的唯一标识
timestamp:'${timestamp}' , // 必填,生成签名的时间戳
nonceStr: '${nonceStr}', // 必填,生成签名的随机串
signature: '${signature}',// 必填,签名,见附录1
jsApiList: ['getLocation','scanQRCode'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
//$("#scanQRCode").click(function() {
/* wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
alert(res)
}
}); */
wx.ready(function(){
wx.scanQRCode({
// 默认为0,扫描结果由微信处理,1则直接返回扫描结果
needResult : 1,
desc : 'scanQRCode desc',
success : function(res) {
$.ajax({
type:"post",
url:"<%=basePath%>weixin/decode?result="+res.resultStr,
success:function(data){
}
});
}
});
});
})
</script>