1、引入微信的js文件。
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
2、通過ajax從后台獲取必填字段。
appId: ‘’, // 必填,公眾號的唯一標識
timestamp: ‘’, // 必填,生成簽名的時間戳<?= $data['timestamp']?>
nonceStr: ‘’,// 必填,生成簽名的隨機串<?= $data['noncestr']?>
signature:‘’,// 必填,簽名<?= $data['signature']?>
// 分享// 微信分享函數 var signature = {}; $.ajax({ url:'http://mxp.chinacmcp.com/index.php?s=Postcard/Postcard/wecat', timeout: 10000, // 超時時間 10 秒 type:'get', data: { url: window.location.href }, async: false, cache:false, dataType: 'json', success: function (data) { console.log(data) if(data.code==200) { console.log(data) signature = data.data; } }, error: function (data) { } }); wx.config({ debug: false, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。 appId: signature.appid, // 必填,公眾號的唯一標識 timestamp: signature.timestamp, // 必填,生成簽名的時間戳<?= $data['timestamp']?> nonceStr: signature.noncestr,// 必填,生成簽名的隨機串<?= $data['noncestr']?> signature: signature.signature,// 必填,簽名<?= $data['signature']?> jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']// 必填,需要使用的JS接口列表 }); wx.ready(function () { wx.checkJsApi({ jsApiList: ['chooseImage'], // 需要檢測的JS接口列表,所有JS接口列表見附錄2, success: function(res) { console.log(res); // 以鍵值對的形式返回,可用的api值true,不可用為false // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"} } }); var shareUrl='http://mxp.chinacmcp.com/html'; var obj = {//朋友圈 title: shareUserPhone1+'給您的悄悄話', // 分享標題 desc: '點擊查看那些未曾對你說出口的話吧!', // 分享描述 link: shareUrl, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 // 該鏈接是重定向鏈接,因為需要獲取用戶code,但是該鏈接又無法直接寫微信獲取code的鏈接, // 所以需要點擊后重新加載新的頁面,來實現重定向,重新打開獲取code的微信鏈接,實現獲取用戶信息的功能; imgUrl: 'http://mxp.chinacmcp.com/html/images/shareBack.png', // 分享圖標 fail: function (res) { alert(JSON.stringify(res)); } }; var obj1 = {//好友 title: shareUserPhone1+'有些話,早就想對您說', // 分享標題 desc: '點擊查看那些未曾對你說出口的話吧!', // 分享描述 link: shareUrl, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 // 該鏈接是重定向鏈接,因為需要獲取用戶code,但是該鏈接又無法直接寫微信獲取code的鏈接, // 所以需要點擊后重新加載新的頁面,來實現重定向,重新打開獲取code的微信鏈接,實現獲取用戶信息的功能; imgUrl: 'http://mxp.chinacmcp.com/html/images/shareBack.png', // 分享圖標 fail: function (res) { alert(JSON.stringify(res)); } }; // 2.1 監聽“分享給朋友”,按鈕點擊、自定義分享內容及分享結果接口 wx.onMenuShareAppMessage(obj1); // 2.2 監聽“分享到朋友圈”按鈕點擊、自定義分享內容及分享結果接口 wx.onMenuShareTimeline(obj); // 2.3 監聽“分享到QQ”按鈕點擊、自定義分享內容及分享結果接口 wx.onMenuShareQQ(obj); // 2.4 監聽“分享到微博”按鈕點擊、自定義分享內容及分享結果接口 wx.onMenuShareWeibo(obj); // 2.5 監聽“分享到QZone”按鈕點擊、自定義分享內容及分享接口 wx.onMenuShareQZone(obj); });