vue hash模式实现微信扫码分享

LogicWaltzMaster
• 阅读 5783

需求:微信扫二维码跳转到设定的链接,然后分享到微信朋友,或者朋友圈, 配置分享界面样式

首先,生成跳转链接的二维码

https://segmentfault.com/a/11...(这里具体写了怎么生成二维码)
vue hash模式实现微信扫码分享

下来我们具体讨论微信分享的具体配置,和遇到的问题。

1、配置微信分享界面

我们系统中使用的路由跳转,都做了权限控制,配置路由的时候如果没有登录就会跳转到登录界面,或者请求接口的时候后台做了token验证,这些都会影响分享界面,所以配置分享界面路由是和login同级别的(即外层),请求接口的时候我们也配置一下微信分享路由不需要验证token。我自己的配置是这样的

router/index.js

...
{
  path: '/wechat-share',
  name: 'wechat-share',
  component: WechatShare
},
{
  path: '/login',
  name: 'login',
  component: Login
}
...

main.js

router.beforeEach((to, from, next) => {
  // 如果没有session信息不能跳转
  if (localStorage.getItem('userInfo_admin')) {
    next()
  } else {
    // 如果是登录界面,或者微信分享界面都不需要验证session
    if (to.path === '/login' || to.path === '/wechat-share') {
      next()
    } else {
      next({
        path: '/login'
      })
    }
  }

请求接口文件,封装http.js

// 请求拦截器
axios.interceptors.request.use(config => {
  // 如果不是登录接口,或者微信分享接口,都需要验证token
  if (window.location.hash.indexOf('login') === -1 && window.location.hash.indexOf('wechat-share') === -1) {
    const token = store.state.userInfo.Authorization
    token && (config.headers.Authorization = token)
  }
  return config
}

2、通过接口获取微信配置信息(和后台沟通)

通常接口只需要传递转码的url就可以了,返回我们需要的配置信息

axios.get('接口地址', {params: {url: encodeURIComponent(window.location.href.split('#')[0])}}).then(res => {}).catch(error => {})

注意:这里的url通过window.location.href.split('#')获取‘#’号前面的内容,然后进行编码传递给后台获取内容。这里只是实力,实际项目中可以把获取信息写在vuex actions中

3、微信分享配置

// 安装wx sdk
npm install weixin-js-sdk --save
// 组件中引入
import wx from 'weixin-js-sdk'
// 在mounted中配置
// appId,timestamp, nonceStr, singature都可以在接口中得到。
wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,公众号的唯一标识
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名,见附录1
    jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline'] // 必填,需要使用的JS接口列表
})

wx.ready(function() { //通过ready接口处理成功验证
// config信息验证成功后会执行ready方法
    wx.onMenuShareAppMessage({ // 分享给朋友  ,在config里面填写需要使用的JS接口列表,然后这个方法才可以用 
        title: '这里是标题', // 分享标题
        desc: 'This is a test!', // 分享描述
        link: '链接', // 分享链接
        imgUrl: '图片', // 分享图标
        type: '', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function() {
            // 用户确认分享后执行的回调函数
        },
        cancel: function() {
            // 用户取消分享后执行的回调函数
        }
     })
     wx.onMenuShareTimeline({ //分享朋友圈
        title: '标题', // 分享标题
        link: '链接',
        imgUrl: '图片', // 分享图标
        success: function() {
            // 用户确认分享后执行的回调函数
        },
        cancel: function() {
            // 用户取消分享后执行的回调函数
        }
    })
})
wx.error(function(res){//通过error接口处理失败验证
    // config信息验证失败会执行error函数
})

我的配置代码,以及遇到的坑

data () {
    return {
      config: {
        url: encodeURIComponent(this.$store.getters.base_url),
        title: '项目名称',
        desc: '项目描述',
        img: 'https://pic4.zhimg.com/80/v2-9e7354788266d6ceae5a0839e24d9c1a_hd.jpg'
      },
      projectInfo: ''
    }
}
...
// 获取微信配置信息,通过后台接口。
    await this.$store.dispatch('getWechatConfigAction', encodeURIComponent(window.location.href.split('#')[0]))
    // alert(this.projectInfo)
    // // 接口获取界面内容
    // alert(JSON.stringify(this.config, null, 4))
    // alert(JSON.stringify(this.$store.state.wxConfig, null, 4))
    wx.config({
      debug: true,
      appId: this.$store.state.wxConfig.appId,
      timestamp: this.$store.state.wxConfig.timestamp,
      nonceStr: this.$store.state.wxConfig.nonceStr,
      signature: this.$store.state.wxConfig.signature,
      jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline']
    })
    wx.ready(() => {
      wx.onMenuShareAppMessage({
        title: this.config.title, // 分享标题
        desc: this.config.content, // 分享描述
        link: window.location.href.split('#')[0] + '#' + window.location.href.split('#')[1], // 分享链接
        imgUrl: this.config.imgUrl, // 分享图标
        type: 'link', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () {
          // 用户确认分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "分享成功"]);
          this.$message({
            type: 'success',
            message: '分享成功'
          })
          // config.success()
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "取消分享"]);
          this.$message({
            type: 'success',
            message: '取消分享'
          })
          // config.cancel()
        },
        fail: function (res) {
          this.$message({
            type: 'error',
            message: '分享失败'
          })
          // config.fail()
        }
      })
      wx.onMenuShareTimeline({
        title: this.config.title, // 分享标题
        desc: this.config.content, // 分享描述
        link: window.location.href.split('#')[0] + '#' + window.location.href.split('#')[1], // 分享链接
        imgUrl: this.config.imgUrl, // 分享图标
        type: 'link', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () {
          // 用户确认分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "分享成功"]);
          this.$message({
            type: 'success',
            message: '分享成功'
          })
          // config.success()
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "取消分享"]);
          this.$message({
            type: 'success',
            message: '取消分享'
          })
          // config.cancel()
        },
        fail: function (res) {
          this.$message({
            type: 'error',
            message: '分享失败'
          })
          // config.fail()
        }
      })
    })
    wx.error(() => {
      console.log('请求分享数据失败')
      // config.fail()
    })

