WeChat Mini Program Update Tips

wechat; mini-program; update
987 words

In WeChat mini programs, we often encounter this requirement: when users open the mini program, if there's a new version, prompt them to update.

If we don't actively prompt users to update, they might continue using the old version, causing issues. So we need a mechanism to actively prompt users to update, letting them know there's a new version, and then they can update themselves. In fact, only when users "actively" update can we ensure they're using the latest version. We're just providing a prompt to let users know there's a new version.

First, Check the Official Documentation

WeChat mini programs should provide relevant APIs to implement this functionality, so let's check the official documentation. Mini Program Runtime / Update Mechanism

It provides "synchronous update on startup" and "asynchronous update on startup". Although both happen on startup, "synchronous update on startup" cannot be controlled by developers, while "asynchronous update on startup" can be controlled by developers. So we choose "asynchronous update on startup".

Implementation

How to Detect if There's a New Version?

For "asynchronous update on startup", the official provides an API: wx.getUpdateManager, and a demo:

const updateManager = wx.getUpdateManager()

updateManager.onCheckForUpdate(function (res) {
  // Callback after requesting new version information
  console.log(res.hasUpdate)
})

updateManager.onUpdateReady(function () {
  wx.showModal({
    title: 'Update Prompt',
    content: 'New version is ready. Restart the app?',
    success(res) {
      if (res.confirm) {
        // New version has been downloaded, call applyUpdate to apply and restart
        updateManager.applyUpdate()
      }
    }
  })
})

updateManager.onUpdateFailed(function () {
  // New version download failed
})

This demo shows how to use wx.getUpdateManager to implement update prompts. We can see that when there's a new version, a modal appears asking users if they want to update.

But honestly, this demo is a bit simplistic. We can improve it a bit.

For example, wx.getUpdateManager is only supported from base library version 1.9.90, so we need to check if the user's base library version supports this API first:

  1. Use wx.canIUse to check if wx.getUpdateManager is supported.

    • If supported, use wx.getUpdateManager to implement update prompts.
    • If not supported, use wx.showModal to prompt users to update their WeChat client version.
    // Check if WeChat version is compatible with mini program update mechanism API
    if (!wx.canIUse('getUpdateManager')) {
      // Cannot use wx.getUpdateManager, prompt user to upgrade WeChat
      wx.showModal({
        title: 'Friendly Reminder',
        content: 'Current WeChat version is too old and cannot use this feature. Please upgrade to the latest WeChat version and try again.',
      })
      return
    }
    // Support wx.getUpdateManager, try update operation
    // Get the global unique version update manager through wx.getUpdateManager
    const updateManager = wx.getUpdateManager()
  2. The updateManager object has multiple methods:

    • updateManager.applyUpdate: Force the mini program to restart and use the new version. Call after the new version download is complete (i.e., after receiving the onUpdateReady callback).
    • updateManager.onCheckForUpdate: Listen for the result of checking for updates from WeChat backend. WeChat automatically checks for updates every time the mini program starts (including hot start), no need for developers to trigger manually.
    • updateManager.onUpdateReady: Listen for mini program new version available event. Listen for mini program version update event. The client automatically triggers download (no need for developer to trigger), and calls the callback after successful download.
    • updateManager.onUpdateFailed: Listen for mini program update failure event. Mini program has a new version, client automatically triggers download (no need for developer to trigger), and calls the callback after download failure (possibly due to network issues, etc.).

Based on the above methods, we can improve the demo:

/**
 * Check WeChat mini program version update
 * Whether it's the latest version, whether it needs to download and update
 */
export const checkWeChatMiniProgramVersionUpdate = () => {
  // Check if WeChat version is compatible with mini program update mechanism API
  if (!wx.canIUse('getUpdateManager')) {
    wx.showModal({
      title: 'Friendly Reminder',
      content: 'Current WeChat version is too old and cannot use this feature. Please upgrade to the latest WeChat version and try again.',
    })
    return
  }

  const updateManager = wx.getUpdateManager()

  // Check version update
  updateManager.onCheckForUpdate(res => {
    if (!res.hasUpdate) return

    updateManager.onUpdateReady(() => {
      wx.showModal({
        title: 'Friendly Reminder',
        content: 'New version found. Restart the mini program?',
        showCancel: false, // Don't show cancel button, force update
        success: res => {
          if (res.confirm) {
            // New version has been downloaded, call applyUpdate to apply and restart
            updateManager.applyUpdate()
          }
        },
      })
    })

    updateManager.onUpdateFailed(() => {
      // New version download failed
      wx.showModal({
        title: 'New Version Available',
        content: 'Please delete the mini program and search for it again to enter',
      })
    })
  })
}

How to Call It?

Now that we've written the detection method, where should we call it?

I think it should be checked on any page, so I chose to call it in app.js:

According to the WeChat mini program lifecycle, we can call it in the onLaunch lifecycle. But since I'm using Taro with React Functional Component, only the useDidShow lifecycle is available. For details, see: Entry Component | Taro Documentation

// Taro additional hooks need to be imported from '@tarojs/taro'
import { useDidShow } from '@tarojs/taro'

// Check WeChat mini program version update
import { checkWeChatMiniProgramVersionUpdate } from './utils/wechat'

const App = () => {
  useDidShow(() => {
    checkWeChatMiniProgramVersionUpdate()
  })

  return <View className='app' />
}

How to Verify?

We can first use the WeChat Developer Tools to simulate version updates through the [Add Compilation Mode] feature.

Because in the add compilation mode, there's a compilation settings option with an optional item: [Simulate update on next compilation (requires base library 1.9.90 or above)]. After selecting this option, you can also choose whether to simulate [success status] or [failure status]. The default is [success status]. After clicking [OK] (confirming to add/modify the compilation mode), it will automatically recompile. After entering the mini program, wait a few seconds and you'll see the effect.

The experience version of mini programs doesn't have an actual version concept, so on real devices, we can only test the update detection feature on the official version.

Summary

This way we've implemented the update prompt feature for WeChat mini programs. When users open the mini program, if there's a new version, a modal will appear asking if they want to update. (It's actually recommended to force updates, as users not updating might cause issues...)