主要也是参照https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
这么多代码就是为了获得一个签名
配置文件里面配置了Appid secrete,微信接口url等
@PostConstruct
@Scheduled(fixedDelay = 7000 * 1000)
public void initTicket() throws ServiceException{
try {
accessToken = getAccessToken();
if(StringUtils.isNotEmpty(accessToken)){
jsapiTicket = getJsapiTicket(accessToken);
}
if(jsapiTicket==null) {
Log.error(this.getClass(), jsapiTicket);
}
} catch (Exception e) {
Log.error(getClass(), e.getMessage());
throw new ServiceException(e.getMessage(), e);
}
}
public MapgetSign(String url) throws ServiceException{Map signMap = new HashMap<>();
signMap.put("noncestr", SystemUtil.generateNonceStr());
signMap.put("timestamp", String.valueOf(SystemUtil.getCurrentTimestamp()));
signMap.put("jsapi_ticket", jsapiTicket);
if(url.contains(ANGULAR_JS_MARK)){
signMap.put("url", url.substring(0, url.indexOf(ANGULAR_JS_MARK)));
} else {
signMap.put("url", url);
}
try {
signMap.put("signature", generateSignature(signMap));
} catch (Exception e) {
Log.error(getClass(), e.getMessage());
throw new ServiceException(e.getMessage(), e);
}
signMap.put("appId", SystemUtil.getValue("wx_app_id"));
signMap.remove("jsapi_ticket");
return signMap;
}
private String getAccessToken() throws Exception{
String url = SystemUtil.getValue("wx_jsapi_access_token_url");
url = url.replace("APPID", SystemUtil.getValue("wx_app_id"));
url = url.replace("SECRET", SystemUtil.getValue("wx_app_secret"));
JSONObject json = SystemUtil.request(url);
return json.getString("access_token");
}
private String getJsapiTicket(String accessToken) throws Exception{
if(!StringUtils.isEmpty(accessToken)){
String url = SystemUtil.getValue("wx_jsapi_ticket_url");
url = url.replace("ACCESS_TOKEN", accessToken);
JSONObject json = SystemUtil.request(url);
return json.getString("ticket");
}else{
return null;
}
}
private String generateSignature(Mapdata) throws Exception { Set keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for(String k : keyArray){
if(sb.length() > 0){
sb.append("&");
}
sb.append(k).append("=").append(data.get(k).trim());
}
return SHA1.encode(sb.toString()).toUpperCase();
}