Home > Web Front-end > JS Tutorial > Introduction to how to use WeChat jssdk logic in vue (code example)

Introduction to how to use WeChat jssdk logic in vue (code example)

不言
Release: 2018-11-14 10:10:36
forward
2664 people have browsed it

This article brings you an introduction to the use of WeChat jssdk logic in vue (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Simple use of WeChat jssdk in 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...
});
Copy after login

The above is the example code given by WeChat official, but for actual project use, it is still The code needs to be further encapsulated. This article demonstrates based on vue, and the same applies to other frameworks.

It has been pointed out in the official document of the WeChat public platform that due to security considerations, the signature logic needs to be processed on the backend, so the principle of signature will not be described in detail here. It mainly talks about how to use the signature returned by the backend. Call jssdk. At the logical level, since the wx.config method is required before calling any interface, we can extract it as much as possible and place it separately.

# utils/
.
├── common.js            # 通用函数
└── lib
    └── wechat           # 微信相关代码
        ├── auth         # 微信用户登陆获取信息相关代码
        │   ├── auth.js
        │   └── index.js
        ├── config       # jssdk 初始化相关代码
        │   └── index.js
        ├── helper.js    # 微信相关操作
        └── share        # 分享接口相关代码
            └── index.js
Copy after login
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
  });
}
Copy after login

In this way, the initialization of jssdk can be completed, and then the sharing interface can be initialized. At the beginning, I wanted to share that since it is possible to correspond to every url page (view in the SPA application), then it should be in view was written using mixin mixed in, so the first version of the implementation was produced.

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

  wechatShareConfig() {
    return {
      title: 'example',
      desc: 'example desc',
      imgUrl: 'http://xxx/example.png',
      link: window.location.href.split('#')[0]
    };
  }
}
Copy after login
// 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;
Copy after login
// 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);
    });
  });
}
Copy after login

After writing it, there seems to be nothing wrong at first glance, but each view folder has a WeChat configuration for .vue which seems very bloated, so The second version of the implementation places the jssdk initialization in the beforeEach hook of vue-router, so that unified configuration of the shared configuration can be achieved, which is more intuitive. .

// 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();
});
Copy after login

In this way, .vue will look much cleaner and there will not be too much code other than business logic.

The above is the detailed content of Introduction to how to use WeChat jssdk logic in vue (code example). For more information, please follow other related articles on the PHP Chinese website!

source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template