微信分享接口配置和調用

步驟一:綁定域名

先登錄微信公衆平臺進入“公衆號設置”的“功能設置”裏填寫“JS接口安全域名”。

步驟二:引入JS文件

在需要調用JS接口的頁面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.js

請注意,如果你的頁面啓用了https,務必引入 https://res.wx.qq.com/open/js/jweixin-1.0.0.js ,否則將無法在iOS9.0以上系統中成功使用JSSDK

如需使用搖一搖周邊功能,請引入 jweixin-1.1.0.js

備註:支持使用 AMD/CMD 標準模塊加載方法加載

步驟三:通過config接口注入權限驗證配置

所有需要使用JS-SDK的頁面必須先注入配置信息,否則將無法調用(同一個url僅需調用一次,對於變化url的SPA的web app可在每次url變化時進行調用,目前Android微信客戶端不支持pushState的H5新特性,所以使用pushState來實現web app的頁面會導致簽名失敗,此問題會在Android6.2中修復)。

wx.config({
    debug: true, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
    appId: '', // 必填,公衆號的唯一標識
    timestamp: , // 必填,生成簽名的時間戳
    nonceStr: '', // 必填,生成簽名的隨機串
    signature: '',// 必填,簽名,見附錄1
    jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
});

步驟四:通過ready接口處理成功驗證

wx.ready(function(){

    // config信息驗證後會執行ready方法,所有接口調用都必須在config接口獲得結果之後,config是一個客戶端的異步操作,所以如果需要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則可以直接調用,不需要放在ready函數中。
});


步驟五:通過error接口處理失敗驗證

wx.error(function(res){

    // config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這裏更新簽名。

});

步驟六:具體接口調用,調用之前要獲取接口調用憑據,具體如下

1.配置文件 application-common.properties 配置一些接口常量信息

[html] view plain copy
  1. #\u5FAE\u4FE1AppID  
  2. AppID=wx0a5aabbccddees  
  3.   
  4. #\u5FAE\u4FE1AppSecret  
  5. AppSecret=f1ec0d65d104589ds0opke907dslsjeln09  

2.工具類ConfigHelper,讀取配置文件:

[java] view plain copy
  1. package com.hengxin.qianee.commons;  
  2.   
  3. import java.util.ResourceBundle;  
  4.   
  5. /** 
  6.  * 讀取配置文件 
  7.  * @author hzg 
  8.  * 
  9.  */  
  10. public class ConfigHelper {  
  11.     private static Object lock = new Object();  
  12.     private static ConfigHelper config = null;  
  13.     private static ResourceBundle rb = null;  
  14.       
  15.     private ConfigHelper(String configFileName) {  
  16.         rb = ResourceBundle.getBundle(configFileName);  
  17.     }  
  18.       
  19.     public static ConfigHelper getInstance(String configFileName) {  
  20.         synchronized(lock) {  
  21.             if(null == config) {  
  22.                 config = new ConfigHelper(configFileName);  
  23.             }  
  24.         }  
  25.         return (config);  
  26.     }  
  27.       
  28.     public String getValue(String key) {  
  29.         return (rb.getString(key));  
  30.     }  
  31.       
  32. }  

3.獲取簽名信息

