在做企业号开发的时候,很有可能会调用微信提供的js接口(JS-SDK), 那么使用JS-SDK必须生成权限验证签名,而生成权限验证签名又必须依赖jsapi_ticket,而获取jsapi_ticket又必须依赖AccessToken.
生成签名所需要的参数
appId,timestamp,noncestr,jsapi_ticket
在获取token之前要先获取到appId 与 appSecret
public class BgAccessToken {
String id;
String appId;
String appSecret;
String tokenValue;
Date lastUpdateDate;
Date creationDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
public String getTokenValue() {
return tokenValue;
}
public void setTokenValue(String tokenValue) {
this.tokenValue = tokenValue;
}
public Date getLastUpdateDate() {
return lastUpdateDate;
}
public void setLastUpdateDate(Date lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
}
public String getAccessToken(String appId, String appSecret) {
String accessToken;
try {
BgAccessToken accessTokenRec = bgAccessTokenService.findByAppId(appId); //WoaAccessToken.findByAppid(appid,[order:"desc",sort:"dateCreated"])
if (accessTokenRec != null) {
Long nowTime = new Date().getTime();
if (nowTime - accessTokenRec.getCreationDate().getTime() < 7200) {
accessToken = accessTokenRec.getTokenValue();
return accessToken;
}
}
accessToken = this.getNewAccessToken(appId,appSecret);
BgAccessToken newTokenRec = new BgAccessToken();
newTokenRec.setAppId(appId);
newTokenRec.setTokenValue(accessToken);
IRequest iRequest = RequestHelper.newEmptyRequest();
bgAccessTokenService.insertSelective(iRequest, newTokenRec);
return accessToken;
} catch (Exception e) {
e.printStackTrace();
//报错的话也要获得token
accessToken = this.getNewAccessToken(appId,appSecret);
if (accessToken == null) {
logger.error("get accesstoken again,but it is: " + accessToken);
}
return accessToken;
}
}
public String getNewAccessToken(String appId,String appSecret) {
// String appId = getAppId("");
String access_token = null;
// String https_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
String https_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + appId + "&corpsecret=" + appSecret;
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer sb = new StringBuffer();
String oneLine = new String("");
while ((oneLine = br.readLine()) != null) {
sb.append(oneLine);
}
JSONObject jsonObject = JSONObject.fromObject(sb.toString());
Object object = jsonObject.get("access_token");
if (object != null) {
access_token = String.valueOf(object);
}
con.disconnect();
br.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return access_token;
}
public String getJsApiTicket(){
String appId = this.getAppId();
String appSecret = this.getAppSecret();
String accessToken = this.getAccessToken(appId,appSecret);
System.out.println("获取ticket时获取的token"+accessToken);
String ticket = null;
String apiTicketUrl = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+accessToken;
URL url;
try {
url = new URL(apiTicketUrl);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer sb = new StringBuffer();
String oneLine = new String("");
while ((oneLine = br.readLine()) != null) {
sb.append(oneLine);
}
JSONObject jsonObject = JSONObject.fromObject(sb.toString());
Object object = jsonObject.get("ticket");
if (object != null) {
ticket = String.valueOf(object);
}
con.disconnect();
br.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return ticket;
}
=================================================================================================
在这里我写了个controller,将参数以Map的形式发给前端
@Controller
public class JSTicketWxController {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private IWxService wxService;
//获取微信参数,因为前端传来的url为json形式,采用@ResponsBody来接收
@RequestMapping(value = "/wechatParam",method = RequestMethod.POST)
@ResponseBody
public Map getWechatParam(@RequestBody JSONObject param){
String urlStr = param.getString("url");
System.out.println("json传来的url"+urlStr);
//当前时间
long now = System.currentTimeMillis();
log.info("currentTime====>"+now+"ms");
String jsApiTicket = wxService.getJsApiTicket();
System.out.println("获取到的ticket"+jsApiTicket);
//生成微信权限验证的参数
Map wechatParam= makeWXTicket(jsApiTicket,urlStr);
return wechatParam;
}
/**
* 功能描述: 生成微信权限验证的参数
*
* @Param: [jsApiTicket, url]
* @Return: java.util.Map
* @Author:
* @Date: 2019-07-18 19:39
*/
public Map makeWXTicket(String jsApiTicket,String url) {
Map ret = new HashMap();
String nonceStr = "Wm3WZYTPz0wzccnW";
String timestamp = createTimestamp();
String string1;
String signature = "";
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsApiTicket +
"&noncestr=" + nonceStr +
"×tamp=" + timestamp +
"&url=" + url;
log.info("String1=====>"+string1);
System.out.println("String1===="+string1);
String ciphertext=null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(string1.toString().getBytes());
ciphertext=byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String appId = wxService.getAppId();
ret.put("url", url);
ret.put("jsapi_ticket", jsApiTicket);
ret.put("noncestr", nonceStr);
ret.put("timestamp", timestamp);
ret.put("signature", ciphertext);
ret.put("appId", appId);
System.out.println("返回给前端的值"+ret.toString());
return ret;
}
public static String byteToStr(byte[] byteArray){
String strDigest="";
for (int i = 0; i < byteArray.length; i++) {
strDigest+=byteToHexStr(byteArray[i]);
}
return strDigest;
}
//字节数组转换为十六进制字符串
public static String byteToHexStr(byte mByte){
char[] Digit={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char[] tempArr = new char[2];
tempArr[0]=Digit[(mByte>>>4)&0X0F];
tempArr[1]=Digit[mByte&0X0F];
String s=new String(tempArr);
return s;
}
//生成时间戳
private static String createTimestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
=================================================================================================
将文件放在tomcat的webapps的ROOT目录下
然后选择已上传域名归属校验文件
点击确定,即可验证完毕
接下来就可以在前端使用JS_SDK进行开发了
因为我只是个写后端的,前端咋写我不会,所以就不写了
第一次发帖,有不对的地方欢迎大家多多指正