messaging-api-wechat

Messaging API client for WeChat

Usage no npm install needed!

<script type="module">
  import messagingApiWechat from 'https://cdn.skypack.dev/messaging-api-wechat';
</script>

README

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 = new WechatClient({
  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 calling console.log with 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

Media API - Official Docs

Debug Tips

Log Requests Details

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

DEBUG=messaging-api:request

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

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

Testing

Point Requests to Your Dummy Server

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

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

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

Warning: Don't do this on your production server.