tencent cloud

All product documents
Tencent Cloud Super App as a Service
DocumentationTencent Cloud Super App as a ServicePractice TutorialMini Program Subscription Message Practical Tutorial
Mini Program Subscription Message Practical Tutorial
Last updated: 2025-02-28 19:49:47
Mini Program Subscription Message Practical Tutorial
Last updated: 2025-02-28 19:49:47

Introduction

Message capabilities are essential for mini programs. Super app allows developers to send subscription messages, creating a closed-loop service. This provides better experience for super app users. In the business ecosystem of a super app, most lifestyle service mini programs or mini games involve payment transactions. Once a payment transaction occurs, an order is generated, and the order undergoes status changes. Therefore, it is necessary to use message subscription and notification capabilities to promptly push order status updates from the mini programs to super app users, allowing them to receive real-time business notifications from different mini programs. The mini program subscription message solution is designed for this purpose. To implement the subscription message feature for the above scenarios, you can follow these steps:

Subscription message solution

1. Prerequisites

To enable the subscription message feature for the super app and mini programs, your app needs to activate the push notification service. Otherwise, mini program subscription messages cannot reach users through the app's push channels.

2. Add message templates

Go to the console, navigate to <b>Mini program management</b> -<b> Subscription</b> <b>message</b>. Pick suitable templates from the public template library, configure the fields, and add them to <b>My templates</b>.

3. Trigger subscription messages in the mini program

Step 1: Get template ID

After adding message templates as instructed above, the configured template ID can be obtained for subsequent message subscription operations.

Step 2: Obtain the user’s consent

For one-time subscription or long-term subscription in the mini program, use wx.requestSubscribeMessage to trigger the client subscription message interface. After the user interacts with the interface, it returns the user's subscription message operation result. If the result is "accept", it indicates that the user has agreed to subscribe to the template message corresponding to the template ID, and the template is available.

Example
JAVASCRIPT
Page({
// tmplIds:Array of template IDs that need to be subscribed
requestSubscribeMessage(tmplIds) {
wx.requestSubscribeMessage({
tmplIds,
success: (res) => {
console.log('wx.requestSubscribeMessage===success', res)
const keysWithAccept = Object.entries(res)
.filter(([key, value]) => value === "accept")
.map(([key]) => key);
if (keysWithAccept.length > 0) {
// Send subscription message
this.orderSubscribe(keysWithAccept)
} else {
wx.showModal({
title: 'No available message templates',
confirmText: 'Confirm',
showCancel: false
})
}
},
fail: (res) => {
console.log('wx.requestSubscribeMessage===fail', res)
wx.showModal({
title: 'wx.requestSubscribeMessage fail',
confirmText: 'Confirm',
content: `${res.errMsg}【${res.errCode}】`,
showCancel: false
})
}
})
},
})

Step 3: Call the API to deliver the subscription message

When a user triggers an operation in the mini program that requires receiving messages, the mini program calls a custom API to communicate with its backend service, passing along the available template ID. The backend service then uses the platform's OpenServer send API to send the subscription message.

4. Deliver subscription messages from the mini program backend

The prerequisite for enabling a mini program to send subscription messages is that the mini program integrates the getAccessToken API.
Typically, the mini program backend needs to retrieve the subscription relationships of the mini program by calling an API such as orderSubscribe shown in the above example. The mini program backend must persist the successfully subscribed templates, subscription times, and subscribers (openid). After the subscription action is completed, sending the message is usually a future action. The mini program backend should provide a platform for message dispatch or use other middleware or APIs to trigger message sending.
When subscribing to messages, the tmplIds parameter can be validated for template ID validity through a background APIs.

Please refer to the following APIs for sending subscription messages. Special attention should be paid to the format of the data field. See the example below.
If the subscription message template is as follows:
name: {{name01.DATA}}
amount: {{amount01.DATA}}
journey: {{thing01.DATA}}
date: {{date01.DATA}}
the data structure of the corresponding message is as follows:
{
"touser": "OPENID",
"template_id": "TEMPLATE_ID",
"page": "index",
"data": {
"name01": {
"value": "who "
},
"amount01": {
"value": "$100"
},
"thing01": {
"value": "from beijing to shanghai"
} ,
"date01": {
"value": "2018-01-01"
}
}
}

