Skip to content

Latest commit

 

History

History
321 lines (223 loc) · 5.57 KB

File metadata and controls

321 lines (223 loc) · 5.57 KB

messaging-api-wechat

Messaging API client for WeChat

Table of Contents

Installation

npm i --save messaging-api-wechat

or

yarn add messaging-api-wechat

Usage

Initialize

const { WechatClient } = require('messaging-api-wechat');

// get appId, appSecret from「微信公众平台-开发-基本配置」page
const client = WechatClient.connect({
  appId: APP_ID,
  appSecret: APP_SECRET,
});

Error Handling

messaging-api-wechat uses axios as HTTP client. We use axios-error package to wrap API error instances for better formatting error messages. Directly console.log on the error instance will return formatted message. If you'd like to get the axios request, response, or config, you can still get them via those keys on the error instance.

client.sendText(userId, text).catch(error => {
  console.log(error); // formatted error message
  console.log(error.stack); // error stack trace
  console.log(error.config); // axios request config
  console.log(error.request); // HTTP request
  console.log(error.response); // HTTP response
});

API Reference

All methods return a Promise.


Send API - Official Docs

sendText(userId, text)

发送文本消息

Param Type Description
userId String user ID of the recipient.
text String Text of the message to be sent.

Example:

client.sendText(USER_ID, 'Hello!');

sendImage(userId, mediaId)

发送图片消息

Example:

client.sendImage(USER_ID, 'MEDIA_ID');

sendVoice(userId, mediaId)

发送语音消息

Example:

client.sendVoice(USER_ID, 'MEDIA_ID');

sendVideo(userId, video)

发送视频消息

Example:

client.sendVideo(USER_ID, {
  media_id: 'MEDIA_ID',
  thumb_media_id: 'THUMB_MEDIA_ID',
  title: 'VIDEO_TITLE',
  description: 'VIDEO_DESCRIPTION',
});

sendMusic(userId, music)

发送音乐消息

Example:

client.sendMusic(USER_ID, {
  musicurl: 'MUSIC_URL',
  hqmusicurl: 'HQ_MUSIC_URL',
  thumb_media_id: 'THUMB_MEDIA_ID',
  title: 'MUSIC_TITLE',
  description: 'MUSIC_DESCRIPTION',
});

sendNews(userId, news)

发送图文消息(点击跳转到外链)

Example:

client.sendNews(USER_ID, {
  articles: [
    {
      title: 'Happy Day',
      description: 'Is Really A Happy Day',
      url: 'URL',
      picurl: 'PIC_URL',
    },
    {
      title: 'Happy Day',
      description: 'Is Really A Happy Day',
      url: 'URL',
      picurl: 'PIC_URL',
    },
  ],
});

sendMPNews(userId, mediaId)

发送图文消息(点击跳转到图文消息页面)

Example:

client.sendMPNews(USER_ID, 'MEDIA_ID');

sendWXCard(userId, cardId)

发送卡券

Example:

client.sendWXCard(USER_ID, '123dsdajkasd231jhksad');

sendMiniProgramPage(userId, miniProgramPage)

发送小程序卡片

Example:

client.sendMiniProgramPage(USER_ID, {
  title: 'title',
  appid: 'appid',
  pagepath: 'pagepath',
  thumb_media_id: 'thumb_media_id',
});

Media API - Official Docs

uploadMedia(type, media)

多媒体文件上传接口

Example:

const fs = require('fs');

const buffer = fs.readFileSync('test.jpg');

client.uploadMedia('image', buffer).then(media => {
  console.log(media);
  // {
  //   type: 'image',
  //   media_id: 'MEDIA_ID',
  //   created_at: 123456789
  // }
});

getMedia(mediaiD)

下载多媒体文件接口

Example:

client.getMedia(MEDIA_ID).then(media => {
  console.log(media);
  // {
  //   video_url: "..."
  // }
});

Debug Tips

Log requests details

To enable default request debugger, use following DEBUG env variable:

DEBUG=messaging-api-wechat

If you want to use custom request logging function, just define your own onRequest:

const client = WechatClient.connect({
  appId: APP_ID,
  appSecret: APP_SECRET,
  onRequest: ({ method, url, headers, body }) => {
    /* */
  },
});

Test

Point requests to your dummy server

To avoid sending requests to real WeChat server, specify origin option when constructing your client:

const { WechatClient } = require('messaging-api-wechat');

const client = WechatClient.connect({
  appId: APP_ID,
  appSecret: APP_SECRET,
  origin: 'https://mydummytestserver.com',
});

Warning: Don't do this on production server.

Manual Mock with Jest

create __mocks__/messaging-api-wechat.js in your project root:

// __mocks__/messaging-api-wechat.js
const jestMock = require('jest-mock');
const { WechatClient } = require.requireActual('messaging-api-wechat');

module.exports = {
  WechatClient: {
    connect: jest.fn(() => {
      const Mock = jestMock.generateFromMetadata(
        jestMock.getMetadata(WechatClient)
      );
      return new Mock();
    }),
  },
};

Then, mock messaging-api-wechat package in your tests:

// __tests__/mytest.spec.js
jest.mock('messaging-api-wechat');