用微信打開一個網頁,選擇右上角的“發送給朋友”后,收到的消息是這樣的:
而為了推廣效果,我們更希望能自定義標題、描述和圖片,效果如下圖:
下面介紹下怎樣來實現這個功能
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js" ></script> <script type="text/javascript"> var imgUrl = 'http://dev.mymax.cn/affix/manmanhouse/images/share.jpg'; var lineLink = 'http://dev.mymax.cn/affix/manmanhouse/index.html'; var descContent = '人類天生就愛玩游戲,游戲為什么吸引人?如果借助游戲的規律,是否可以讓工作學習變得更精彩?'; var shareTitle = '游戲化學習工作坊第四站-北京清華科技園'; var appid = ''; $.ajax({ type : 'POST', url : "http://dev.mymax.cn/running/comm/weixin/open/jsSDKConfig", //這個地址並非通用且長期有效,請去微信官方查看文檔,並自行配置 dataType : "json", data:{url:window.location.href}, success : function(response){ var appId = response.s.appId; var timestamp = response.s.timeStamp; var nonceStr = response.s.nonceStr; var signature = response.s.signature; wx.config({ debug: false, appId: appId, timestamp: timestamp, nonceStr: nonceStr, signature: signature, jsApiList: [ 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage' ] }); wx.ready(function() { wx.onMenuShareTimeline({ title: shareTitle, // 分享標題 link: lineLink, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 imgUrl: imgUrl, // 分享圖標 success: function () { // 用戶確認分享后執行的回調函數 }, cancel: function () { // 用戶取消分享后執行的回調函數 } }); wx.onMenuShareAppMessage({ title: shareTitle, // 分享標題 desc: descContent, // 分享描述 link: lineLink, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 imgUrl: imgUrl, // 分享圖標 type: '', // 分享類型,music、video或link,不填默認為link dataUrl:'' , // 如果type是music或video,則要提供數據鏈接,默認為空 success: function () { // 用戶確認分享后執行的回調函數 }, cancel: function () { // 用戶取消分享后執行的回調函數 } }); }); }, error:function(response){ window.parent.growl("刪除失敗["+response.responseText+"]!","error"); } }); </script>
上方代碼只為HTML中的部分,ajax的url地址並非通用且長期有效,還需要在微信公眾號中綁定同樣域名設置接口權限。
具體的方法請查看微信官方技術文檔:微信JS-SDK說明文檔,自行配置。