# Message Push
There are two ways to integrate the Weixin Mini Program message push service:
# Developer Server Receives Pushed Messages
Developers need to perform the following steps to receive pushed messages:
- Enter server configurations
- Verify that the server address is valid
- Implement the business logic to receive messages and events as per the API documentation
# Step 1: Enter server configurations
Log in as the admin to the Mini Program console, and go to Development > Development Settings > Message Push. Scan the QR code to enable the messaging service, and enter information such as the server address (URL), the token (Token), and the message encryption key (EncodingAESKey).
- URL: URL of an API used by a developer to receive Weixin messages and events. The URL must begin with http:// or https:// and support port 80 and port 443 respectively.
- Token: It can be randomly entered by the developer to generate a signature (this token is compared with the token included in the API URL to verify security).
- EncodingAESKey: It is manually entered or randomly generated by the developer, and used as the encryption/decryption key for the message body.
The developer can also set the message encryption/decryption mode to the plaintext mode (default), compatibility mode, or security mode, and set the message data format to the XML format (default) or the JSON format.
The selected mode and the server configurations take effect immediately after submission, so please proceed with caution. To switch between the encryption modes and data formats, you need to first configure necessary code. For details, see About Message Encryption and Decryption.
# Step 2: Verify that the message comes from the Weixin server
After the developer submits the information, the Weixin server sends a GET request to the entered server URL. The parameters carried by the GET request are as follows:
Parameter | Description |
---|---|
signature | Weixin encrypted signature. The signature combines the token parameter entered by the developer and the timestamp and nonce parameters in the request. |
timestamp | Timestamp |
nonce | Random number |
echostr | Random string |
Developers verify (see the verification method below) the request by verifying the signature. If you confirm the GET request comes from the Weixin server, return the echostr parameter as is, so that the access takes effect and you enter the developer mode; otherwise, the access failed. The encryption/verification procedure is as follows:
- Sort the token, timestamp, and nonce parameters in lexicographic order.
- Join the strings of the three parameters into one string and encrypt it via SHA1.
- Compare the encrypted string with the signature. If they match, the request comes from Weixin.
If the URL is validated, the access takes effect and you enter the developer mode.
PHP code sample for verifying the signature:
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if ($tmpStr == $signature ) {
return true;
} else {
return false;
}
}
Download the PHP code sample
# Step 3: Receive messages and events
When event push is triggered by some specific user operations (for example, the user sends a message to the Mini Program customer service, or starts a session), the Weixin server sends the data package of the message (or event) via a POST request to the URL configured by the developer. The developer can respond to the POST request based on the business logic.
After sending the user message to the server address of the developer, if the Weixin server failed to receive any response within five seconds, it will disconnect from the URL and re-send the request. The Weixin server will make a total of 3 retry attempts. During debugging, if it is found that the user cannot receive any response message, check whether message processing timed out. It is recommended that you remove duplicate messages by msgid, and remove duplicate event messages according to FromUserName and CreateTime.
The Weixin server does not perform any processing or make retry attempts only when the server responds in any of the following ways after receiving the request; otherwise, a severe error may occur.
- Directly replies "success" (recommended).
- Directly replies an empty string (an empty string containing 0 bytes, but not an empty content field in the structure).
- Returns the response content specified in the API documentation if any.
In any of the following cases, Weixin will send a customer service message in a Mini Program session to notify the user that "The Mini Program currently cannot provide customer services. Try again later":
- The developer did not reply any content within 5s.
- The developer returned exception data.
To enhance security, developers can enable message encryption in the Developer Center. So that the messages sent by users to Mini Programs and the messages replied passively by the Mini Programs will be encrypted. For details, see About Message Encryption and Decryption.
# Cloud Functions Receive Pushed Messages
This feature is supported as of Weixin DevTools
1.02.1904220
, and Nightly Build is required.
After Cloud Base is activated for a Mini Program, cloud functions can be used to receive pushed messages. This feature only supports messages pushed by Customer Service.
The integration procedure is as follows:
- In Weixin DevTools, complete and upload configuration
- Messages are processed in cloud functions
# Step 1: In Weixin DevTools, complete and upload configuration
Create a new message push configuration file, temp-cloud-callback-config.json
, in the project's root directory. After completing the configuration, right-click the file and select "Upload Configuration".
The format of the configuration file is as follows (using Customer Service message push configuration as an example):
{
"enable": true,
"callbacks": [
{
"msgType": 1,
"functionName": "Cloud function name",
"env": "EnvironmentID"
}
]
}
Fields:
enable
: Cloud function message push is enabled only when this field is set to true. Otherwise, cloud function message push is not activated.callbacks
: The configuration for all cloud functions that receive push messages.callbacks.msgType
: ThemsgType
of a message. ThemsgType
for a Customer Service messages is 1.callbacks.functionName
: The name of the cloud function that receives push messages.callbacks.env
: The environment of the cloud function.
After completing the configuration, right-click the file and select Upload Configuration.
# Step 2: Messages are processed in cloud functions
When a cloud function is triggered, its event
parameter is the JSON object defined by the API (objects support JSON
format, but not XML
format).
When a message pushed by Customer Service is received, the event
structure is as follows:
{
"FromUserName": "ohl4L0Rnhq7vmmbT_DaNQa4ePaz0",
"ToUserName": "wx3d289323f5900f8e",
"Content": "Test",
"CreateTime": 1555684067,
"MsgId": "49d72d67b16d115e7935ac386f2f0fa41535298877_1555684067",
"MsgType": "text"
}
Here, you can call the API for sending Customer Service messages to reply to the message. In the following example, "Received" is sent after a messaged is received.
// Cloud function entry file
const cloud = require('wx-server-sdk')
cloud.init()
// Entry function of the cloud 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'
}