API for wechat development

Keywords: Mini Program wechat


  1. wx.env: environment variable, directory path in file system (local path)
  2. wx.canIUse(string schema): judge whether the API, callback, parameters, components, etc. of the applet are available in the current version
  • Parameters: call using ${API}. ${method}. ${parameter}. ${option} or ${component}.${attribute}.${option}
  • ${API} represents API name ${method} represents calling method. Valid values are return, success, object, callback ${param} represents parameter or return value ${option} represents optional value of parameter or attribute of return value ${component} represents component name ${attribute} represents component attribute ${option} represents optional value of component attribute
  • Return value: boolean
  1. wx.base64ToArrayBuffer(string base64): convert Base64 string to ArrayBuffer object
  • Parameter: Base64 string to convert to ArrayBuffer object
  • The ArrayBuffer object is used to represent a generic, fixed length raw binary data buffer. It is a byte array, which is often called "byte array" in other languages. You cannot directly manipulate the contents of ArrayBuffer, but through type array objects or DataView objects. They will represent the data in the buffer in specific formats and read and write the contents of the buffer through these formats.


  • Base64 is one of the most common encoding methods for transmitting 8Bit byte code on the network. Base64 is a method to represent binary data based on 64 printable characters. You can view RFC2045 ~ RFC2049, which has the detailed specification of MIME. Base64 encoding is a process from binary to character, which can be used to transfer long identification information in HTTP environment. Base64 encoding is unreadable and can only be read after decoding.


  • Return value: ArrayBuffer object
const base64 = 'CxYh'
const arrayBuffer = wx.base64ToArrayBuffer(base64)
  1. wx.arrayBufferToBase64(ArrayBuffer arrayBuffer): convert ArrayBuffer object to Base64 string
  • Parameter: ArrayBuffer arrayBuffer
  • Return value: Base64 string
const arrayBuffer = new Uint8Array([11, 22, 33])
const base64 = wx.arrayBufferToBase64(arrayBuffer)


  1. wx.getSystemInfo(Object object): get system information. Due to historical reasons, wx.getSystemInfo is an asynchronous call format, but it is returned synchronously. It is necessary to obtain system information asynchronously. Please use wx.getSystemInfoAsync
  • Sync version: wx.getSystemInfoSync()
  1. wx.getSystemInfoAsync(Object object): get system information asynchronously. Certain wechat client version support is required. On unsupported clients, synchronous implementation will be used to return.

to update

  1. wx.updateWeChatApp(Object object): update the client version. When it is judged that the client version of the user applet is too low, you can use this interface to jump to the update wechat page
  2. wx.getUpdateManager(): get the globally unique version update manager, which is used to manage applet updates
  • Return value: update manager object
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
  // Callback after requesting new version information
