1.配置
需要注意的是:
(1)域名不能带http://或者https://
(2)需要下载文件 MP_verify_dRk8DCHUcYJUDMuQ.txt 放入到系统,并且使用域名可以访问到文件,否则保存不成功
测试号:
注意:域名不能带http://或https://就可以了
2.引入 js 路径:
http://res.wx.qq.com/open/js/jweixin-1.2.0.js 或 https://res.wx.qq.com/open/js/jweixin-1.2.0.js
3.生成签名
public JSONObject autograph(String url) throws Exception{
JSONObject json = null;
try {
String noncestr = UUID.randomUUID().toString();//随机字符串
Long timestamp = new Date().getTime();//时间戳
String jsapiTicket = getJsapiTicket();
String string1 = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
String signature = null;//签名
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.reset();
md.update(string1.getBytes("UTF-8"));
signature = sha1(md.digest());
json = new JSONObject();
json.put("status", true);
json.put("url", url);
json.put("noncestr", noncestr);
json.put("timestamp", timestamp);
json.put("signature", signature);
json.put("appId", WeixinInfo.appId);
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
/**
* 字节数组转换成十六进制字符串
* @param bytes 字节数组
* @return
*/
public String sha1(byte[] bytes){
StringBuffer buf = new StringBuffer();
for(byte b : bytes){
String shaHex = Integer.toHexString(b & 0xFF);
if(shaHex.length() < 2)
buf.append(0);
buf.append(shaHex);
}
return buf.toString();
}
jsp页面:
var url = location.href.split("#")[0];
sendPost("${ctxpath}/weixin/daily-management/autograph", '{"url":"' + url + '","wechat":"${wechat}"}', function(data){
var json = JSON.parse(data);
if(json.status){
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: json.appId, // 必填,公众号的唯一标识
timestamp: json.timestamp, // 必填,生成签名的时间戳
nonceStr: json.noncestr, // 必填,生成签名的随机串
signature: json.signature,// 必填,签名,见附录1
jsApiList: ["scanQRCode"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
//微信扫一扫
wx.ready(function(){
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
console.log(result);
}
});
});
}
});
注意:要用异步请求获取签名,否则会提示:无效签名 invalid signatur 。我之前遇到这个情况
在iframe中使用JSSDK,直接使用是不行的,即使在子页面中重新生成签名也不能使用,正确使用方法是:parent.wx.xxxxx。
例如:我在主页面生成签名在子页面中使用parent.wx.xxxxx,否则一直会没有反应