1. 程式人生 > >微信 jssdk 邏輯在 vue 中的運用

微信 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

進行示範,其餘類框架同理。

在微信公眾平臺的官方文件中已經指出,由於安全性考慮,需要將簽名邏輯放在後端處理,所以簽名原理不在此贅述,主要講講如何使用後端返回後的簽名呼叫 jssdk。在邏輯層面,由於 wx.config 方法是呼叫任何介面前所必須的,所以我們可以儘可能將其抽離出來單獨放置。

# 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 混入來書寫,所以產生了第一版實現。


// 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 鉤子中進行,這樣可以實現分享配置的統一配置,更加直觀一些。


// 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 清爽很多,不會有太多業務邏輯之外的程式碼。

原文地址:https://segmentfault.com/a/1190000017002624