這里只談HTML界面的微信分享。安卓和IOS均有對應的API包。
HTML界面的分享,是2015元旦期間微信刪掉了老的 WeixinJSBridge 方式(原因是微信無法管理它),
推出了需要鑒權、並和公眾號綁定的JS JDK。
默認分享
特征
無需引用JDK。微信自動讀取網頁標題、網頁第一張圖片、location.href 三元素作為分享內容。
步驟
<head> <!--1,設置標題--> <title>這是我設的微信默認分享</title> </head> <body> <!--2, 設置圖片--> <img src=http://image5.suning.cn/b2c/catentries/000000000124346362_1_400x400.jpg width='0' height='0' /> </body>
測試
測試頁面
可以在PC端打開看到源碼
注意點
微信讀不到圖片的情況分以下幾種
1 圖片<= 300PX*300PX,微信可能讀不到圖
2 圖片 style不能設置Display:none
3 圖片盡量放到body下第一個元素
自定義分享
特征
引入微信JS JDK,通過微信鑒權,注入自定義標題、內容、圖片,鏈接分享
步驟
1 設置JS安全域名 登錄公眾號--公眾號設置--功能設置
2 引入微信JS JDK <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"> </script>
3 配置微信鑒權消息
<!--請求后台,生成鑒權消息。后台需要做緩存。2小時內從緩存里讀。原因是鑒權信息里的簽名兩小時后失效,需重新生成。--> <!--后台如何生成鑒權消息? 以java為例,前端提供URL地址,后台進行sha1加密。然后將鑒權消息返回前端。--> <!--然后前端配置鑒權消息--> <!--前端代碼--> <script> $.ajax({ url: 'XXXX.do', data:{ shareUrl:encodeURI(location.href) }, success:function(data){ wx.config({ debug: false, appId: Const.APP_ID, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: [ 'onMenuShareTimeline', 'onMenuShareAppMessage', 'hideMenuItems', 'showMenuItems' ] }); }, error:function(data){ console.error('req '+ Const.CHECK_WECHAT + " error "+data); } }); </script>
4 注入分享
var shareConfig = { "imgUrl": config.shareIcon || Const.SHARE_IMG, "link": config.url || location.href, "desc": config.shareContent || Const.SHARE_DESC, "title": config.title || Const.SHARE_TITLE }; wx.ready(function () { wx.checkJsApi({ jsApiList: [ 'onMenuShareTimeline', 'onMenuShareAppMessage', 'hideMenuItems', 'showMenuItems' ], success: function (res) { } }); wx.onMenuShareAppMessage(shareConfig); wx.onMenuShareTimeline(shareConfig); });
測試
微信JDK 步驟的詳細說明文檔 http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
實際運用
注意點
1 若分享不對,開啟微信的debug模式,觀察彈出的異常信息,去http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html此頁面查找異常原因
debug模式開啟
wx.config({ debug: true //設為true開啟debug,上線時設為false
...