updateManager.onUpdateReady(function () {
    title: 'Update tips',
    content: 'The new version is ready. Do you want to restart the application?',
    success: function (res) {
      if (res.confirm) {
        // The new version has been downloaded. Call applyUpdate to apply the new version and restart
updateManager.onUpdateFailed(function () {
  // Download of new version failed
Force the applet to restart and use the new version. After the download of the new version of the applet is completed (i.e. received) onUpdateReady Callback) call.
UpdateManager.onCheckForUpdate(function callback)
Listen for the event of requesting the wechat background to check the update result. Wechat automatically checks for updates when the applet is cold started without being triggered by the developer.
UpdateManager.onUpdateReady(function callback)
The listening applet has version update events. The client actively triggers the download (without triggering by the developer), and calls back after the download is successful
UpdateManager.onUpdateFailed(function callback)
Listen for applet update failure events. There is a new version of the applet. The client actively triggers the download (without the developer's triggering), and calls back after the download fails (possibly due to network reasons)

Applet lifecycle

  1. wx.getLaunchOptionsSync(): get the parameters when the applet starts, which is consistent with the callback parameters of App.onLaunch
  2. wx.getEnterOptionsSync(): get the parameters when the applet starts this time. If it is currently cold start, the return value is consistent with the callback parameter of App.onLaunch; If it is currently hot start, the return value is consistent with App.onShow

Applet application level events

  1. wx.onUnhandledRejection(function callback): listen for the unhandled Promise rejection event, which is consistent with the callback timing and parameters of App.onUnhandledRejection.
  • Parameter: callback function for unhandled Promise reject event
  • All unhandledrejections can be captured by this listener, but only those of Error type will trigger an alarm in the applet background
  1. wx.offUnhandledRejection(function callback): cancels listening for unprocessed Promise events
  • Parameter: callback function for unhandled Promise reject event
  1. wx.onThemeChange(function callback): listen for the system theme change event, which is consistent with the callback timing of App.onThemeChange.
  • Parameter: callback function for unhandled Promise reject event
  • This event is triggered only when "darkmode": true is configured globally
  1. wx.onPageNotFound(function callback): there is no event on the page to be opened by the listening applet. This event is consistent with the callback timing of App.onPageNotFound.
  • Parameter: the callback function of the event does not exist on the page to be opened by the applet
  • The developer can redirect the page in the callback, but it must be processed synchronously and asynchronously in the callback (for example, setTimeout is executed asynchronously) Invalid; if the developer does not call wx.onPageNotFound binding to listen and does not declare App.onPageNotFound, when the jump page does not exist, it will push the wechat client's native page without prompt page; if the callback redirects to another non-existent page, it will push the wechat client's native page without prompt page, and there will be no second callback
  1. wx.offPageNotFound(function callback): cancel listening. The page to be opened by the applet does not have an event

  2. wx.onError(function callback): listen for applet error events, such as script errors or API call errors. This event is consistent with the callback timing and parameters of App.onError

  • Parameter: callback function of applet error event (error message, including stack)
  1. Wx. Oferror (function callback): cancels listening for applet error events

  2. Wx.onaudiointeruptionend (function callback): listen for the audio interrupt end event. After receiving the onaudiointeruptionbegin event, all audio in the applet will pause. After receiving this event, it can be played successfully again

  • Parameter: callback function of audio interrupt end event
  1. wx.offAudioInterruptionEnd(function callback): cancels listening for audio interrupt end events

  2. Wx.onaudiointeruptionbegin (function callback): listen for the start event of audio interruption due to system occupation. This event will be triggered in the following scenarios, such as alarm clock, telephone, FaceTime call, wechat voice chat and wechat video chat. After this event is triggered, all audio in the applet will be suspended

  • Parameter: the callback function of the start event when the audio is interrupted because it is occupied by the system
  1. wx.offAudioInterruptionBegin(function callback): the start event of canceling listening for audio interruption because it is occupied by the system

  2. wx.onAppShow(function callback): listen for the applet's foreground cutting event, which is consistent with the callback parameters of App.onShow

  • Some versions will return undefined when there is no referrinfo. It is recommended to use options.referrinfo & & options.referrinfo.appid for judgment
  1. wx.offAppShow(function callback): cancels listening for applet foreground events

  2. wx.onAppHide(function callback): listen for the applet background cutting event, which is consistent with the callback timing of App.onHide.

  3. wx.offAppHide(function callback): cancels listening for applet background cutting events

Applet debugging

  1. wx.setEnableDebug(Object object): set whether to turn on the debugging switch. This switch can also take effect for the official version
  • Another way to open debugging in the official version is to open debugging in the development version or experience version, and then switch to the official version to see vConsole
// Open debug
  enableDebug: true

// Turn off debugging
  enableDebug: false
  1. wx.getRealtimeLogManager(): get the real-time log manager object
  • Developers can enter the applet side log query page from "development - > operation and maintenance center - > real-time log" in the applet management background, or enter the plug-in side log query page from "applet plug-in - > real-time log", and then view the log information printed by developers.
  • Return value: RealtimeLogManager
// Applet side
const logger = wx.getRealtimeLogManager()
logger.info({str: 'hello world'}, 'info log', 100, [1, 2, 3])
logger.error({str: 'hello world'}, 'error log', 100, [1, 2, 3])
logger.warn({str: 'hello world'}, 'warn log', 100, [1, 2, 3])

// On the plug-in side, the basic library is supported after version 2.16.0, and only the new format of key value is allowed to be reported
const logManager = wx.getRealtimeLogManager()
const logger = logManager.tag('plugin-log1')
logger.info('key1', 'value1')
logger.error('key2', {str: 'value2'})
logger.warn('key3', 'value3')
write info Log, which is not supported in plug-ins
write warn Log, which is not supported in plug-ins
write error Log, which is not supported in plug-ins
RealtimeLogManager.setFilterMsg(string msg)
Set filtering keywords, which are not supported in plug-ins
RealtimeLogManager.addFilterMsg(string msg)
Add filter keywords, which are not supported in plug-ins
  1. wx.getLogManager(Object object): get the log manager object
  • Return value: LogManager
  • Save up to 5M of log content. After 5M, the old log content will be deleted; For applets, users can upload the printed logs by using the open type = "feedback" of the button component; For small games, users can create buttons to upload and print logs by using wx.createFeedbackButton; Developers can view relevant print logs through the "feedback management" Page of the menu on the left of the applet management background; By default, the basic library will write the life cycle functions of App and Page and the function calls under the Wx namespace to the log
write debug journal
write info journal
write log journal
write warn journal
  1. RealtimeTagLogManager: the real-time log manager instance with a given tag can be obtained through the RealtimeLogManager.tag interface. At present, it is only supported in plug-ins
  • The function of RealtimeTagLogManager is similar to that of RealtimeLogManager, but in order to make the output real-time log easier to analyze, it has more strict format requirements; When using RealtimeTagLogManager, tags need to be passed in. The logs output by calling this instance will be collected under the corresponding tags. At the same time, the logs of this instance only support key value format for output
RealtimeTagLogManager.info(string key, Object|Array.<any>|number|string value)
write info journal
RealtimeTagLogManager.warn(string key, Object|Array.<any>|number|string value)
write warn journal
RealtimeTagLogManager.error(string key, Object|Array.<any>|number|string value)
write error journal
RealtimeTagLogManager.setFilterMsg(string msg)
Set filter keywords
RealtimeTagLogManager.addFilterMsg(string msg)
Add filter keyword

Applet routing

  1. wx.switchTab(Object object): jump to the tabbar page and close all other non tabbar pages
  2. wx.reLaunch(Object object): close all pages and open a page in the application
  3. wx.redirectTo(Object object): close the current page and jump to a page in the application. However, it is not allowed to jump to the tabbar page
  4. wx.navigateTo(Object object): keep the current page and jump to a page in the application. But you can't jump to the tabbar page. Use wx.navigateBack to return to the original page. The page stack in the applet can be up to ten layers
  • Parameters:
    url, the path (code package path) of the non tabBar page in the application to jump to. The path can be followed by parameters. Use between parameter and path? Separate, parameter keys and parameter values are connected by =, and different parameters are separated by &; For ex amp le, 'path? Key = value & key2 = Value2';
    events, object and inter page communication interface are used to listen for the data sent by the open page to the current page. The basic library 2.7.3 starts to support (the successful callback function parameter is eventchannel and the type is eventchannel, which is used to open the page for communication)
  url: 'test?id=1',
  events: {
    // Add a listener for the specified event to get the data transferred from the open page to the current page
    acceptDataFromOpenedPage: function(data) {
    someEvent: function(data) {
  success: function(res) {
    // Transfer data to the opened page through eventChannel
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
  onLoad: function(option){
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
    eventChannel.emit('someEvent', {data: 'test'});
    // Listen to the acceptDataFromOpenerPage event to obtain the data transmitted from the previous page to the current page through the eventChannel
    eventChannel.on('acceptDataFromOpenerPage', function(data) {
EventChannel.emit(string eventName, any args)
Trigger an event
EventChannel.on(string eventName, EventCallback fn)
Continuously listening for an event
EventChannel.once(string eventName, EventCallback fn)
Listen to an event once, and it will become invalid after triggering
EventChannel.off(string eventName, EventCallback fn)
Cancel listening for an event. When the second parameter is given, only the given listening functions are cancelled, otherwise all listening functions are cancelled
  1. Wx. Navigateback (object): close the current page and return to the previous page or multi-level page. You can get the current page stack through getCurrentPages and decide how many layers to return
  • Parameter: Delta, number type, the default value is 1. The number of returned pages. If delta is greater than the number of existing pages, it will return to the first page
// Note: when calling navigateTo jump, the page calling this method will be added to the stack, while the redirectTo method will not
// This is page A
  url: 'B?id=1'
// This is page B
  url: 'C?id=1'
// navigateBack in page C will return to page A
  delta: 2

Applet interface

  1. wx.showActionSheet(Object object): displays the action menu
  2. wx.enableAlertBeforeUnload(Object object): open the applet page and return to the query dialog box
  3. Wx. Disablealert beforeunload (object object): close the applet page and return to the query dialog box
  4. wx.showNavigationBarLoading(Object object): displays the navigation bar loading animation on the current page
  5. Wx. Setnavigationbartitle (object): dynamically set the title of the current page
  6. wx.setNavigationBarColor(Object object): sets the color of the page navigation bar
  7. wx.showTabBarRedDot(Object object): displays the red dot in the upper right corner of a tabBar item
  8. wx.setTabBarStyle(Object object): dynamically set the overall style of tabBar
  color: '#FF0000',
  selectedColor: '#00FF00',
  backgroundColor: '#0000FF',
  borderStyle: 'white'
  1. wx.setTabBarItem(Object object): dynamically set the content of a tabBar item. Since 2.7.0, images support temporary files and network files
  index: 0,
  text: 'text',
  iconPath: '/path/to/iconPath',
  selectedIconPath: '/path/to/selectedIconPath'
  1. wx.setTabBarBadge(Object object): add text to the upper right corner of an item in tabBar
  index: 0,
  text: '1'
  1. Wx. Remove tabbarbadge (object object): removes the text in the upper right corner of an item in the tabBar
  2. wx.stopPullDownRefresh(Object object): stop the pull-down refresh of the current page
  3. wx.startPullDownRefresh(Object object): start pull-down refresh. Trigger the drop-down refresh animation after calling, and the effect is consistent with the user's manual drop-down refresh
  4. wx.pageScrollTo(Object object): scrolls the page to the target position. It supports positioning by selector and scrolling distance
  • Parameters: selector, string, selector
selector be similar to CSS , but only the following syntax is supported:
ID Selector:#the-id
class Selector (multiple can be specified consecutively):.a-class.another-class
 Child element selector:.the-parent > .the-child
 Descendant selector:.the-ancestor .the-descendant
 Descendants selector across custom components:.the-ancestor >>> .the-descendant
 Union of multiple selectors:#a-node, .some-other-nodes
  scrollTop: 0,
  duration: 300
  1. ScrollViewContext: enhance the ScrollView instance, which can be obtained through the NodesRef.node method of wx.createSelectorQuery. It takes effect only after the enhanced attribute is enabled on the scroll view component
boolean scrollEnabled
 Rolling switch
boolean bounces
 Set rolling boundary elasticity (Only in iOS Effective under)
boolean showScrollbar
 Sets whether the scroll bar is displayed
boolean pagingEnabled
 Paging slide switch
boolean fastDeceleration
 Set the roll deceleration rate
boolean decelerationDisabled
 Cancel rolling inertia (Only in iOS Effective under)

ScrollViewContext.scrollTo(Object object)
Scroll to the specified position
ScrollViewContext.scrollIntoView(string selector)
Scroll to the specified position
  .exec((res) => {
    const scrollView = res[0].node;
    scrollView.scrollEnabled = false;
  1. wx.setTopBarText(Object object): dynamically set the text content of the top bar. Only when the current applet is set to the top can it take effect. If the current applet is not set to the top, it can be called successfully, but it will not take effect immediately. The set text content can be changed only after the user sets the applet to the top; After successful calling, this interface can be called again at an interval of 5s. If this interface is called again within 5s, it will call back fail, errMsg: "setTopBarText: fail invoke too frequently"
  2. wx.setWindowSize(Object object): set the window size. This interface is only applicable to PC platform. Please refer to the guide for details
  3. wx.onWindowResize(function callback): listen for window size change events
  • Parameter: callback function for window size change event
  1. wx.offWindowResize(function callback): cancels listening for window size change events

Applet network

  1. wx.request(Object object): initiates an HTTPS network request
  • Parameters:
    |url | string | developer server interface address
    |data | string/object/ArrayBuffer | requested parameters
    |header | Object | set the header of the request. Referer s cannot be set in the header.
    Content type defaults to application/json
    |timeout | number | timeout, in milliseconds
    |method | string | default GET | HTTP request method
    | | |
  url: 'example.php', //This is an example only and is not a real interface address
  data: {
    x: '',
    y: ''
  header: {
    'content-type': 'application/json' // Default value
  success (res) {
  1. wx.downloadFile(Object object): download file resources locally. The client directly initiates an HTTPS GET request and returns the local temporary path (local path) of the file. The maximum file allowed for a single download is 200MB
    -object.success callback function parameters:
  • tempFilePath, string, temporary file path (local path). If no filePath is passed in, the file storage path will be returned, and the downloaded file will be stored in a temporary file
  • filePath, string, user file path (local path). When filePath is passed in, it will be returned, which is consistent with the passed in filePath
  • statusCode, number, HTTP status code returned by the developer server
  • profile, Object, some debugging information during network request
  • Return value: DownloadTask, an object that can listen to download progress change events and cancel downloading
  url: 'https://example.com/audio/123 ', / / examples only, not real resources
  success (res) {
    // As long as the server has response data, it will write the response content to the file and enter the success callback. The business needs to judge whether the desired content has been downloaded
    if (res.statusCode === 200) {
        filePath: res.tempFilePath
Interrupt download task
DownloadTask.onProgressUpdate(function callback)
Listening for download progress change events
DownloadTask.offProgressUpdate(function callback)
Event triggered after canceling listening for download progress change
DownloadTask.onHeadersReceived(function callback)
monitor HTTP Response Header event. Will be earlier than the request completion event
DownloadTask.offHeadersReceived(function callback)
Cancel listening HTTP Response Header event
const downloadTask = wx.downloadFile({
  url: 'http://example.com/audio/123 ', / / examples only, not real resources
  success (res) {
      filePath: res.tempFilePath

downloadTask.onProgressUpdate((res) => {
  console.log('Download progress', res.progress)
  console.log('Length of downloaded data', res.totalBytesWritten)
  console.log('Total length of data expected to be downloaded', res.totalBytesExpectedToWrite)

downloadTask.abort() // Cancel download task
  1. wx.uploadFile(Object object): uploads local resources to the server. The client initiates an HTTPS POST request, where the content type is multipart / form data
  • object.success callback function parameters:
  • Data, string, data returned by the developer server
  • statusCode, number, HTTP status code returned by the developer server
  • Return value: UploadTask, an object that can listen to the event of upload progress change and cancel upload
  success (res) {
    const tempFilePaths = res.tempFilePaths
      url: 'https://example.weixin.qq.com/upload ', / / it is only an example, not a real interface address
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        'user': 'test'
      success (res){
        const data = res.data
        //do something
Interrupt upload task
UploadTask.onProgressUpdate(function callback)
Listening for upload progress change events
UploadTask.offProgressUpdate(function callback)
Cancel listening for upload progress change events
UploadTask.onHeadersReceived(function callback)
monitor HTTP Response Header event. Will be earlier than the request completion event
UploadTask.offHeadersReceived(function callback)
Cancel listening HTTP Response Header event
const uploadTask = wx.uploadFile({
  url: 'http://example.weixin.qq.com/upload ', / / it is only an example, not a real interface address
  filePath: tempFilePaths[0],
  name: 'file',
    'user': 'test'
  success (res){
    const data = res.data
    //do something

uploadTask.onProgressUpdate((res) => {
  console.log('Upload progress', res.progress)
  console.log('Length of uploaded data', res.totalBytesSent)
  console.log('Total length of data expected to be uploaded', res.totalBytesExpectedToSend)

uploadTask.abort() // Cancel upload task

Applet payment

  1. wx.requestPayment(Object object): initiate wechat payment. Before calling, you need to apply for access to wechat payment at the wechat public platform - function - wechat payment portal of the applet; If cloud development is used, the parameters required for wx.requestPayment can be obtained without authentication through the unified ordering interface of cloud development wechat payment, and can safely call the wechat payment server interface without certificate and signature, and receive asynchronous payment result callback. See cloud development wechat payment for details
  • Parameters:
  • timeStamp, string, required, timeStamp, the number of seconds since 00:00:00 on January 1, 1970, that is, the current time
  • nonceStr, string, required, random string, length less than 32 characters
  • package, string, required; prepay returned by the unified ordering interface_ ID parameter value, submission format, such as: prepay_id=***
  • signType, string, MD5, signature algorithm, which shall be consistent with the value when placing an order in the background
  • paySign, string, required, signature, see wechat payment document for details
  timeStamp: '',
  nonceStr: '',
  package: '',
  signType: 'MD5',
  paySign: '',
  success (res) { },
  fail (res) { }
  • If the server uses cloud development, it can obtain all the above parameters without authentication through the unified ordering interface of cloud development wechat payment
// Cloud function code
const cloud = require('wx-server-sdk')

exports.main = async (event, context) => {
  const res = await cloud.cloudPay.unifiedOrder({
    "body" : "Xiaoqiu TIT store-supermarket",
    "outTradeNo" : "1217752501201407033233368018",
    "spbillCreateIp" : "",
    "subMchId" : "1900009231",
    "totalFee" : 1,
    "envId": "test-f0b102",
    "functionName": "pay_cb"
  return res

// Applet code
  name: 'Function name',
  data: {
    // ...
  success: res => {
    const payment = res.result.payment
      success (res) {
        console.log('pay success', res)
      fail (err) {
        console.error('pay fail', err)
  fail: console.error,
  1. wx.requestOrderPayment(Object args): create a custom version transaction component order and initiate payment. Only the applet connected to the customized transaction component needs to be used. Ordinary applets can directly use wx.requestPayment
  • After accessing the customized transaction component, if you want to initiate wechat payment, please query the scenarios to be verified first. In scenarios requiring verification, you must use this interface when initiating wechat payment. You need to pass in the relevant order information for verification as required. After the verification is passed, the user can complete the payment of the current order. In non verification scenarios, you can choose to pass in the order information or not according to the merchant's requirements
// Except orderInfo, other fields are consistent with wx.requestPayment
  orderInfo: {},
  timeStamp: '',
  nonceStr: '',
  package: '',
  signType: 'MD5',
  paySign: '',
  success (res) { },
  fail (res) { }

Applet picture

  1. wx.saveImageToPhotosAlbum(Object object): save pictures to the system album
  2. wx.previewMedia(Object object): preview pictures and videos
  • Parameters:
  • sources, array / object, required, list of resources to preview
  • current, number, default 0, currently displayed resource serial number
  • showmenu, boolean, true by default, whether to display the long press menu
  1. wx.previewImage(Object object): preview the picture in full screen in a new page. During the preview process, users can save pictures, send them to friends, etc
  2. wx.getImageInfo(Object object): get image information. The download domain name must be configured before the network picture can take effect
  src: 'images/a.jpg',
  success (res) {

  success (res) {
      src: res.tempFilePaths[0],
      success (res) {
  1. wx.compressImage(Object object): compression image interface, optional compression quality
  • Parameters:
  • src, string, required, image path, image path, local path and code package path are supported
  • Quality, number, default 80, compression quality, range 0-100. The smaller the value, the lower the quality and the higher the compression rate (only valid for jpg)
  src: '', // Picture path
  quality: 80 // compression quality
  1. wx.chooseMessageFile(Object object): select a file from the client session
  • Parameters:
  • count, number, required. The maximum number of files that can be selected is 0-100
  • Type, string, default all, type of selected file
  • Extension, Array/string, filtered by file extension name, only valid when type==file. Each item cannot be an empty string. The default is no filtering.

Posted by timmy2 on Wed, 13 Oct 2021 16:35:07 -0700