封装的通过微信JS-SDK实现自定义分享到朋友圈或者朋友的ES6类!

引言:

我们经常在做微信H5的过程中需要自定义分享网页,这个如何实现呢?请看如下的封装的ES6类及使用说明!

/**
 * @jssdk js对象,包括appId,timestamp,nonceStr,signature,后台请求过来。
 * 以上4个参数,需要后台在公众号相关平台进行配置,然后得出!前端页面必须放在服务号配置的域名下面才可以保证成功!
 * options js对象为你自定义要分享的一些参数。
 * 用法:
 *      1、引入weixinShare.js
 *      2、var weixinShare = new weixinShare(jssdk, options);
 *      3、默认加载页面时,调用weixinShare.beforeShareJs,这里必须的!
 *      4、如果点击分享朋友,则调用weixinShare.shareFriends
 *      5、如果点击分享朋友圈,则调用weixinShare.shareCircleFriends
 *      备注:通过右上角的分享按钮,则不需要进行点击事件触发。
 */
class weixinShare {
    constructor(jssdk, options) {
        this.jssdk = jssdk;
        this.options = options;
    }
    beforeShareJs() {
        var that = this;
        wx.config({
            debug: false,//是否开启调试功能,这里关闭!
            appId: that.jssdk.appId,//appid
            timestamp: parseInt(that.jssdk.timestamp), //时间戳
            nonceStr: that.jssdk.nonceStr, //生成签名的随机字符串
            signature: that.jssdk.signature,//签名
            jsApiList: [
                "onMenuShareTimeline",
                "onMenuShareAppMessage"
            ]
        });
    }
    defaultOptions() {
        var defaults = {
            title: "分享的标题",
            desc: "分享的描述",
            link: location.href, //分享页面地址,不能为空,这里可以传递参数!!!!!!!
            imgUrl: 'https://tup.iheima.com/sport.png', //分享是封面图片,不能为空
            success: function () { }, //分享成功触发
            cancel: function () { } //分享取消触发,需要时可以调用
        }
        // 合并对象,后面的替代前面的!
        return Object.assign({}, defaults, this.options);
    }
    shareCircleFriends() {
        var thatopts = this.defaultOptions();
        wx.onMenuShareTimeline({
            title: thatopts.title, // 分享标题
            desc: thatopts.desc, // 分享描述
            link: thatopts.link, // 分享链接
            imgUrl: thatopts.imgUrl, // 分享图标
            success: function () {
                // alert("成功");
            },
            cancel: function () {
                // alert("失败");
            }
        });
    }
    shareFriends() {
        var thatopts = this.defaultOptions();
        wx.onMenuShareAppMessage({
            title: thatopts.title, // 分享标题
            desc: thatopts.desc, // 分享描述
            link: thatopts.link, // 分享链接
            imgUrl: thatopts.imgUrl, // 分享图标
            success: function () {
                // alert("成功");
            },
            cancel: function () {
                // alert("失败")
            }
        });
    }
}

 

posted @ 2018-10-17 10:46  茶记忆  阅读(1482)  评论(0编辑  收藏  举报