Use Cloud Call to receive and send WeChat messages.
Overview
Developers may use the WeChat customer service messaging feature to receive customer service conversation messages from Mini Program users and send messages to users.
The cloud call function of Mini Program Cloud Development natively integrates with the WeChat message push interface. Developers only need to call the corresponding function to easily complete the message push process.
Solution Comparison
Receive Messages
Send Messages
Code Sample
Mini Programs that have enabled Cloud Development can use cloud functions to receive message pushes, currently only supporting customer service messages.
See: Using Cloud Functions to Receive Message Push
Step 1: Add Configuration in Developer Tools Cloud Development Console
Open the Cloud Development Console, go to the Settings Tab, select "Global Settings" - "Add Message Push Configuration", and add a cloud function to receive messages.
The message type corresponds to the MsgType
in the received packet, and the event type corresponds to the Event
in the received packet. The same <message type, event type>
tuple can only be pushed to one cloud function in one environment. For example, for a customer service text message, the message type is text
and the event type is empty. Please refer to the message format of each message for specific values.
Step 2: Receive and Process Messages in Cloud Functions
When a cloud function is triggered, its event
parameter is the object of the JSON structure defined by the interface (unified JSON format, XML format is not supported).
Take customer service messages as an example. When receiving a customer service message push, the event
structure is as follows:
{
"FromUserName": "ohl4L0Rnhq7vmmbT_DaNQa4ePaz0",
"ToUserName": "wx3d289323f5900f8e",
"Content": "Test",
"CreateTime": 1555684067,
"MsgId": "49d72d67b16d115e7935ac386f2f0fa41535298877_1555684067",
"MsgType": "text"
}
Step 3: Send Customer Service Messages
At this point, you can call the Customer Service Message Sending API to reply to messages. A simple sample that uniformly replies with "Received" upon receiving a message is as follows:
// Cloud Function entry file
const cloud = require("wx-server-sdk");
cloud.init();
// Cloud function entry function
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext();
await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: "text",
text: {
content: "Received",
},
});
return "success";
};