问题1:

// 配置完成以后弹出如下信息
{errorMsg: config: invalid signature}
// 这是因为请求配置信息的接口参数url有误,可以通过encodeURIComponent(window.location.href.split('#')[0])来获取

问题2:

// 配置完成以后弹出如下信息
{errorMsg: config: invalid url domain}
// 这是因为微信公众号设置中没有设置好,可以根据下图设置

vue hash模式实现微信扫码分享

完整代码

// 分享界面的代码
<!--
 * @Author: 张旭超
 * @Date: 2020-01-08 13:14:14
 * @LastEditTime : 2020-01-10 17:09:56
 * @LastEditors  : Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /src/components/wechat-share/WechatShare.vue
-->
<template>
  <div>
    <div>微信分享</div>
    <div>微信扫码分享</div>
    <div>{{projectInfo}}</div>
    {{this.$store.state.wxConfig.appId}}
    {{this.$store.state.wxConfig.timestamp}}
    {{this.$store.state.wxConfig.nonceStr}}
    {{this.$store.state.wxConfig.signature}}
  </div>
</template>

<script>
import wx from 'weixin-js-sdk'
export default {
  data () {
    return {
      config: {
        url: encodeURIComponent(this.$store.getters.base_url),
        title: '项目名称',
        desc: '项目描述',
        img: 'https://pic4.zhimg.com/80/v2-9e7354788266d6ceae5a0839e24d9c1a_hd.jpg'
      }
    }
  },
  async mounted () {
    // 获取微信配置信息,通过后台接口。
    await this.$store.dispatch('getWechatConfigAction', encodeURIComponent(window.location.href.split('#')[0]))
    // alert(this.projectInfo)
    // // 接口获取界面内容
    // alert(JSON.stringify(this.config, null, 4))
    // alert(JSON.stringify(this.$store.state.wxConfig, null, 4))
    wx.config({
      debug: true,
      appId: this.$store.state.wxConfig.appId,
      timestamp: this.$store.state.wxConfig.timestamp,
      nonceStr: this.$store.state.wxConfig.nonceStr,
      signature: this.$store.state.wxConfig.signature,
      jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline']
    })
    wx.ready(() => {
      wx.onMenuShareAppMessage({
        title: this.config.title, // 分享标题
        desc: this.config.content, // 分享描述
        link: window.location.href.split('#')[0] + '#' + window.location.href.split('#')[1], // 分享链接
        imgUrl: this.config.imgUrl, // 分享图标
        type: 'link', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () {
          // 用户确认分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "分享成功"]);
          this.$message({
            type: 'success',
            message: '分享成功'
          })
          // config.success()
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "取消分享"]);
          this.$message({
            type: 'success',
            message: '取消分享'
          })
          // config.cancel()
        },
        fail: function (res) {
          this.$message({
            type: 'error',
            message: '分享失败'
          })
          // config.fail()
        }
      })
      wx.onMenuShareTimeline({
        title: this.config.title, // 分享标题
        desc: this.config.content, // 分享描述
        link: window.location.href.split('#')[0] + '#' + window.location.href.split('#')[1], // 分享链接
        imgUrl: this.config.imgUrl, // 分享图标
        type: 'link', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () {
          // 用户确认分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "分享成功"]);
          this.$message({
            type: 'success',
            message: '分享成功'
          })
          // config.success()
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
          // _hmt.push(['_trackEvent', config.title, "分享给好友", "取消分享"]);
          this.$message({
            type: 'success',
            message: '取消分享'
          })
          // config.cancel()
        },
        fail: function (res) {
          this.$message({
            type: 'error',
            message: '分享失败'
          })
          // config.fail()
        }
      })
    })
    wx.error(() => {
      console.log('请求分享数据失败')
      // config.fail()
    })
  }
}
</script>

