微信給我們提供了自定義的分享平臺。
一、綁定域名:
登錄微信公衆平臺,進入“公衆號設置”的“功能設置”裏填寫“JS接口安全域名”
二、引入JS文件
在需要調用JS接口的頁面引入JS文件:http://res.wx.qq.com/open/js/jweixin-1.0.0.js
三、通過config接口注入權限驗證配置
在需要自定義分享的頁面必須注入配置信息:
例如:
<span style="font-size:18px;"> wx.config({
debug: false,
appId: '${map.appId}',
timestamp: '${map.timestamp}',
nonceStr: '${map.nonceStr}',
signature: '${map.signature}',
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'translateVoice',
'startRecord',
'stopRecord',
'onRecordEnd',
'playVoice',
'pauseVoice',
'stopVoice',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
]
});
</span>
其中:appId 必填,是公衆號的唯一標識;timestamp必填,生成簽名的時間戳;nonceStr必填,生成簽名的隨機串(例如:UUID);signature必填,需要簽名機制來生成;jsApiList:[]必填,需要使用的JS接口列表。
四、通過ready接口處理成功驗證:
<span style="font-size:18px;"> wx.ready(function () {
var shareData = {
title: '${newsItem.title}',//分享標題
desc: '${newsItem.description}',//分享描述
link: '${url}',//分享地址
imgUrl:'${shareImgUrl}'//分享圖標
};
wx.onMenuShareAppMessage({
title: '${newsItem.title}',
desc: '${newsItem.description}',
link: '${url}',
imgUrl:'${shareImgUrl}',
trigger: function (res) {
// 不要嘗試在trigger中使用ajax異步請求修改本次分享的內容,因爲客戶端分享操作是一個同步操作,這時候使用ajax的回包會還沒有返回
// alert('用戶點擊發送給朋友');
},
success: function (res) {
//alert('已分享');用戶確認分享後成功回調
},
cancel: function (res) {
//alert('已取消');
},
fail: function (res) {
alert(JSON.stringify(res));
}
});
wx.onMenuShareTimeline(shareData);
// 要隱藏的菜單項,只能隱藏“傳播類”和“保護類”按鈕
wx.hideMenuItems({
menuList: [
'menuItem:copyUrl'
]
});
});</span>
五、通過error接口處理失敗驗證:
<span style="font-size:18px;"> wx.error(function (res) {
alert("error: "+ res.errMsg);
});
</span>
通過上述的配置,就可以實現自定義分享的配置了。