Build your WeChat chatbot

Photo by Sunrise on Unsplash

Just in case your company decides to interact with the 1 billion monthly active users on WeChat.

While most people are quite familiar with Facebook chatbot.

The thought of doing something with WeChat can seem kind of daunting,

Because it’s a Chinese software and you can’t just Google your way out if you’re stuck.

Even if you Baidu, you will likely end up at Segmentfault(Chinese version of Stack overflow).

So this article’s purpose is to get your feet wet with WeChat Public Platform.


Prerequisites:

Basic knowledge of NodeJS

Basic knowledge of Javascript

WeChat App

Get a WeChat Developer Sandbox Account

Go to this link.

Scan the QR code with WeChat app.

You can use chrome’s translation plugin to translate the page.

WeChat Sandbox Console

appID, URL, Token are the only fields we need to worry about for this chatbot.

Setup up NodeJS server

git clone https://github.com/davidyu37/wechat-chatbot
cd wechat-chatbot
yarn

Or do npm install instead of yarn if you’re allergic to yarn.

Setup up Environment

Create a file called .env at the project’s root folder.

APP_ID=210234019230492
TOKEN=whateveryoulike

Run It

yarn start

If no errors pop up, feel good about yourself.

Use Ngrok to quickly test your server

npm install ngrok -g

Ngrok enables WeChat server to talk to your server without having to put your code on ☁️. (Heroku, AWS, …)

With your NodeJS server running, run ngrok http 3000

Once ngrok is online, copy the url from your terminal. Put it in URL field in the sandbox account dashboard.

Make sure you add /wechat at the end of the url.

Put the token from .env file to Token field

If something green pop up at the top, it means that WeChat has successfully bind your url to the sandbox account.

Scan QR code of your sandbox account

If you scroll down on your sandbox account dashboard, you will see a QR code.

Scan it and begin sending it random things. Start to mess around with the code.

How it works?

Your NodeJS server is the User business logic

Tencent server sends request to the URL to confirm if the token matches.

If it matches, it will pass along the messages that users send to the account to the NodeJS server in XML

Tencent server expects a XML format of the user’s OpenID and the content of the message.

OpenID is WeChat user’s ID related to the Public Platform.

WeChat notifies the user that the service is unavailable after three tries.

Thanks to library by Jackson Tian.

His library takes care of the logic that authenticate the token and handle XML.

Official Documents:

Code Links:

Thanks for reading

If you think this article will be useful for your friend, please share and smash the 👏button to help other developers to discover this.

Call to Action

To learn more about WeChat development, click here to download a free glossary.