importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Component;importorg.springframework.transaction.annotation.Transactional;importjava.io.UnsupportedEncodingException;importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;importjava.util.Formatter;importjava.util.HashMap;importjava.util.Map;importjava.util.UUID;
@Component("wxJsService")
@Transactionalpublic classJsApiService{
@Autowired
@Qualifier("wxService")privateWxService wxService;public Mapsign(String url) {
Map ret = new HashMap();
String jsapiTicket=wxService.getJsApiTicket();//这里的jsapi_ticket是获取的jsapi_ticket。
String nonceStr=createNonceStr();
String timestamp=createTimestamp();
String string1;
String signature= "";//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapiTicket +
"&noncestr=" + nonceStr +
"×tamp=" + timestamp +
"&url=" +url;
System.out.println("string1:"+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", jsapiTicket);
ret.put("nonceStr", nonceStr);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
ret.put("appId", "wx4c544fd0d116dedd");returnret;
}private static String byteToHex(final byte[] hash) {
Formatter formatter= newFormatter();for (byteb : hash)
{
formatter.format("%02x", b);
}
String result=formatter.toString();
formatter.close();returnresult;
}private staticString createNonceStr() {returnUUID.randomUUID().toString();
}private staticString createTimestamp() {return Long.toString(System.currentTimeMillis() / 1000);
}
}