wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,公众号的唯一标识
timestamp: '' , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名
jsApiList: [] // 必填,需要使用的JS接口列表
});
这三个参数都是在你点击验证的时候 通过url get的方式返回给到你的。
timestamp为当前的时间戳 就是服务器的时间转换为的毫秒数
nonceStr是自己写的一个随机字符串
jsapi_ticket 呢要先获取access_token
有了access_token 比如你获取到的access_token为abc 后呢发送这个https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=abc&type=jsapi
你就会得到一个json格式的数据 里面就包含有jsapi_ticket
具体方式如下:
package com.test.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class CheckUtil {
private static final String token = "mytest";
public static boolean checkSignature(String signaure, String timestamp,
String nonce) {
String[] arr = new String[] {token, timestamp, nonce };
// 排序
Arrays.sort(arr);
// 生成字符串
StringBuffer content = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
content.append(arr);
}
// sha1加密
String temp = getSha1(content.toString());
return temp.equals(signaure);
}
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;
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
String jsapi_ticket = req.getParameter("jsapi_ticket");
if(CheckUtil.checkSignature(signature, timestamp, nonce)){
System.out.println("nonce:"+nonce);
System.out.println("timestamp:"+timestamp);
System.out.println("signature:"+signature);
System.out.println("echo:"+echostr);
out.print(echostr);
}
还请认真看一下官方api
最后对拼接出来的字符串用sha1签名,得到sign。放入config的参数里。