vue hash模式實現微信掃碼分享

需求:微信掃二維碼跳轉到設定的連接,而後分享到微信朋友,或者朋友圈, 配置分享界面樣式

首先,生成跳轉連接的二維碼

https://segmentfault.com/a/11...(這裏具體寫了怎麼生成二維碼)
2.pngvue

下來咱們具體討論微信分享的具體配置,和遇到的問題。

一、配置微信分享界面

咱們系統中使用的路由跳轉,都作了權限控制,配置路由的時候若是沒有登陸就會跳轉到登陸界面,或者請求接口的時候後臺作了token驗證,這些都會影響分享界面,因此配置分享界面路由是和login同級別的(即外層),請求接口的時候咱們也配置一下微信分享路由不須要驗證token。我本身的配置是這樣的ios

router/index.jsvuex

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

main.jsnpm

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.jsaxios

// 請求攔截器
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
}

二、經過接口獲取微信配置信息(和後臺溝通)

一般接口只須要傳遞轉碼的url就能夠了,返回咱們須要的配置信息segmentfault

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

注意:這裏的url經過window.location.href.split('#')獲取‘#’號前面的內容,而後進行編碼傳遞給後臺獲取內容。這裏只是實力,實際項目中能夠把獲取信息寫在vuex actions中api

三、微信分享配置

// 安裝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:session

// 配置完成之後彈出以下信息
{errorMsg: config: invalid url domain}
// 這是由於微信公衆號設置中沒有設置好,能夠根據下圖設置

image.png

完整代碼

// 分享界面的代碼
<!--
 * @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的配置。app

相關文章
相關標籤/搜索