码迷,mamicode.com
首页 > 微信 > 详细

基于Java spring框架的微信企业号开发中关于js-sdk的配置

时间:2016-12-27 00:44:39      阅读:506      评论:0      收藏:0      [点我收藏+]

标签:false   dig   cipher   配置文件   bin   ace   ext   字符串   amp   

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

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

一、分析参数:

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,所以以下代码就依次获取这些参数来做一个展示:

  1         /**
  2      * 获取access_token
  3      * @param request
  4      * @param response
  5      * @throws Exception
  6      */
  7     @RequestMapping("/getAccessToken")  
  8     public void getAccessToken(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  9         String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CORPID+"&corpsecret="+CORPSECRET;    
 10         processUrl(response, urlStr);    
 11     }  
 12       
 13     /**
 14      * 获取jsapi_ticket
 15      * @param request
 16      * @param response
 17      * @throws Exception
 18      */
 19     @RequestMapping("/getJsapiTicket")  
 20     public void getJsapiTicket(HttpServletRequest request, HttpServletResponse response) throws Exception {  
 21         String access_token = request.getParameter("access_token");  
 22         String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+access_token;    
 23         processUrl(response, urlStr);    
 24     }  
 25     
 26     /**
 27      * 获取签名signature
 28      * @param request
 29      * @param response
 30      * @throws Exception
 31      */
 32     @RequestMapping("/getJsSdkSign")  
 33     public void getJsSdkSign(HttpServletRequest request, HttpServletResponse response) throws Exception {  
 34         String noncestr = request.getParameter("noncestr");  
 35         String tsapiTicket = request.getParameter("jsapi_ticket");  
 36         String timestamp = request.getParameter("timestamp");  
 37         String url = request.getParameter("url");  
 38         String jsSdkSign = getJsSdkSign(noncestr, tsapiTicket, timestamp, url);  
 39         PrintWriter out = response.getWriter();  
 40         out.print(jsSdkSign);  
 41     }  
 42       
 43     private void processUrl(HttpServletResponse response, String urlStr) {  
 44         URL url;  
 45         try {  
 46             url = new URL(urlStr);  
 47             URLConnection URLconnection = url.openConnection();    
 48             HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;    
 49             int responseCode = httpConnection.getResponseCode();    
 50             if (responseCode == HttpURLConnection.HTTP_OK) {    
 51                 InputStream urlStream = httpConnection.getInputStream();    
 52                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));    
 53                 String sCurrentLine = "";    
 54                 String sTotalString = "";    
 55                 while ((sCurrentLine = bufferedReader.readLine()) != null) {    
 56                     sTotalString += sCurrentLine;    
 57                 }    
 58                 PrintWriter out = response.getWriter();  
 59                 out.print(sTotalString);  
 60             }else{  
 61                 System.err.println("失败");  
 62             }  
 63         } catch (Exception e) {  
 64             e.printStackTrace();  
 65         }  
 66     }         
 67 
 68         /**
 69      * 获得加密后的签名
 70      * @param noncestr
 71      * @param tsapiTicket
 72      * @param timestamp
 73      * @param url
 74      * @return
 75      */
 76     public static String getJsSdkSign(String noncestr,String tsapiTicket,String timestamp,String url){  
 77         String content="jsapi_ticket="+tsapiTicket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;  
 78         String ciphertext=getSha1(content);  
 79         
 80         return ciphertext;  
 81     }  
 82     
 83     /**
 84      * 进行sha1加密
 85      * @param str
 86      * @return
 87      */
 88     public static String getSha1(String str){
 89         if(str==null||str.length()==0){
 90             return null;
 91         }
 92         char hexDigits[] = {‘0‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘,
 93                 ‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘};
 94         try {
 95             MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
 96             mdTemp.update(str.getBytes("UTF-8"));
 97 
 98             byte[] md = mdTemp.digest();
 99             int j = md.length;
100             char buf[] = new char[j*2];
101             int k = 0;
102             for (int i = 0; i < j; i++) {
103                 byte byte0 = md[i];
104                 buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
105                 buf[k++] = hexDigits[byte0 & 0xf];      
106             }
107             return new String(buf);
108         } catch (Exception e) {
109             // TODO: handle exception
110             return null;
111         }
112     }
113     
114     /**
115      * 获得随机串
116      * @return
117      */
118     public static String create_noncestr() {
119         return UUID.randomUUID().toString();
120     }

三、前端请求部分:

 1 var weixin = false;
 2 $.ajax({  
 3         dataType:"json",  
 4         url: "${ctx.contextPath}/wechat/getAccessToken",  
 5         success: function(data){  
 6              $.getJSON("${ctx.contextPath}/wechat/getJsapiTicket",  
 7                   {  
 8                     access_token:data.access_token  //获取的access_token  
 9                   },  
10                   function(result){  
11                       var time=parseInt((new Date().getTime())/1000);  
12                       $.get("${ctx.contextPath}/wechat/getJsSdkSign",  
13                         {  
14                             noncestr:"${noncestr!""}",  
15                             jsapi_ticket:result.ticket,//获取的jsapi_ticket  
16                             timestamp:time,  
17                             url:location.href.split(‘#‘)[0]  
18                         },  
19                         function(sign){  
20                             wx.config({
21                           debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
22                           appId: ‘${appId!""}‘, // 必填,企业号的唯一标识,此处填写企业号corpid
23                           timestamp: time, // 必填,生成签名的时间戳
24                           nonceStr: ‘${noncestr!""}‘, // 必填,生成签名的随机串
25                           signature: sign,// 必填,签名,见附录1
26                           jsApiList: [‘uploadImage‘, ‘chooseImage‘] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
27                       });
28                         }  
29                       );  
30                   }  
31                );  
32             },  
33         error:function(XMLHttpRequest, textStatus, errorThrown){  
34         }  
35     });  
36  wx.ready(function(){
37      weixin = true;
38  });

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

fullStack.yang

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

基于Java spring框架的微信企业号开发中关于js-sdk的配置

标签:false   dig   cipher   配置文件   bin   ace   ext   字符串   amp   

原文地址:http://www.cnblogs.com/fullstack-yang/p/6224228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!