微信分享(移動web端)


create-at 2019-02-16

引入微信JS-SDK http://res.wx.qq.com/open/js/jweixin-1.4.0.js (當前最新版本)

js 相關代碼 (移動端實測, 需做老版本兼容)

function weChatShare(title,desc) {
    var link = window.location.href;// 這里如果采用的並非當前頁可能會出錯,具體原因有待查找
    var serverUrl = encodeURIComponent(link);
    var imgUrl = '分享顯示的小圖'; //80*80 實測可以使用其它比列,最好使用小尺寸正方形,域名也要在安全域名之下

    // 數據請求,根據項目需求更改
    function ajaxFn() {
        var xhr = new XMLHttpRequest()

        xhr.open('get', '這是請求配置項的接口?url=' + serverUrl, true)
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
                wxConfig(JSON.parse(xhr.responseText))
            }
        }
        xhr.send()
    }

    function wxConfig(res) {
        wx.config({
            // 是否開啟調試(會返回一些錯誤原因)
            debug: true,
            // 公眾號的唯一標識
            appId: res.appId,
            // 簽名的時間戳
            timestamp: res.timestamp,
            // 簽名的隨機串
            nonceStr: res.nonceStr,
            // 簽名
            signature: res.signature,
            // 需要調用的JS接口
            jsApiList: [
                'updateAppMessageShareData',
                'updateTimelineShareData',
                'onMenuShareAppMessage',
                'onMenuShareTimeline'
            ]
        });

        // config 驗證后會執行ready方法
        wx.ready(function () {
            var shareConfig = {
                title: title,
                desc: desc,
                link: link,
                imgUrl: imgUrl
            };

            // 目前新版方法存在問題,所以如果有老方法,優先選擇老方法
            if(wx.onMenuShareAppMessage){
                wx.onMenuShareAppMessage(shareConfig);
                wx.onMenuShareTimeline(shareConfig);
            } else {
                // 自定義“分享給朋友”及“分享到QQ”按鈕的分享內容
                wx.updateAppMessageShareData(shareConfig);
                // 朋友圈
                wx.updateTimelineShareData(shareConfig);
            }
        });

        wx.error(function (res) {
            // config信息驗證失敗
            console.log(res);
        });
    }

    ajaxFn()
}

weChatShare('tit', 'des')

本篇文章只是做了方法整合,詳見 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432

交流 Github blog issues


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM