天天看點

h5微信分享js這是一個接微信sdk實作的分享js

這是一個接微信sdk實作的分享js

// wxShareSDK.js

import {getWeixinSign} from "@/api/share"; // 擷取微信簽名的api接口,即後端接口,通過請求該接口擷取微信分享所需的微信簽名資訊

// 微信sdk分享
export function jssdkConfig(shareParams){
    var _this = this;
    let _url = window.location.href.split('#')[0]; // 擷取目前url,比如'http://aaa.com/',此位址要求在微信公衆号配置

    console.log('----------分享參數----------');
    console.log(shareParams); // 分享的标題,副标題,分享icon,位址

    getWeixinSign({url: _url}).then(res => { // 拿配置好的位址去請求換取微信簽名所需資訊
        console.log('----------微信簽名參數-------------');
        console.log(res);
        
        // 微信提供的方法,用于校驗微信簽名以及jsApiList中設定的菜單是否可用
        wx.config({
            debug: false,
            appId: res.appId,
            timestamp: res.timestamp,
            nonceStr: res.nonceStr,
            signature: res.signature,
            jsApiList: ["checkJsApi", 'onMenuShareAppMessage', 'onMenuShareTimeline']
        });
		// 分享失敗的回調
        wx.error(function(res){
            // config資訊驗證失敗會執行error函數,如簽名過期導緻驗證失敗,具體錯誤資訊可以打開config的debug模式檢視,也可以在傳回的res參數中檢視,對于SPA可以在這裡更新簽名。
            console.log("wx.err")
            console.log(res);
        });
        // jsApiList是你希望微信右上角三個點中所展示的菜單内容
        wx.checkJsApi({
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'], // 需要檢測的JS接口清單,所有JS接口清單見附錄2,
            success: function(res) {
                // 以鍵值對的形式傳回,可用的api值true,不可用為false
                // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                console.log("checkJsApi:")
                console.log(res);
            }
        });
		// 分享實作放在wx.ready中執行
        wx.ready(function(){
            
                wx.onMenuShareAppMessage({
                    title: shareParams.title, // 分享标題
                    desc: shareParams.desc, // 分享描述
                    link: shareParams.link, // 分享連結,該連結域名或路徑必須與目前頁面對應的公衆号JS安全域名一緻
                    imgUrl: shareParams.imgUrl, // 分享圖示
                    success: function () {
                        console.log("分享成功"); // 設定成功
                        console.log(window.location.href)
                    }
                });
                wx.onMenuShareTimeline({
                    title: shareParams.title, // 分享标題
                    desc: shareParams.desc, // 分享描述
                    link: shareParams.link,
                    imgUrl: shareParams.imgUrl, // 分享圖示
                    success: function () {
                        console.log("分享成功"); // 設定成功
                        console.log(window.location.href)
                    }
                });
            }
        })
    }).catch(error => {
		consoe.log(error)
    })
}


           

繼續閱讀