# Message Push
Message push is an active push service launched by the open platform. Based on the push service, developers can get the relevant information of the open platform in time without calling API. There are currently three ways to access:
- [The developer server receives a message push](#The developer server receives a message push)
- [Cloud function receives message push](#Cloud function receives message push)
- [WeChat CloudRun Service Receive Message Push](#WeChat CloudRun Receive Messages)
# The developer server receives a message push
Total data link as shown in Figure:![](https://res.wx.qq .com /op_res/CyXI7cGX7jxeP-vdY2Hkm9s2cMZlsxeY23fkgw44pPOtTwMbZQq-iM-3Lv4054rfJtUFVOwyac0E9I3vFclKqw )
# Message Push Server Configuration
The Official Account message template is available in Mini Program, Mini Mini game, WeChat Channels store and third-party platform. Here we introduce the configuration of Mini Program platform.
# Fill in the relevant information
LandMini Program management background, InDevelopment-Development management-Message push configurationPlease fill in the following information:
- URL: The interface that developers use to receive WeChat messages and events The URL, must be in the http:// or https:// Beginning, respectively, in support of 80 Port and 443 Port.
- Token: Used for signature processing, which is described below.
- EncodingAESKey: Will be used as the message body encryption and decryption key.
- Message encryption and decryption:
- Plaintext mode: do not use message encryption and decryption, plaintext sent, low security factor, not recommended.
- Compatibility mode: plaintext, ciphertext coexistence, not recommended.
- Safe mode: use message encryption and decryption, pure ciphertext, high security factor, strongly recommended.
- Data format: The format of the message body, either XML or JSON.
# Initiate verification
After clicking "Submit," the WeChat server will initiate the verification to the developer server. Please follow the following methods before submitting: WeChat Server will send a GET request to the URL of the server address filled in, The GET request carries parameters as shown in the following table:
parameter | describe |
---|---|
signature | autograph |
timestamp | timestamp |
nonce | random number |
echostr | Random character string |
Where signature is generated by:
- The three parameters of Token, timestamp and nonce are lexicographically sorted.
- A signature is obtained by concatenating three argument character strings into one string and signing it with sha1 computations. The developer needs to verify the signature is correct, to determine whether the request is from the WeChat server, after the verification, please return the echo str character string.
Example: Suppose the URL = "https://www.qq.com/revice", Token="AAA"
- Push URL link: https://www.qq.com/revice?signature=f464b24fc39322e44b38aa78f5edd27bd1441696&echostr=4375120948345356249×tamp=1714036504&nonce=1514711492
- The token, timestamp, nonce three parameters are lexicographic sort, sort the result is:["1514711492","1714036504","AAAAA"]。
- Concatenate the three argument strings into one character string: "15147114921714036504AAA"
- Perform sha1 calculation Signature: f464b24fc39322e44b38aa78f5edd27bd1441696
- Compared with the signature parameter in the URL link, the equivalent indicates that the request comes from the WeChat server and is legal.
- Construct back package to return WeChat, back package message body content for the URL link in the echostr parameter 4375120948345356249.
To make debugging easier for developers, we provideURL Verification ToolFor developers to use![](https://res.wx.qq .com /op_res/CyXI7cGX7jxeP-vdY2Hkm9kdbt1XFpcK-5W3xMW-rUdMFepPUAjXfDxv7v-V28ytPPMMydovWViBMEO4PKXFug ) The developer must complete[AccessToken ](https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken .html), URL address, Token, click "Check parameters and initiate validation," the debugging tool will send a GET request to the server referred to by the URL, and return relevant debugging information.
# Receive message push
When a particular message or event is triggered, the WeChat server sends the packet of the message (or event) to the POST The request is sent to the developer-configured URL, below to “debug_Demo”Event as an example, detailing the entire process:
# Message decryption mode is plaintext mode
- Suppose the URL is configured to https://www.qq.com/revice, Data format is JSON, Token = "AAAAA."
- Push URL link: https://www.qq.com/recive?signature=899cf89e464efb63f54ddac96b0a0a235f53aa78×tamp=1714037059&nonce=486452656
- Pushed package:
{
"ToUserName": "gh_97417a04a28d",
"FromUserName": "o9AgO5Kd5ggOC-bXrbNODIiE3bGY",
"CreateTime": 1714037059,
"MsgType": "event",
"Event": "debug_demo",
"debug_str": "hello world"
}
- Verify that the signature is correct to determine whether the request is from the WeChat server.
- The token, timestamp (in the URL parameter), and nonce (in the URL parameter) are lexicographically sorted, and the result is:["1714037059","486452656","AAAAA"]
- Concatenate the three argument character strings into one string: "1714037059486452656AAA"
- Perform sha1 calculationSigned: 899cf89e464efb63f54ddac96b0a0a235f53aa78
- Compared with the signature parameter in the URL link, the equivalent indicates that the request comes from the WeChat server and is legal.
- Return the package to WeChat, the specific content of the package depends on the specific interface document requirements, if there is no specific requirements, reply to the empty string or success.
# Message decryption in safe mode
- Suppose the URL is configured to https://www.qq.com/revice, 数据格式为JSON,Token="AAAAA",EncodingAESKey="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",小程序Appid="wxba5fad812f8e6fb9"。
- Push URL link:: https://www.qq.com/recive?signature=6c5c811b55cc85e0e1b54100749188c20beb3f5d×tamp=1714112445&nonce=415670741&openid=o9AgO5Kd5ggOC-bXrbNODIiE3bGY&encrypt_type=aes&msg_signature=046e02f8204d34f8ba5fa3b1db94908f3df2e9b3
- Pushed package:
{
"ToUserName": "gh_97417a04a28d",
"Encrypt": +qdx1OKCy+5JPCBFWw70tm0fJGb2Jmeia4FCB7kao+ /Q5c/ohsOzQHi8khUOb05JCpj0JB4RvQMkUyus8TPxLKJGQqcvZqzDpVzazhZv6JsXUnnR8XGT740XgXZUXQ7vJVnAG+tE8NUd4yFyjPy7GgiaviNrlCTj+l5kdfMuFUPpRSrfMZuMcp3Fn2Pede2IuQrKEYwKSqFIZoNqJ4M8EajAsjLY2km32IIjdf8YL /P50F7mStwntrA2cPDrM1kb6mOcfBgRtWygb3VIYnSeOBrebufAlr7F9mFUPAJGj04="
}
- Verify msg_The signature is correct to determine whether the request is from the WeChat server. Note: Do not use signature validation!
- The token, timestamp (in the URL parameter), nonce (in the URL parameter), Encrypt (in the package body field) four parameters lexicographic sort, sort the result is: [+qdx1OKCy+5JPCBFWw70tm0fJGb2Jmeia4FCB7kao+ /Q5c/ohsOzQHi8khUOb05JCpj0JB4RvQMkUyus8TPxLKJGQqcvZqzDpVzazhZv6JsXUnnR8XGT740XgXZUXQ7vJVnAG+tE8NUd4yFyjPy7GgiaviNrlCTj+l5kdfMuFUPpRSrfMZuMcp3Fn2Pede2IuQrKEYwKSqFIZoNqJ4M8EajAsjLY2km32IIjdf8YL /P50F7mStwntrA2cPDrM1kb6mOcfBgRtWygb3VIYnSeOBrebufAlr7F9mFUPAJGj04=", "1714112445", "415670741", "AAAAA"]。
- The four parameter string stitching into a character string, and then calculate the signature sha1: 046e02f8204d34f8ba5fa3b1db9908f2e9b3
- With msg in the URL parameter _Signature parameters for comparison, equivalent to the request from WeChat server, legal.
- Decrypts the message body "Encrypt" ciphertext.
- AESKey = Base64_Decode( EncodingAESKey + "=" ),EncodingAESKey The trailing edge of a character "=", use Base64_Decode generate 32 One byte AESKey
- Base64 decodes the Encrypt ciphertext to get TmpMsg, 224 bytes in length
- The TmpMsg is AES decrypted using AESKey to get a FullStr with a byte length of 205. AES Use CBC Mode, the key length is 32 Bytes (256 Bit), the data adopts PKCS#7 Fill PKCS#7:K Number of key bytes (using 32),Buf For the content to be encrypted, n Its number of bytes. Buf Need to be filled as K The whole number of times. in Buf The tail filling of the(K - N%K)The content of each byte yes(K - N%K)The WeChat team provided sample code in a number of languages (including PHP, Java, C++, Python, C #), please developers try to use the sample code, carefully read the technical documentation, sample code and comments, and then code debugging.[Sample download](https://wximg.gtimg.com /Shake_tv/mpwiki/cryptoDemo.zip)
- FullStr=random(16B) + msg_len(4B) + msg + Appid, of which:
- random(16B)for 16 Random character string of bytes
- msg_len for msg Length, accounted for 4 One byte(Network byte order)
- MSG for decrypted plaintext
- Appid is a Mini Program Appid, and the developer needs to verify that the Appid matches its own Mini Program.
- In this example:
- random(16B)="a8eedb185eb2fecf"
- msg_Len = 167 (note: 4 bytes in network byte order)
- msg="{"ToUserName":"gh_97417a04a28d","FromUserName":"o9AgO5Kd5ggOC-bXrbNODIiE3bGY","CreateTime":1714112445,"MsgType":"event","Event":"debug_demo","debug_str":"hello world"}"
- appid="wxba5fad812f8e6fb9"
- Back to the WeChat server, first need to determine the clear text content of the bag body, depending on the specific interface document requirements, such as no specific requirements, reply empty string or success (no encryption) can be, other back to the package content need to be encrypted. It is assumed that the plaintext content of the package body is "{" demo_resp":"good The data format is JSON. Here's how to encrypt the back packet:
- Depending on the data format you configure (JSON or XML), where:
- Encrypt: Encrypted content
- MsgSignature: signature, WeChat will verify the signature
- TimeStamp: Time Stamp
- Nonce: Take the chance
{ "Encrypt": " ${msg _encrypt}$", "MsgSignature": " ${msg _signature}$", "TimeStamp": ${timestamp}$, "Nonce": ${nonce}$ }
<xml> <Encrypt><![CDATA[${msg _encrypt}$]]></Encrypt> <MsgSignature><![CDATA[${msg _signature}$]]></MsgSignature> <TimeStamp>${timestamp}$</TimeStamp> <Nonce><![CDATA[${nonce}$]]></Nonce> </xml>
- Generate method for encrypt:
- AESKey = Base64_Decode( EncodingAESKey + "=" ),EncodingAESKey The trailing edge of a character "=", use Base64_Decode generate 32 One byte AESKey
- Construct FullStr = random(16B) + msg_len(4B) + msg + Appid, of which
- random(16B)for 16 Random character string of bytes
- msg_len for msg Length, accounted for 4 One byte(Network byte order)
- Msg for plaintext
- Appid is a Mini Program Appid.
- In this example:
- random(16B)="707722b803182950"
- msg_Len = 25 (note: 4 bytes in network byte order)
- msg = "{"demo _resp":"good luck"}"
- appid="wxba5fad812f8e6fb9"
- FullStr has a byte size of 63
- FullStr is encrypted with AESKey to get a TmpMsg with a byte size of 64. AES Use CBC Mode, the key length is 32 Bytes (256 Bit), the data adopts PKCS#7 Fill PKCS#7:K Number of key bytes (using 32),Buf For the content to be encrypted, n Its number of bytes. Buf Need to be filled as K The whole number of times. in Buf The tail filling of the(K - N%K)The content of each byte yes(K - N%K)The WeChat team provided sample code in a number of languages (including PHP, Java, C++, Python, C #), please developers try to use the sample code, carefully read the technical documentation, sample code and comments, and then code debugging.[Sample download](https://wximg.gtimg.com /Shake_tv/mpwiki/cryptoDemo.zip)
- Base64 encode TmpMsg to get Encrypt = "ELGduP2YcVatjqIS+eZbp80MNLoAUWvzzyJxgGzxZO/5sAvd070Bs6qrLARC9nVHm48Y4hyRbtzve1L32tmxSQ=="。
- TimeStamp is generated by the developer, using the current timestamp, the example uses 1713424427.
- The nonce backfills the nonce parameter in the URL parameter, for example 415670741.
- MsgSignature is generated by:
- The four parameters of token, TimeStamp (in the back packet), Nonce (in the back packet), and Encrypt (in the back packet) are lexicographically sorted, and the result is: ["1713424427", "415670741", "AAAAA", "ELGduP2YcVatjqIS+eZbp80MNLoAUWvzzyJxgGzxZO/5sAvd070Bs6qrLARC9nVHm48Y4hyRbtzve1L32tmxSQ=="]
- The four parameter string stitching into a character string, and sha1 calculation signature: 1b9339964ed2e271e7c7b6ff2b0ef902fc94 dea1
- The final package is:
{
"Encrypt": "ELGduP2YcVatjqIS+eZbp80MNLoAUWvzzyJxgGzxZO/5sAvd070Bs6qrLARC9nVHm48Y4hyRbtzve1L32tmxSQ==",
"MsgSignature": "1b9339964ed2e271e7c7b6ff2b0ef902fc94dea1",
"TimeStamp": 1713424427,
"Nonce": "415670741"
}
In order to facilitate debugging, we provide relevant debugging tools (Request construction、Debugging tool) for use by developers.
- "Request Construct" allows the developer to fill in the relevant parameters to generate a debug_Demo event or back to the package related debugging information for developers to use.[](https://res.wx.qq .com /op_res/CyXI7cGX7jxeP-vdY2HkmzPAxYtOmSK_jSvQsQKLjBlK9LTCJjQY14AmHwQmPIcyQWFYPWpn8lqzVjfQKB9y1w )
- The Debugging Tool allows the developer to fill in the[AccessToken ](https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken .html)After the Body, the WeChat Server will pull the message you configure in the background of the Mini Program to push the configuration, and actually push a debug_Demo event for developers to debug.![](https://res.wx.qq .com /op_res/CyXI7cGX7jxeP-vdY2Hkm-hEi9O6s8jFZI7ewGAoi8bUp6X86EpNxCM2wn_rnHrhQ7ByOfhYVmrN-TLJVR69HQ )
# Cloud function receives message push
Developer Tools Version required at least
1.02.1906252
Opened.[Cloud development](https://developers.weixin.qq.com/miniprogram/dev/wxcloud /basis/getting-started.html)The Mini Program can use the cloud function to receive push messages, and currently only supports customer service push messages.
The access steps are as follows:
- Fill out the configuration and upload it in the cloud development console
- Processing messages in cloud functions
# Step 1: Add configuration to the developer tools cloud development console
Go to the path “Cloud development-Set up-Other settings-Message Push”, Select the push mode as a cloud function
Add a message push configuration. The message type has an effect on the MsgType
, the event type has an effect on the Event
, the same <Type of message, Type of event>
Binary groups can only be pushed to one cloud function in one environment. For example, the customer service message text message corresponds to the message type text
, The event type is empty. See the message format for each message.
Multiple message types and event types can be added to the message push configuration multiple times.
Be careful: If a certain type of message is configured in the cloud function, the type of message will no longer be pushed to the domain name configured in "WeChat Public Platform - Development Settings - Message Push."
# Step 2: Processing messages in cloud functions
When the cloud function is triggered, its event
Parameters are defined by the interface JSON The object of the structure (unifying JSON
Format, not supported XML
Format).
Take the customer service message as an example. Upon receiving the service message push,event
The structure is as follows:
{
"FromUserName": "ohl4L0Rnhq7vmmbT_DaNQa4ePaz0",
"ToUserName": "wx3d289323f5900f8e",
"Content": "Testing,"
"CreateTime": 1555684067,
"MsgId": "49d72d67b16d115e7935ac386f2f0fa41535298877_1555684067",
"MsgType": "text"
}
Customer service messages can be invoked at this timesendInterface reply message, a simple unified reply after receiving the message "Received." An example of this 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'
}
# WeChat CloudRun Receive Messages
use[WeChat cloud hosting](https://cloud.weixin.qq.com/cloudrun?utm _source=wxdoc&utm_content=msgpush )Mini Program/Official Account message template can use cloud hosting service to receive message push, only need to configure a cloud hosting service can support all types of message push.
The access steps are as follows:
- WeChat cloud hosting console to fill in the configuration
- Processing messages in cloud hosted services
# step one Cloud Hosting Console Fill Out Configuration
Go to the path “WeChat cloud hosting-Set up-Other settings-Message Push”In Configuration
Click Configure, select the target cloud development environment, fill in the corresponding cloud hosting service path (path can go to "cloud hosting" - "service list" - "path field" to copy), select the push type
- Environment ID: Select to receive a message push
- Service Name: A service that receives push messages. Only 1 service needs to be configured to receive all types of messages
- Path: Which interface under the service receives and writes the path of the interface in the service.
- Push mode: support JSON, XML two modes
After configuration is complete, the cloud hosting service can receive the current Mini Program/All types of Official Account message templates.
# Configuration test
When configuring push messages, the WeChat backend will initiate a detection request to the configured service.
When the configuration format is JSON The request body is:
{ "action": "CheckContainerPath"}
When the configuration format is XML The request body is:
<xml><action>CheckContainerPath</action></xml>
Developer Reply success Or return empty.
# Confirm the source
If the cloud hosting does not enable public access, you can trust all push messages. If the cloud hosting opens the public network access, you need to verify the request header of the message push, with x-wx-sources The request is the push initiated by the WeChat side.
# Step 2 Processing messages in cloud hosted services
The following example shows how to use cloud hosting in conjunction with push messaging to enable customer service message response. Note: You need to deploy the following image first, and then fill in the path and environment of the corresponding service in Settings - Other Settings - Push Messages. ID。
const express = Require('express')
const BodyParser = Require('body-parser')
const axios = Require('axios')
const PORT = process.env.PORT || 80
const HOST = '0.0.0.0'
// App
const app = express()
app.use(bodyParser.raw ())
app.use(bodyParser.json ({}))
app.use(bodyParser.urlencoded({ extended: true }))
const client = axios.default
app.all('/', async (req, res) => {
const headers = req.headers
const weixinAPI = `http://api.weixin.qq .com /cgi-bin/message/custom/send`
const payload = {
touser: headers['x-wx-openid' ],
msgtype: 'text',
text: {
content: `The cloud hosting received the message push successfully, which reads as follows:n${JSON.stringify(req.body, null, 2)}`
}
}
// dispatch to wx server
const result = await client.post (weixinAPI, payload)
console.log('received request', req.body, result.data)
res.send('success')
})
app.listen(PORT, HOST)
console.log(`Running on http://${HOST}:${PORT}`)
After the configuration is successful, use the <button open-type="contact">
Type of button evokes a customer service conversation, and send any message to see a response from cloud-hosted processing.