基於Java spring框架的微信企業號開發中關於js-sdk的配置


  在調用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於成都高新區天府軟件園


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM