阿里云主机折上折
  • 微信号
Current Site:Index > Push notifications and messages for mini-programs

Push notifications and messages for mini-programs

Author:Chuan Chen 阅读数:62222人阅读 分类: 微信小程序

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:

  1. Template Messages (gradually being replaced by subscription messages)
  2. Subscription Messages (long-term and one-time subscriptions)
  3. Customer Service Messages
  4. 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:

  1. Obtain a template ID.
  2. Frontend calls wx.requestSubscribeMessage.
  3. 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:

  1. One-time subscription messages are valid for 7 days.
  2. Each user can receive no more than 3 messages per day for the same template.
  3. 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:

  1. Concise and Clear: Highlight key information upfront.
  2. Action-Oriented: Include clear instructions.
  3. 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:

  1. Message delivery success rate.
  2. User click-through rate.
  3. Subscription rejection rate.
  4. 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

  1. Contextual Pushes: Trigger relevant messages based on user behavior.

    • Abandoned cart: Remind after 2 hours.
    • Course starting: Remind 15 minutes before.
  2. 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)]
    
  3. 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:

  1. Queue Processing: Use message queues to control sending rates.
  2. Batch Sending: Merge messages with the same template.
  3. 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:

  1. No marketing content allowed.
  2. Important actions require confirmation.
  3. 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

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.