代码中获取配置信息,封装在了vuex的actions中,获取的配置信息存储在 $store.stat.wxConfig中,主要是传递参数url的配置。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
3年前
QQ分享 QQ空间分享 API链接:
通过qq空间、qq聊天、新浪微博和微信二维码分享平台提供的接口,实现把网页中对应的图片、标题、描述的信息参数用javascript获取后传进接口中,实现一键分享。使用到的接口(测试时需要登录,网址和图片必须是公网的,不能是localhost):1.分享到QQ空间接口:https://sns.qzone.qq.com/cg
Easter79 Easter79
3年前
thinkcmf+jsapi 实现微信支付
首先从小程序端接收订单号、金额等参数,然后后台进行统一下单,把微信支付的订单号返回,在把订单号发送给前台,前台拉起支付,返回参数后更改支付状态。。。回调publicfunctionnotify(){$wechatDb::name('wechat')where('status',1)find();
梦
4年前
微信小程序new Date()转换时间异常问题
微信小程序苹果手机页面上显示时间异常,安卓机正常问题image(https://imghelloworld.osscnbeijing.aliyuncs.com/imgs/b691e1230e2f15efbd81fe11ef734d4f.png)错误代码vardate'2021030617:00:00'vardateT
_dolphin _dolphin
4年前
.net core Cookie的使用
缘起:  公司领导让我做一个测试的demo,功能大概是这样的:用户通过微信扫一扫登陆网站,如果用户登录过则直接进入主界面,否则就保留在登录界面。实现方法:  首先先把网站地址生成个二维码,在扫描二维码后去获取Cookie如果有值那么就证明登录过直接跳转到主界面,如果Cookie不存在用户通过登录记录的用户信息并保存到Cookie。什么是Cookie:  储存
Stella981 Stella981
3年前
Android 微信分享后留在微信,没有回调的问题解决方案
网上有很多关于微信分享后没有回调的问题,大多数讲的都是一些配置不对、WXEntryActivity类的包名不对等所引起的错误。但我今天要讲的问题不是因为这些集成不当引起的问题,而是微信分享SDK本身存在的问题(或者这并不是微信SDK的bug,而是微信本身就是这样设计的)。这个问题就是,当我们分享成功后,微信会弹出一个弹窗,让用户选择“留在微信”或者“返回ap
Easter79 Easter79
3年前
Taro小程序自定义顶部导航栏
微信自带的顶部导航栏是无法支持自定义icon和增加元素的,在开发小程序的时候自带的根本满足不了需求,分享一个封装好的组件,支持自定义icon、扩展dom,适配安卓、ios、h5,全面屏。我用的是京东的Taro多端编译框架写的小程序,原生的也可以适用,用到的微信/taro的api做调整就行,实现效果如下。!在这里插入图片描述(https://i
Wesley13 Wesley13
3年前
11.11如何卖到一个亿:从0到1的电商爆品打造术 电子书 PDF
内容转自:https://download.csdn.net/download/chenyao1994/11191034下载地址:https://pan.baidu.com/s/1uQ1cjm9QH4ZXPoqQRiAw0A分享码:如需分享码:\打开微信\\扫描右侧二维码\\关注码小辫的微信\输入"21489
Stella981 Stella981
3年前
DevOps&CloudNative技术交流群
微信群:添加微信:devsecopser,或者扫描下方二维码添加微信好友,备注加群。!(https://oscimg.oschina.net/oscnet/7f93ee88656c4ba36be309c9c097992721f.jpg)本文分享自微信公众号云原生生态圈(CloudNativeEcoSystem)。如有侵权,
使用taro+canvas实现微信小程序的图片分享功能 | 京东云技术团队
业务场景二轮充电业务中,用户充电完成后在订单详情页展示订单相关信息,用户点击分享按钮唤起微信小程序分享菜单,将生成的图片海报分享给微信好友或者下载到本地,好友可通过扫描海报中的二维码加群领取优惠。使用场景及功能:微信小程序生成海报图片分享好友下载图片使用技