在调用js-sdk的第一步,我们需要引入js-sdk的js链接,然后执行wx.config,官方示例如下所示:

 wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,企业号的唯一标识,此处填写企业号corpid
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名,见附录1
jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});

一、分析参数:

1. appId我们可以通过后端读取配置文件读取出来传递到前端。

2. timestamp是前端生成还是后端生成都OK,我这里是用的异步获取签名等参数,所以我这个案例是使用前端生成时间戳。

3. nonceStr是一个随机串,java中采用UUID来生成这个随机串。

4. signature是一个签名,这个是需要java后端根据以上三个参数来组成一个字符串,然后再对这个字符串进行sha1加密得到的。微信官方还给出了一个用于在线校验签名的工具

二、后端接口部分:

1. 我们需要直接准备的是 appId 、secret、noncestr,appId 在企业号中为 CorpId,这两个参数可以从微信企业号后台得到。noncestr 为随机串,采用UUID生成,方法如下:

public static String create_noncestr() {
return UUID.randomUUID().toString();
}

2. 因为最终需要正确地生成signature签名,而生成签名需要四个参数,即 jsapi_ticket、noncestr、timestamp、url,在这四个参数重,jsapi_ticket是需要获取到的,而获取jsapi_ticket又需要先获取到access_token,所以以下代码就依次获取这些参数来做一个展示:

         /**
* 获取access_token
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/getAccessToken")
public void getAccessToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CORPID+"&corpsecret="+CORPSECRET;
processUrl(response, urlStr);
} /**
* 获取jsapi_ticket
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/getJsapiTicket")
public void getJsapiTicket(HttpServletRequest request, HttpServletResponse response) throws Exception {
String access_token = request.getParameter("access_token");
String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+access_token;
processUrl(response, urlStr);
} /**
* 获取签名signature
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/getJsSdkSign")
public void getJsSdkSign(HttpServletRequest request, HttpServletResponse response) throws Exception {
String noncestr = request.getParameter("noncestr");
String tsapiTicket = request.getParameter("jsapi_ticket");
String timestamp = request.getParameter("timestamp");
String url = request.getParameter("url");
String jsSdkSign = getJsSdkSign(noncestr, tsapiTicket, timestamp, url);
PrintWriter out = response.getWriter();
out.print(jsSdkSign);
} private void processUrl(HttpServletResponse response, String urlStr) {
URL url;
try {
url = new URL(urlStr);
URLConnection URLconnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream urlStream = httpConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));
String sCurrentLine = "";
String sTotalString = "";
while ((sCurrentLine = bufferedReader.readLine()) != null) {
sTotalString += sCurrentLine;
}
PrintWriter out = response.getWriter();
out.print(sTotalString);
}else{
System.err.println("失败");
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 获得加密后的签名
* @param noncestr
* @param tsapiTicket
* @param timestamp
* @param url
* @return
*/
public static String getJsSdkSign(String noncestr,String tsapiTicket,String timestamp,String url){
String content="jsapi_ticket="+tsapiTicket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
String ciphertext=getSha1(content); return ciphertext;
} /**
* 进行sha1加密
* @param str
* @return
*/
public static String getSha1(String str){
if(str==null||str.length()==0){
return null;
}
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j*2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// TODO: handle exception
return null;
}
} /**
* 获得随机串
* @return
*/
public static String create_noncestr() {
return UUID.randomUUID().toString();
}

三、前端请求部分:

 var weixin = false;
$.ajax({
dataType:"json",
url: "${ctx.contextPath}/wechat/getAccessToken",
success: function(data){
$.getJSON("${ctx.contextPath}/wechat/getJsapiTicket",
{
access_token:data.access_token //获取的access_token
},
function(result){
var time=parseInt((new Date().getTime())/1000);
$.get("${ctx.contextPath}/wechat/getJsSdkSign",
{
noncestr:"${noncestr!""}",
jsapi_ticket:result.ticket,//获取的jsapi_ticket
timestamp:time,
url:location.href.split('#')[0]
},
function(sign){
wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
       appId: '${appId!""}', // 必填,企业号的唯一标识,此处填写企业号corpid
       timestamp: time, // 必填,生成签名的时间戳
       nonceStr: '${noncestr!""}', // 必填,生成签名的随机串
       signature: sign,// 必填,签名,见附录1
       jsApiList: ['uploadImage', 'chooseImage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
      });
}
);
}
);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
}
});
wx.ready(function(){
weixin = true;
});

ps:案例仅供参考,接口因人而异。谢谢大家~

fullStack.yang

2016-12-26于成都高新区天府软件园

04-30 08:31