美文网首页
微信个性化分享实现

微信个性化分享实现

作者: 飞鹰_007 | 来源:发表于2020-09-04 09:42 被阅读0次

    1.引入微信js-sdk:   npm install --save-dev weixin-js-sdk

    2.引入axios:    npm install --save axios

    3.新建wxShare.js

    import wx from 'weixin-js-sdk'

    import axios from 'axios'

    const wxApi = {

        wxRegister (callback) {

            axios.get('weChat/share?url='+window.location.href.split('#')[0], // 获取签名接口

              { timeout: 5000, withCredentials: true }

              ).then((res) => {

              let data = JSON.parse(res.data); //这里根据接口的返回值来使用

              wx.config({

                debug: false, // 开启调试模式

                appId: data.appId, // 必填,公众号的唯一标识

                timestamp: data.timestamp, // 必填,生成签名的时间戳

                nonceStr: data.nonceStr, // 必填,生成签名的随机串

                signature: data.signature, // 必填,签名,见附录1

                jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']

          })

        }).catch((error) => {

          console.log(error)

        });

        wx.ready((res) => {    // 如果需要定制ready回调方法

          if (callback) {

            callback()

          }

        })

      },

      ShareTimeline (option) {  //分享到朋友圈

        wx.onMenuShareTimeline({

          title: option.title, // 分享标题

          link: option.link, // 分享链接

          imgUrl: option.imgUrl, // 分享图标

          success () {    // 用户成功分享后执行的回调函数

            option.success()

          },

          cancel () {     // 用户取消分享后执行的回调函数

            option.error()

          }

        })

      }

    };

    export default wxApi

    4.要个性化分享页面:

    import wxapi from '@/utils/wxShare';

     mounted(){

        wxapi.wxRegister(this.wxRegCallback)

      },

    methods: {

        wxRegCallback () {    //用于微信JS-SDK回调

          this.wxShareTimeline();

        },

        wxShareTimeline () {     //微信自定义分享到朋友圈

          let path = window.location;

          let  getBasePath = path .protocol + "//" +path .host + "/" +path .pathname.split("/")[1]

          let option = {

            title: '这是自定义标题', // 分享标题

            link: path.href.split('#')[0], // 分享链接,根据自身项目决定是否需要split

            imgUrl: getBasePath + "/static/images/logo.png", // 分享图标,绝对路径,建议72*72px

            success: () => {

              Toast({

                message: '分享成功',

                duration: 1000

              });

            },

            error: () => {

              Toast({

                message: '分享失败',

                duration: 1000

              });

            }

          };

          wxapi.ShareTimeline(option)    // 将配置注入通用方法

        },

    }

    相关文章

      网友评论

          本文标题:微信个性化分享实现

          本文链接:https://www.haomeiwen.com/subject/koyosktx.html