js-sdk微信分享功能的实现(vue)

经过处理了各种bug后的最终版本代码

在index.html:
引入 <script type="text/javascript" src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>



在需要做分享功能的页面:
created(){
    this.getVideoDetails()
}
methods:{
    //获取视频数据
    getVideoDetails(){
        this.$axios.get(`${api.videoApi}/getVideo?vid=${this.vid}`).then(res=>{
            if(res.data.code==200){
                this.videoDetails=res.data.data
                this.wxShareCheck()  //此函数应在获取数据的接口成功获取数据后执行,以免数据为空时调用分享函数出现bug。
            }
        }).catch(err=>{})
    }
    //检查是否是微信端,是微信端则调用微信分享功能
    wxShareCheck(){
        let ua = navigator.userAgent.toLowerCase();  
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            this.getWxShare()
        }        
    }
    //微信分享功能调用
    getWxShare(){
        let url =encodeURIComponent(window.location.href.split('#')[0])
        axios.get(`${common.coper}/getWxShareParam?url=${url}`).then(res=>{
            if(res.data.code==200){
                let wxInfo=res.data.data
                wx.config({
                    debug: false, // 是否开启调试模式
                    appId: wxInfo.appid, //appid:需与公众号一致
                    timestamp: wxInfo.timestamp, // 时间戳
                    nonceStr: wxInfo.nonceStr, // 随机字符串
                    signature: wxInfo.signature, // 签名
                    jsApiList: [
                        'onMenuShareAppMessage',
                        'onMenuShareTimeline',
                        'updateAppMessageShareData',
                        'updateTimelineShareData',
                    ] // 需要使用的JS接口列表
                })
                wx.ready(()=>{  
                    wx.onMenuShareAppMessage({ 
                        title: this.videoDetails.title?this.videoDetails.title:'',     // 分享标题
                        desc: this.videoDetails.name?`电影主演:${this.videoDetails.name}`:'',     // 分享描述
                        link: window.location.href,     // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: this.videoDetails.image?this.videoDetails.image:'',     // 分享图标
                        success: function () {
                            console.log("成功")
                        },
                        cancel:function(){
                            console.log("取消")
                        }
                    })
                    wx.onMenuShareTimeline({ 
                        title: this.videoDetails.title?this.videoDetails.title:'',     // 分享标题
                        link: window.location.href,     // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: this.videoDetails.image?this.videoDetails.image:'',     // 分享图标
                        success: function () {
                            console.log("成功")
                        },
                        cancel:function(){
                            console.log("取消")
                        }
                    })
                })
                wx.error(function(res){
                    console.log(res.errMsg)
                })
            }else{
                console.log(res.data.msg)   //请求接口不为200时,输出失败信息,比如401未登录
            }
        }).catch()
    },
}

坑:

1、微信分享函数在何时执行?

------ 很多人说是在vue的mounted周期里执行,但我认为更保险的执行时期是在拿到页面数据之后。因为若执行分享函数时,数据还没拿到的话,那么第一可能分享功能失效,第二可能分享出去的图文是undefined。

2、报错63002(意思是无效的签名)是什么原因造成的?

------ 很大因素可能就是域名不符合的问题,要与后端沟通好域名,config里的每一个配置都要确认无误才可以。

3、直接使用新api:updateAppMessageShareData,updateTimelineShareData时有一些兼容性问题怎么办?

------ 这是微信的问题,微信在js-sdk1.4.0和1.6.0新版本里发布的这新api在某些环境会有问题出现。现在我也不知道怎么办,目前我用的是旧版本api,等以后解决了再来补上

4、微信链接第一次分享成功,但点进此链接后再次分享此链接便会失效是怎么回事?

------ 原因是微信分享后会自动给当前链接拼接上from等参数,再次进入此链接,因为此次链接携带了from等参数。wx.config时若两次的url不一样,则wx.config失败,因此分享功能失效。如
分享前:http://test.com/test.html
分享后:http://test.com/test.html?from=singlemessage&isappinstalled=0
------ 那么怎么办呢?思路是去除from等参数带来的影响

  • 方案1:在调用分享函数前,先判断当前url是否带有from等参数,若有,则重置url
getWxShare(){
    function getQueryString(name) {  //根据字段看网址是否拼接&字符串
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substr(1).match(reg);
        if (r != null)
            return unescape(r[2]);
        return null;
    }
    let from = getQueryString('from');
    let appinstall = getQueryString('appinstall');
    let sec = getQueryString('sec');
    let timekey = getQueryString('timekey');
    if(from || appinstall || sec || timekey){
        window.location.href =window.location.href.split("?")[0]
    }

    。。。。。。
}


弊端:①、重置页面url会导致进入页面时页面会闪一下,用户体验不好。②、安卓微信有部分兼容性问题:二次分享时好时坏,稳定性差
  • 方案2:转化url格式,使用encodeURIComponent格式请求后端接口
getWxShare(){
    let url =encodeURIComponent(window.location.href.split('#')[0])
    。。。。。。
}
提醒:
wx.updateAppMessageShareData({ 
    title: 
    desc:  
    link: window.location.href, // 值得一提的是,这里请使用window.location.href而不要图省事使用url,url可是经过转码的,这里不可使用
    imgUrl: 
    success: function () {},
    cancel:function(){}
})

暂时没有发现什么弊端
5、若分享的链接是这样的http://192.168.1.164/web#/live/liveroom?islive=0&lid=17&roomid=23456,链接中带有&会导致请求接口时被自动解析
如上,使用encodeURIComponent转码后上传即可
posted @ 2020-01-02 14:51  huihuihero  阅读(1072)  评论(0编辑  收藏  举报