Egg + Vue + 微信公众号开发(自定义菜单)

245 阅读1分钟

前言:

本篇在上一篇文章(《Egg + Vue + 微信公众号开发(基础框架搭建)》)的基础之上进行

注意:
微信公众号开发自定义菜单功能,只能在该公众号“微信认证”成功后才能线上测试,由于我的公众号主体是个人,所以无法上线,只能使用微信官方提供的测试公众号进行开发。至于测试微信公众号怎么申请,见上一篇文章《Egg + Vue + 微信公众号开发(基础框架搭建)》

image.png

一. 简述

1. 步骤

第一步:获取access_token
获取 Access token 官方文档(戳我查看)
第二步:拿上access_token,创建个性化菜单
个性化菜单接口官方文档(戳我查看)

2. 问题提出

access_token:如何获取?什么时候获取?在什么地方获取?
创建个性化菜单:如何创建?什么时候创建?在什么地方创建?

答案:启动自定义(app.js)里面创建

二. 讲解

1. “获取access_token”和“创建个性化菜单”

1.1 app.js

// app.js

'use strict';
const path = require('path');

class AppBootHook {
  constructor(app) {
    this.app = app;
    this.app.ossClient = {};
  }

  /**
   * 服务器正在监听。
   */
  async serverDidReady() {
    console.log('服务器正在监听.......');
    const ctx = this.app.createAnonymousContext();
    await this.refreshMenu(ctx);
  }

  /**
   * 更新公众号菜单
   */
  async refreshMenu(ctx) {
    this.app.logger.info('初始化菜单...');
    await ctx.service.wxClient.wechat.createMenu();
    this.app.logger.info('初始化菜单完成');
  }
}

module.exports = AppBootHook;

1.2 service层

'use strict';

const Service = require('egg').Service;

class WechatService extends Service {
  // 获取 ACCESS_TOKEN
  async getAccessToken() {
    const { ctx, app } = this;
    const { appid, appSecret } = app.config.wechat_config;
    const baseUrl = 'https://api.weixin.qq.com/cgi-bin/token';
    const accessTokenUrl = `${baseUrl}?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
    const result = await ctx.curl(accessTokenUrl, { dataType: 'json' });
    if (result.data.hasOwnProperty('errcode')) {
      this.ctx.logger.error(`获取access_token报错!errcode:${result.data.errcode}, errmsg:${result.data.errmsg}`);
      return null;
    }
    return result.data['access_token'];
  }

  // 创建菜单
  async createMenu() {
    const { app } = this;
    const accessToken = await this.getAccessToken();
    if (accessToken) {
      const baseUrl = "https://api.weixin.qq.com/cgi-bin/menu/create"
      const menuCreateUrl = `${baseUrl}?access_token=${accessToken}`
      const result = await this.ctx.curl(menuCreateUrl, {
        dataType: 'json',
        contentType: 'json',
        method: 'POST',
        data: {
          'button': [
            {
              'type': 'view',
              'name': '百度搜索',
              'url': 'https://www.baidu.com/'
            },
            {
              'type': 'view',
              'name': '腾讯网',
              'url': 'https://www.qq.com/'
            }
          ]
        },
      });
      if (result.data.errcode !== 0) {
        this.ctx.logger.error(`创建自定义菜单出错。errcode:${result.data.errcode},errmsg:${result.data.errmsg}`);
      }
      return result;
    }
  }
}

module.exports = WechatService;

以上代码就能简简单单的自定义菜单了

源码参考(狂戳我~~)