[java] view plain copy
  1. package com.hengxin.qianee.talent.wechat.utils;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.util.Date;  
  8. import java.util.HashMap;  
  9. import java.util.Map;  
  10. import java.util.UUID;  
  11.   
  12. import javax.servlet.http.HttpServletRequest;  
  13.   
  14. import org.apache.http.HttpEntity;  
  15. import org.apache.http.HttpResponse;  
  16. import org.apache.http.HttpStatus;  
  17. import org.apache.http.client.HttpClient;  
  18. import org.apache.http.client.methods.HttpGet;  
  19. import org.springframework.beans.factory.annotation.Autowired;  
  20.   
  21. import com.alibaba.fastjson.JSON;  
  22. import com.alibaba.fastjson.JSONObject;  
  23. import com.hengxin.qianee.cache.impl.MyCache;  
  24. import com.hengxin.qianee.commons.ConfigHelper;  
  25. import com.hengxin.qianee.service.thirdparty.pay.llpay.conn.CustomHttpClient;  
  26.   
  27. public class WechatSignUtil {  
  28.       
  29.     @Autowired  
  30.     MyCache cache;  
  31.   
  32.       
  33.     public static JSONObject sendGetRequest(String url){  
  34.         HttpClient httpClient = CustomHttpClient.GetHttpClient();  
  35.         HttpGet get = new HttpGet(url);  
  36.         get.setHeader("Content-Type",  
  37.                 "application/x-www-form-urlencoded;charset=utf-8");  
  38.         BufferedReader br = null;  
  39.           
  40.         try {  
  41.             // 發送請求,接收響應  
  42.             HttpResponse resp = httpClient.execute(get);  
  43.             int ret = resp.getStatusLine().getStatusCode();  
  44.             if(ret == HttpStatus.SC_OK){  
  45.                 // 響應分析  
  46.                 HttpEntity entity = resp.getEntity();  
  47.                 br = new BufferedReader(new InputStreamReader(  
  48.                         entity.getContent(), "UTF-8"));  
  49.                 StringBuffer responseString = new StringBuffer();  
  50.                 String str = br.readLine();  
  51.                 while (str != null) {  
  52.                     responseString.append(str);  
  53.                     str = br.readLine();  
  54.                 }  
  55.                 return JSON.parseObject(responseString.toString());  
  56.             }  
  57.         }catch(Exception e){  
  58.             e.printStackTrace();  
  59.         }finally {  
  60.             if (br != null) {  
  61.                 try {  
  62.                     br.close();  
  63.                 } catch (IOException e) {  
  64.                     // do nothing  
  65.                 }  
  66.             }  
  67.         }  
  68.         return new JSONObject();  
  69.     }  
  70.       
  71.     /** 
  72.      * 獲取簽名信息 
  73.      * @return 返回簽名等 
  74.      */  
  75.     public Map<String,String> getWechatSign(HttpServletRequest request,MyCache cache) throws UnsupportedEncodingException{  
  76.         String appid = ConfigHelper.getInstance("config").getValue("AppID");  
  77.         String appSecret = ConfigHelper.getInstance("config").getValue("AppSecret");  
  78.         String url_Template_GetAccessToken ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";  
  79.         String url_Template_GetAccessTicket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";  
  80.           
  81.         String accessToken = cache.getString("wechatAccessToken");  
  82.         if(accessToken == null){  
  83.             //獲取token  
  84.             String url_GetAccessToken = String.format(url_Template_GetAccessToken, appid,appSecret);  
  85.             JSONObject accessTokenMap = WechatSignUtil.sendGetRequest(url_GetAccessToken);  
  86.             accessToken = accessTokenMap.getString("access_token");  
  87.             cache.setString("wechatAccessToken"6000, accessToken);  
  88.         }  
  89.           
  90.         String accessTicket = cache.getString("wechatAccessTicket");  
  91.         if(accessTicket == null){  
  92.             //獲取ticket  
  93.             String url_GetAccessTicket = String.format(url_Template_GetAccessTicket, accessToken);  
  94.             JSONObject url_GetAccessTicketMap = WechatSignUtil.sendGetRequest(url_GetAccessTicket);  
  95.             accessTicket = url_GetAccessTicketMap.getString("ticket");  
  96.             cache.setString("wechatAccessTicket"6000, accessTicket);  
  97.         }  
  98.           
  99.         // 時間戳  
  100.         Long timeStamp = new Date().getTime()/1000;  
  101.           
  102.         String url = request.getRequestURL().toString();  
  103.           
  104.         //隨機字串  
  105.         String noncestr = UUID.randomUUID().toString();  
  106.           
  107.         //簽名  
  108.         String signature = getSignature(noncestr,accessTicket,url,timeStamp);  
  109.           
  110.         Map<String,String> result = new HashMap<String,String>();  
  111.         result.put("appId", appid);  
  112.         result.put("timestamp", timeStamp.toString());  
  113.         result.put("nonceStr", noncestr);  
  114.         result.put("signature", signature);  
  115.           
  116.         return result;  
  117.     }  
  118.       
  119.     /** 
  120.      * 生成簽名 
  121.      * @param nonceStr 隨機字串 
  122.      * @param jsapi_ticket 票據 
  123.      * @param url  
  124.      * @param timestamp 時間戳 
  125.      * @return 
  126.      */  
  127.     private String getSignature(String nonceStr,String jsapi_ticket,String url,Long timestamp){  
  128.         String template = "jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s";  
  129.         String result = String.format(template, jsapi_ticket,nonceStr,timestamp,url);  
  130.           
  131.         return org.apache.commons.codec.digest.DigestUtils.shaHex(result);  
  132.     }  
  133. }  

總結:先配置好域名,先根據appid和appSecret拼成的串發送請求獲取到一個JSONObject對象,通過該對象調用getString("access_token")方法取到token;

根據token拼成的url發送一個http get請求得到JSONObject對象,通過調用該對象的.getString("ticket")方法得到ticket

根據時間戳、隨機串、當然訪問的url和ticket生產簽名,也就是接口調用的憑據。最後jsp頁面調用如下:

[html] view plain copy
  1. <script type="text/javascript"  
  2.     src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>  
  3. <style type="text/css">  
  4.   
  5. </style>  
  6. <script type="text/javascript">  
  7.     wx.config({  
  8.         debug : false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。  
  9.         appId : "${appId}", // 必填,公衆號的唯一標識  
  10.         timestamp : "${timestamp}", // 必填,生成簽名的時間戳  
  11.         nonceStr : "${nonceStr}", // 必填,生成簽名的隨機串  
  12.         signature : "${signature}",// 必填,簽名,見附錄1  
  13.         jsApiList : [ 'onMenuShareTimeline', 'onMenuShareAppMessage',  
  14.                 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone' ]  
  15.     });  
  16.     var obj = {  
  17.         title : '標題',  
  18.         desc : '歡迎關注!',  
  19.         link : 'http://m.test.com',  
  20.         imgUrl : 'https://qianee-official.oss-cn-beijing.aliyuncs.com/data/2016-05-21%2Fe382d374-f3c5-45bb-b8cedlsjelnge',  
  21.     };  
  22.     wx.ready(function(){  
  23.         wx.onMenuShareAppMessage(obj);  
  24.       
  25.         // 2.2 監聽“分享到朋友圈”按鈕點擊、自定義分享內容及分享結果接口  
  26.         wx.onMenuShareTimeline(obj);  
  27.           
  28.         // 2.3 監聽“分享到QQ”按鈕點擊、自定義分享內容及分享結果接口  
  29.         wx.onMenuShareQQ(obj);  
  30.           
  31.         // 2.4 監聽“分享到微博”按鈕點擊、自定義分享內容及分享結果接口  
  32.         wx.onMenuShareWeibo(obj);  
  33.     });  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章