微信 jssdk 邏輯在 vue 中的運用

微信 jssdk 在 vue 中的簡單使用

import wx from 'weixin-js-sdk';

wx.config({
  debug: true,
  appId: '',
  timestamp: ,
  nonceStr: '',
  signature: '',
  jsApiList: []
});

wx.ready(() => {
  // do something...
});

wx.error((err) => {
  // do something...
});

以上是微信官方給出的示例代碼,可是對於實際項目使用,還須要進一步對代碼進行封裝。本文基於 vue 進行示範,其他類框架同理。javascript

在微信公衆平臺的官方文檔中已經指出,因爲安全性考慮,須要將簽名邏輯放在後端處理,因此簽名原理不在此贅述,主要講講如何使用後端返回後的簽名調用 jssdk。在邏輯層面,因爲 wx.config 方法是調用任何接口前所必須的,因此咱們能夠儘量將其抽離出來單獨放置。vue

# utils/
.
├── common.js            # 通用函數
└── lib
    └── wechat           # 微信相關代碼
        ├── auth         # 微信用戶登錄獲取信息相關代碼
        │   ├── auth.js
        │   └── index.js
        ├── config       # jssdk 初始化相關代碼
        │   └── index.js
        ├── helper.js    # 微信相關操做
        └── share        # 分享接口相關代碼
            └── index.js
import sdk from 'weixin-js-sdk';

export function initSdk({ appid, timestamp, noncestr, signature, jsApiList }) { // 從後端獲取
  sdk.config({
    debug: process.env.VUE_APP_ENV !== 'production',
    appId: appid,
    timestamp: timestamp,
    nonceStr: noncestr,
    signature: signature,
    jsApiList: jsApiList
  });
}

這樣就能夠完成對 jssdk 的初始化,以後能夠進行分享接口的初始化。最初的時候我想分享接口既然是可能對應每個 url 頁面(SPA 應用中的 view),那麼就應該在 view 中使用 mixin 混入來書寫,因此產生了初版實現。java

// example.vue
export default {
  name: 'example',

  wechatShareConfig() {
    return {
      title: 'example',
      desc: 'example desc',
      imgUrl: 'http://xxx/example.png',
      link: window.location.href.split('#')[0]
    };
  }
}
// wechatMixin.js
import { share } from '@/utils/lib/wechat/share';

// 獲取 wechat 分享接口配置
function getWechatShareConfig(vm) {
  const { wechatShareConfig } = vm.$options;
  if (wechatShareConfig) {
    return typeof wechatShareConfig === 'function'
      ? wechatShareConfig.call(vm)
      : wechatShareConfig;
  }
}

const wechatShareMixin = {
  created() {
    const wechatShareConfig = getWechatShareConfig(this);
    if (wechatShareConfig) {
      share({ ...wechatShareConfig });
    }
  }
};

export default wechatShareMixin;
// utils/lib/wechat/share
import { getTicket } from '@/utils/lib/wechat/helper'; // 簽名接口
import { initSdk } from '@/utils/lib/wechat/config';
import sdk from 'weixin-js-sdk';

// 接口清單
const JS_API_LIST = ['onMenuShareAppMessage', 'onMenuShareTimeline'];

// 消息分享
function onMenuShareAppMessage(config) {
  const { title, desc, link, imgUrl } = config;
  sdk.onMenuShareAppMessage({ title, desc, link, imgUrl });
}

// 朋友圈分享
function onMenuShareTimeline(config) {
  const { title, link, imgUrl } = config;
  sdk.onMenuShareTimeline({ title, link, imgUrl });
}

export function share(wechatShareConfig) {
  if (!wechatShareConfig.link) return false;

  // 簽名驗證
  getTicket(wechatShareConfig.link).then(res => {
    // 初始化 `jssdk`
    initSdk({
      appid: res.appid,
      timestamp: res.timestamp,
      noncestr: res.noncestr,
      signature: res.signature,
      jsApiList: JS_API_LIST
    });

    sdk.ready(() => {
      // 初始化目標接口
      onMenuShareAppMessage(wechatShareConfig);
      onMenuShareTimeline(wechatShareConfig);
    });
  });
}

寫完以後乍一看彷佛沒什麼毛病,可是每一個 view 文件夾下的 .vue 都有一份微信配置顯得非常臃腫,因此第二版實現則是將 jssdk 初始化放在 vue-routerbeforeEach 鉤子中進行,這樣能夠實現分享配置的統一配置,更加直觀一些。vue-router

// router.js

//...
routes: [
  {
    path: '/',
    component: Example,
    meta: {
      wechat: {
        share: {
          title: 'example',
          desc: 'example desc',
          imgUrl: 'https://xxx/example.png'
        }
      }
    }
  }
]
//...

// 初始化分享接口
function initWechatShare (config) {
  if (config) {
    share(config);
  }
}

router.beforeEach((to, from, next) => {
  const { shareConfig } = to.meta && to.meta.wechat;
  const link = window.location.href;

  if (!shareConfig) next();

  initWechatShare({ ...shareConfig, link });
  switchTitle(shareConfig.title); // 切換標題
  next();
});

這樣一來,會顯得 .vue 清爽不少,不會有太多業務邏輯以外的代碼。後端

相關文章
相關標籤/搜索