Push notifications and messages for mini-programs
Mini Program Push Notifications and Messages
Push notifications and messages in mini programs are crucial tools for improving user retention and engagement. Proper use of push functionality can effectively reach users, but excessive pushes may lead to user dissatisfaction or even app uninstallation. WeChat Mini Programs offer various message push methods, and developers need to choose the appropriate one based on business scenarios.
Message Types and Use Cases
WeChat Mini Programs primarily support the following message types:
- Template Messages (gradually being replaced by subscription messages)
- Subscription Messages (long-term and one-time subscriptions)
- Customer Service Messages
- Unified Service Messages
Subscription Messages are currently the primary push method, suitable for scenarios like order status updates, logistics information, and service reminders. For example, an e-commerce mini program can send a payment success notification after a user places an order:
// Example of sending a subscription message
wx.requestSubscribeMessage({
tmplIds: ['OrderStatusUpdateTemplateID'],
success(res) {
if (res['OrderStatusUpdateTemplateID'] === 'accept') {
// User agreed to subscribe; message can be sent
wx.cloud.callFunction({
name: 'sendSubscribeMessage',
data: {
templateId: 'OrderStatusUpdateTemplateID',
page: 'pages/order/detail?id=123',
data: {
thing1: { value: 'Your payment was successful' },
amount2: { value: '99.00' },
time3: { value: '2023-05-20 14:30' }
}
}
})
}
}
})
Implementing Subscription Messages
One-Time Subscription Messages
One-time subscriptions require user activation each time and are suitable for low-frequency but important notifications. Implementation steps:
- Obtain a template ID.
- Frontend calls
wx.requestSubscribeMessage
. - Backend calls the
subscribeMessage.send
interface.
// Frontend requests user authorization
Page({
onPaySuccess() {
wx.requestSubscribeMessage({
tmplIds: ['TemplateID1', 'TemplateID2'],
success(res) {
console.log('Subscription result', res)
}
})
}
})
Long-Term Subscription Messages
Available only for specific categories like government, healthcare, and education, requiring additional permissions.
Message Sending Limits and Strategies
WeChat imposes strict limits on message pushes:
- One-time subscription messages are valid for 7 days.
- Each user can receive no more than 3 messages per day for the same template.
- The same user can receive no more than 5 subscription messages for the same template within 7 days.
Optimization Strategies:
- Merge notification content to reduce frequency.
- Set quiet hours (e.g., 11 PM to 8 AM).
- Provide message preference settings for user customization.
Server-Side Implementation Example
Node.js example for sending subscription messages:
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async (event, context) => {
try {
const result = await cloud.openapi.subscribeMessage.send({
touser: event.userOpenId,
templateId: event.templateId,
page: event.page,
data: event.data
})
return result
} catch (err) {
console.error(err)
return err
}
}
Message Template Design Tips
Effective message templates should follow these principles:
- Concise and Clear: Highlight key information upfront.
- Action-Oriented: Include clear instructions.
- Personalized: Add user-specific details.
Example template:
{{thing1.DATA}} (Status Update)
Amount: {{amount2.DATA}}
Time: {{time3.DATA}}
Click to view details
Error Handling and Monitoring
Essential monitoring points:
- Message delivery success rate.
- User click-through rate.
- Subscription rejection rate.
- Message delivery delay.
// Monitor message delivery status
wx.onMessageSentCallback(res => {
if (res.errCode === 0) {
// Delivery successful
reportAnalytics('message_sent', { templateId: res.templateId })
} else {
// Delivery failed
reportAnalytics('message_failed', {
templateId: res.templateId,
errCode: res.errCode
})
}
})
User Preference Management
Providing user control options can significantly reduce unsubscribe rates:
Page({
data: {
messageSettings: {
orderNotify: true,
promotionNotify: false,
systemNotify: true
}
},
toggleSetting(e) {
const type = e.currentTarget.dataset.type
this.setData({
[`messageSettings.${type}`]: !this.data.messageSettings[type]
})
// Sync with server
wx.request({
url: 'https://api.example.com/settings',
method: 'POST',
data: this.data.messageSettings
})
}
})
Best Practices for Message Pushes
-
Contextual Pushes: Trigger relevant messages based on user behavior.
- Abandoned cart: Remind after 2 hours.
- Course starting: Remind 15 minutes before.
-
A/B Testing: Compare the effectiveness of different messages.
// Randomly select a message template const templates = ['templateA', 'templateB'] const selectedTemplate = templates[Math.floor(Math.random() * templates.length)]
-
Link Tracking: Add UTM parameters.
pages/order/detail?id=123&utm_source=message&utm_medium=push
Handling Special Scenarios
Multi-Device Sync
Users may log in on multiple devices; message statuses need synchronization:
// Use cloud database to mark read status
const db = wx.cloud.database()
db.collection('user_messages').doc(messageId).update({
data: {
read: true,
readTime: new Date()
}
})
Internationalized Messages
Send content based on user language settings:
function getMessageTemplate(locale) {
const templates = {
'zh_CN': {
paymentSuccess: '支付成功'
},
'en_US': {
paymentSuccess: 'Payment successful'
}
}
return templates[locale] || templates['zh_CN']
}
Performance Optimization
Optimization strategies for large-scale message sending:
- Queue Processing: Use message queues to control sending rates.
- Batch Sending: Merge messages with the same template.
- Delayed Sending: Delay non-urgent messages.
// Use cloud functions for batch processing
const batchSize = 100
const messages = [...] // Array of pending messages
for (let i = 0; i < messages.length; i += batchSize) {
const batch = messages.slice(i, i + batchSize)
await processBatch(batch)
}
async function processBatch(batch) {
return Promise.all(batch.map(msg => sendMessage(msg)))
}
Compliance and User Experience
Mandatory rules to follow:
- No marketing content allowed.
- Important actions require confirmation.
- Provide clear unsubscribe options.
Example compliance check:
function validateMessageContent(content) {
const forbiddenWords = ['promotion', 'discount', 'limited-time']
return !forbiddenWords.some(word => content.includes(word))
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:小程序的支付功能集成
下一篇:小程序的审核与发布流程