tech.mhuang.pacebox.springboot.wechat.wechat.common.util.WechatJSTicketUtil Maven / Gradle / Ivy
package tech.mhuang.pacebox.springboot.wechat.wechat.common.util;
import tech.mhuang.pacebox.core.timer.SystemClock;
import tech.mhuang.pacebox.core.util.CryptoUtil;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 微信JS凭证工具类
*
* @author mhuang
* @since 1.0.0
*/
public class WechatJSTicketUtil {
public static Map sign(String jsapiTicket, String url) {
Map ret = new HashMap<>();
String nonceStr = createNonceStr(),
timestamp = createTimestamp(),
string1,
signature = "";
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapiTicket +
"&noncestr=" + nonceStr +
"×tamp=" + timestamp +
"&url=" + url;
try {
signature = CryptoUtil.encrypt(string1, "SHA-1");
} 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);
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 createNonceStr() {
return UUID.randomUUID().toString();
}
private static String createTimestamp() {
return Long.toString(SystemClock.now() / 1000);
}
}