May 18, 2021 WeChat Mini Program Development Document
The synoper also provides a range of APIs that use HTTPS request calls on back-end servers to help developers perform a variety of data analysis, management, and query operations in the background. Such as getAccessToken, code2Session, etc.
access_token is the only global background interface calling credentials for a small program, which is required when calling the vast majority of background interfaces. Developers can get it and save it properly through the getAccessToken interface.
For access_token security, the back-end API cannot be called directly within a small program through wx.request, that is, api.weixin.qq.com cannot be configured as a server domain name. Developers should use get the data on the back-end server using get access_token and call the relevant API;
Note: When the API call succeeds, some interfaces do not return errcode and errmsg, only if the call fails.
Access to WeChat's small program messaging service, you can choose one of two ways:
Developers need to follow these steps:
After logging into the background of the program, in Development - Development Settings - Message Push, the administrator scans the code to enable the messaging service and fills in information such as server address (URL), token (Token), and message encryption key (EncodingAESKey).
At the same time, developers can choose how messages are decrypted: clear text mode (default), compatibility mode, and security mode. You can choose the message data format: XML format (default) or JSON format.
The choice of mode and server configuration will take effect immediately after submission, please developers carefully fill in and select. Switching encryption methods and data formats requires configuring the relevant code in advance, please refer to the message plus decryption instructions for details.
After the developer submits the information, the WeChat server will send the GET request to the filled-in server address URL, and the GET request carry parameters are shown in the table below:
Parameters | Describe |
---|---|
signature | WeChat encrypted signature, signature combined with the developer token parameters and the request in the timestamp parameters, nonce parameters. |
timestamp | Time stamp |
Nonce | Random number |
echostr | Random string |
The developer verifies the request by verifying the signature (there is a check below). I f it is confirmed that the GET request is from the WeChat server, please return the echostr parameter content as is, the access will take effect and the developer will succeed, otherwise the access will fail. The encryption/verification process is as follows:
After verifying the validity of the URL, the access takes effect and becomes a developer.
Test the PHP sample code for 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;
}
}
PHP sample code download: Download
When certain user actions raise an event push, such as a user sending a message to a small program customer service, or entering a session, the WeChat server sends packets of messages (or events) to the DEVELOPER-configured URL with a POST request, which the developer can respond to based on their own business logic.
After the WeChat server sends the user's message to the developer server address, the WeChat server loses the connection and re-initiates the request within five seconds, retrying it three times in total. I f, during debugging, you find that the user cannot receive a response message, you can check to see if the message processing timed out. F or message scheduling for retrying, messages with msgid are recommended for use msgid scheduling. Event type messages are recommended for fromUserName and CreateTime scheduling.
The server must respond to the request below so that the WeChat server does not do anything about it and does not retry, otherwise a serious error message will occur. See the instructions below:
For customer service messages, WeChat will send a system prompt to the user in a small program session that "the customer service of the small program is temporarily unable to provide services, please try again later":
If the developer wants to enhance security, message encryption can be turned on at the Developer Center so that messages sent by users to small programs and messages sent by small programs that passively reply to user messages continue to be encrypted, as detailed in the message plus decryption instructions.
A developer tool version is required at least 1.02.1906252
Small programs with cloud development available can receive message pushes using cloud functions, and currently only customer service messaging is supported.
The access steps are as follows:
Open the cloud development console and select the global settings in settings tab - add a message push configuration. T he message type corresponds to the msgType of the package, the event type corresponds to the event of the package, the same message type, and the event type and binary can only be pushed to a cloud function of an environment. F or example, a customer service message text message corresponds to a message type of text and an empty event type. For specific values, check the message format for each message.
When a cloud function is triggered, its event parameter is the object of the JSON structure defined by the interface (unified JSON format, not XML format).
Take customer service messages as an example, when you receive a customer service message push, the event structure is as follows:
{
"FromUserName": "ohl4L0Rnhq7vmmbT_DaNQa4ePaz0",
"ToUserName": "wx3d289323f5900f8e",
"Content": "测试",
"CreateTime": 1555684067,
"MsgId": "49d72d67b16d115e7935ac386f2f0fa41535298877_1555684067",
"MsgType": "text"
}
At this point, the customer service message sending interface can be called to reply to the message, a simple received message after the unified reply "received" example is as follows:
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: 'text',
text: {
content: '收到',
},
})
return 'success'
}