引言

准备工作

1. 微信公众号申请与配置

2. 获取公众号的AppID和AppSecret

3. 配置服务器域名

在公众号的“开发者中心”中,找到“JS接口安全域名”模块,将您的服务器域名添加进去。如果处于本地开发阶段,可以使用内网穿透工具生成临时域名。

集成步骤

1. 安装微信SDK

npm install weixin-js-sdk --save

2. 引入微信SDK

import wx from 'weixin-js-sdk';

Vue.prototype.$wx = wx;

3. 初始化微信SDK

export default {
  mounted() {
    this.initWeChatSDK();
  },
  methods: {
    initWeChatSDK() {
      const params = this.getWeChatSDKParams();
      this.$wx.config({
        debug: true, // 开启调试模式
        appId: params.appId, // 公众号的AppID
        timestamp: params.timestamp, // 时间戳
        nonceStr: params.nonceStr, // 随机字符串
        signature: params.signature, // 签名
        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'], // 需要使用的JS接口列表
      });
      this.$wx.ready(() => {
        // 微信JS接口调用成功
      });
      this.$wx.error((err) => {
        // 微信JS接口调用失败
        console.error(err);
      });
    },
    getWeChatSDKParams() {
      // 调用后台接口获取初始化参数
      // ...
      return {
        appId: 'your_appid',
        timestamp: 'your_timestamp',
        nonceStr: 'your_nonce_str',
        signature: 'your_signature',
      };
    },
  },
};

4. 调用微信JS接口

常见问题和解决方案

结语