5. Super app receives and displays subscription messages




In the previous step, the mini program backend sends subscription messages to the super app backend. The super app backend needs to provide an API for retrieving the message list to the super app, so that the app can obtain subscription message data pushed from the mini program and display the messages to app users.
Note:
The API for super app to retrieve message list needs to be developed on the super app backend.
We recommend that the app receives and displays subscription messages in the following ways.
If your app is equipped with social chat features, we recommend that you place the notification entry for subscription messages in the chat list for users to view in real time.

In addition, if your app has a system message feature, you can also use the system message entry for subscription messages.

You can also decide the entry of the subscription messages according to your own preferences. We recommend placing the entry in a more prominent position.
Once you have the entry point for subscription messages, the next step is to create a custom subscription message list page, which we will refer to as the "Message card" page. This page will be used to display subscription messages. You can refer to the image below for UI implementation.

Below is an example on how to implement the subscription message list and “Message card”.
When entering the "Message card" page, call the super app backend to retrieve the subscription messages. Example:
// Define an array variable jsonDatas, used to store the acquired data, the initial value is nil
BLOCK_ARRAY jsonDatas = nil;

// Call getMessage method of the singleton SubscriptionManager to retrieve message data
// Parameters:
// - token: The token of the logged-in user
// - appId: The appKey from the configuration file (tcmpp-ios-configurations.json or tcmpp-android-configurations.json)
// Successful callback:
// - message: The array of retrieved message data
// Failed callback:
// - error: Error information
[SubscriptionManager.sharedInstance getMessage: UserInfo.sharedInstance.token
appId: MiniAppSDKManager.sharedInstance.configAppKey
success:^(ARRAY message) {
// Check if message is an array; if not, return immediately
if (![message isArray]) {
return;
}

// Check if the message array is empty; if so, return immediately
if ([message isEmpty]) {
return;
}

// Assign the retrieved message data array to the jsonDatas variable
jsonDatas = message;

// Create a mutable array arrayDatas to store the parsed data models
MUTABLE_ARRAY arrayDatas = [NSMutableArray array];

// Iterate over the jsonDatas array
for (DICTIONARY json in jsonDatas) {
// Parse each json data into a SubscribeInfoModel object
SubscribeInfoModel *model = [[SubscribeInfoModel alloc] initWithJsonDatas: json];

// Add the model object to the arrayDatas array
[arrayDatas addObject: model];
}

// Assign the arrayDatas array to the self.modelDatas property
self.modelDatas = [NSArray arrayWithArray: arrayDatas];

// Asynchronously execute the tableView's reloadData method on the main thread to refresh the table data
[self.tableView performSelectorOnMainThread: @selector(reloadData)
withObject: nil
waitUntilDone: YES];
}
failure:^(ERROR error) {
// Handle the failure to retrieve message data, providing failure prompts based on the business scenario
}];
In the example, we pass the user’s token and AppKey parameters through the getMessage API provided by the app to retrieve the subscription card data. In the successful callback, the corresponding subscription data is deserialized and updated in the view container, followed by a refresh.
Tap the card to enter the corresponding mini program page. Example:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// Get the subscription model object corresponding to the tapped card
SubscribeInfoModel *model = self.modelDatas[indexPath.row];
// Pass the parameters of the subscription model object and call the SDK's method to open the mini program
[[TMFMiniAppSDKManager sharedInstance] startUpMiniAppWithAppID:model.MnpId verType:model.vertype scene:0 firstPage:model.Page paramsStr:nil parentVC:self completion:^(NSError * _Nullable error) {
if(error) {
// If opening fails, provide a prompt based on the business scenario
return;
}
// If opening succeeds, provide a prompt based on the business scenario
}];
}
In the example, we retrieve the corresponding subscription object by tapping on a list element. By calling the startUpMiniAppWithAppID method, we pass in parameters such as the mini program ID, its status, and the entry page to open the mini program.

Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback

Contact Us

Contact our sales team or business advisors to help your business.

Technical Support

Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

7x24 Phone Support