Java:
@ResponseBody
@RequestMapping(value = "/wechat/jsApiTicket", method = RequestMethod.GET)
public JsonResponse getJsApiTicket(HttpServletRequest request) {
String jsapi_ticket= "HoagFKDcsGMVCIY2vOjf9kwlKC1UuXueXYiKtTHCeeFxK7VEtmGiR4nWiWC002Wx0JSUSz8kMcMJmpVg2Xbn_g";
return JsonResponse.success(sign(jsapi_ticket,request.getQueryString()));
}
public static Map<String, String> sign(String jsapi_ticket, String url) {
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);
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();
}
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);
}
前端
uxfn.get({
url: '../../sys/wechat/jsApiTicket?'+encodeURIComponent(location.href.split('#')[0]),
success: function (data) {
console.log(data.data)
let myappid= "wxc99325e1a29dd4fd"
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: "wxc99325e1a29dd4fd", // 必填,公众号的唯一标识
timestamp:data.data.timestamp.toString(), // 必填,生成签名的时间戳
nonceStr: data.data.nonceStr.toString(), // 必填,生成签名的随机串
signature: data.data.signature,// 必填,签名
jsApiList: ['chooseImage'] // 必填,需要使用的JS接口列表
})
}
})
URL ?