1. 程式人生 > >微信分享功能的實現

微信分享功能的實現

該微信分享依賴於jq,所以頁面首先要引入jq。

第一步:引入微信jssdk,如下:

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

第二步:引入微信分享js,可放在公共js資料夾中,程式碼如下:

$.Share = function(opt) {
var  locationurl = window.location.href;
var  url = location.href.split('#')[0];
var  data = {};//data為前後臺互動所傳遞的引數,這個需要前後臺配合,這裡就不添加了
data = JSON.stringify(data);
$.ajax({
type:   'post',
url:   '',//該處為資料介面
data: data,
async:  true,
crossDomain:  true,
dataType:   'json',
success:   function(jo) {
if(jo.succ) {
//微信分享的初始化配置,這裡禁用了一些功能,只展示了分享給朋友,分享到朋友圈
wx.config({
debug:  false,
appId:  jo.appid,
timestamp:  jo.timestamp,
nonceStr:  jo.noncestr,
signature:  jo.signature,
jsApiList: [
'hideMenuItems',
'hideAllNonBaseMenuItem',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'showMenuItems'
]
});


wx.ready(function() {
wx.checkJsApi({
jsApiList: [
'hideMenuItems',
'hideAllNonBaseMenuItem',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'showMenuItems'
],
success: function(res) {
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
// 通過下面這個API顯示右上角按鈕
WeixinJSBridge.call('showOptionMenu');
});
//要隱藏的選單項,只能隱藏"傳播類"和"保護類"按鈕,所有menu項見附錄3
wx.hideMenuItems({
menuList: [
'menuItem:share:qq',
'menuItem:share:weiboApp',
'menuItem:favorite',
'menuItem:share:facebook',
'menuItem:share:QZone',
'menuItem:editTag',
'menuItem:delete',
'menuItem:copyUrl',
'menuItem:originPage',
'menuItem:readMode',
'menuItem:openWithQQBrowser',
'menuItem:openWithSafari',
'menuItem:share:email',
'menuItem:share:brand'
]
});
wx.showMenuItems({
menuList: [
'menuItem:share:appMessage',
'menuItem:share:timeline'
]
});
//傳送給朋友
wx.onMenuShareAppMessage({
title: opt.title,
desc: opt.desc,
link: opt.link,
imgUrl:  opt.imgUrl,
trigger: function(res) {},
success: function(res) {


},
cancel: function(res) {},
fail: function(res) {}
});


//分享到朋友圈
wx.onMenuShareTimeline({
title: opt.title,
link: opt.link,
imgUrl: opt.imgUrl,
trigger: function(res) {},
success: function(res) {


},
cancel: function(res) {},
fail:   function(res) {}
});
},
fail: function(res) {}
});
});
}
},
error:   function (msg)  {}
});
}


第三步:呼叫
$.Share({
title: , //自定義標題
desc:, //自定義描述
link: location.href, //頁面連結
imgUrl: '' //圖片路徑,注意要絕對路徑
});