WeChat Mini Program APIs: A Comprehensive Guide

Making HTTP Requests

Fetching HTML Content

Here's how to retrieve HTML content from a remote server:

<button type="primary" bindtap="fetchHtmlData">Fetch Data</button>
<textarea value='{{htmlContent}}' auto-height maxlength='0'></textarea>
Page({
  data: {
    htmlContent: ""
  },
  fetchHtmlData: function() {
    var self = this;
    wx.request({
      url: 'https://www.example.com',
      data: {},
      header: {'Content-Type': 'application/json'},
      success: function(response) {
        console.log(response);
        self.setData({
          htmlContent: response.data
        });
      }
    });
  }
})

Querying address information by postal code:

<view>Postal Code:</view>
<input type="text" bindinput="handleInput" placeholder='6-digit postal code'/>
<button type="primary" bindtap="lookupAddress">Search</button>
<block wx:for="{{addressData}}">
    <block wx:for="{{item}}">
        <text>{{item}}</text>
    </block>
</block>
Page({
  data: {
    postalCode: "",
    addressData: [],
    errorMessage: "",
    errorCode: -1
  },
  handleInput: function(event) {
    this.setData({
      postalCode: event.detail.value
    });
    console.log(event.detail.value);
  },
  lookupAddress: function() {
    var postalCode = this.data.postalCode;
    if(postalCode != null && postalCode != "") {
      var self = this;
      wx.showToast({
        title: 'Searching, please wait...',
        icon: 'loading',
        duration: 10000
      });
      wx.request({
        url: 'https://api.example.com/postcode/query',
        data: {
          'postcode': postalCode,
          'key': '0ff9bfccdf147476e067de994eb5496'
        },
        header: {
          'Content-Type': 'application/json',
        },
        method: 'GET',
        success: function(response) {
          wx.hideToast();
          if(response.data.errorCode == 0) {
            console.log(response);
            self.setData({
              errorMessage: "",
              errorCode: response.data.errorCode,
              addressData: response.data.result.list
            });
          } else {
            self.setData({
              errorMessage: response.data.reason || response.data.reason,
              errorCode: response.data.errorCode
            });
          }
        }
      });
    }
  }
})

File Upload

Example of uploading an image to a server and displaying it:

<button type="primary" bindtap="uploadImage">Upload Image</button>
<image src="{{imageUrl}}" mode="widthFix"/>
Page({
  data: {
    imageUrl: null,
  },
  uploadImage: function() {
    var self = this;
    wx.chooseImage({
      success: function(response) {
        var tempFilePaths = response.tempFilePaths;
        uploadFile(self, tempFilePaths);
      }
    });
    
    function uploadFile(page, paths) {
      wx.showToast({
        icon: "loading",
        title: "Uploading"
      });
      
      wx.uploadFile({
        url: "https://your-server.com/upload",
        filePath: paths[0],
        success: function(response) {
          console.log(response);
          if(response.statusCode != 200) {
            wx.showModal({
              title: 'Notification',
              content: 'Upload failed',
              showCancel: false
            });
            return;
          }
          
          var data = response.data;
          page.setData({
            imageUrl: paths[0]
          });
        },
        fail: function(error) {
          console.log(error);
          wx.showModal({
            title: 'Notification',
            content: 'Upload failed',
            showCancel: false
          });
        },
        complete: function() {
          wx.hideToast();
        }
      });
    }
  }
})

Multimedia APIs

Image APIs

wx.chooseImage({
  count: 2,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success: function(response) {
    var tempFilePaths = response.tempFilePaths;
    var tempFiles = response.tempFiles;
    console.log(tempFilePaths);
    console.log(tempFiles);
  }
})
Image Preview
wx.previewImage({
  current: "https://example.com/image1.png",
  urls: [
    "https://example.com/image1.png",
    "https://example.com/image2.png",
    "https://example.com/image3.png"
  ]
})
Get Image Information
wx.chooseImage({
  success: function(response) {
    wx.getImageInfo({
      src: response.tempFilePaths[0],
      success: function(info) {
        console.log(info.width);
        console.log(info.height);
      }
    });
  }
})
Save Image to Album
wx.chooseImage({
  success: function(response) {
    wx.saveImageToPhotosAlbum({
      filePath: response.tempFilePaths[0],
      success: function(result) {
        console.log(result);
      }
    });
  }
})

Audio Recording APIs

Start Recording

The wx.startRecord interface is used to begin recording audio.

Stop Recording

The wx.stopRecord interface is used to actively stop recording.

wx.startRecord({
  success: function(response) {
    var tempFilePath = response.tempFilePath;
  },
  fail: function(response) {
    // Handle failure
  }
});

setTimeout(function() {
  wx.stopRecord();
}, 10000);

Audio Playback Control APIs

Play Audio

The wx.playVoice interface is used to start playing audio. Only one audio file can be played at a time.

Pause Playback

The wx.pauseVoice interface is used to pause the currently playing audio. When wx.playVoice is called again for the same file, it will resume from where it was paused. To start from the beginning, you need to call wx.stopVoice first.

wx.startRecord({
  success: function(response) {
    var tempFilePath = response.tempFilePath;
    wx.playVoice({
      filePath: tempFilePath
    });
    
    setTimeout(function() {
      wx.pauseVoice();
    }, 5000);
  }
})

File APIs

Files downloaded from the network or recorded audio are temporarily saved. For persistent storage, you need to use the File APIs. The File API provides capabilities to open, save, delete, and perform other operations on local files, including the following 5 API interfaces:

  1. wx.saveFile(Object) - Saves files to local storage.
  2. wx.getSavedFileList(Object) - Gets the list of saved files.
  3. wx.getSavedFileInfo(Object) - Gets information about a saved file.
  4. wx.removeSavedFile(Object) - Deletes a saved file.
  5. wx.openDocument(Object) - Opens a document in a new page, supporting formats: doc, xls, ppt, pdf, docx, xlsx, pptx.

Save Files

saveImage: function() {
  wx.chooseImage({
    count: 1, // Default is 9
    sizeType: ['original', 'compressed'], // Specify original or compressed images
    sourceType: ['album', 'camera'], // Specify source as album or camera
    success: function(response) {
      var tempFilePath = response.tempFilePaths[0];
      wx.saveFile({
        tempFilePath: tempFilePath,
        success: function(res) {
          var savedFilePath = res.savedFilePath;
          console.log(savedFilePath);
        }
      });
    }
  });
}

Get Local File List

wx.getSavedFileList({
  success: function(response) {
    self.setData({
      fileList: response.fileList
    });
  }
})

Get Local File Information

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success: function(response) {
    var tempFilePath = response.tempFilePaths[0];
    wx.saveFile({
      tempFilePath: tempFilePath,
      success: function(res) {
        var savedFilePath = res.savedFilePath;
        wx.getSavedFileInfo({
          filePath: savedFilePath,
          success: function(info) {
            console.log(info.size);
          }
        });
      }
    });
  }
})

Delete Local Files

wx.getSavedFileList({
  success: function(response) {
    if(response.fileList.length > 0) {
      wx.removeSavedFile({
        filePath: response.fileList[0].filePath,
        complete: function(res) {
          console.log(res);
        }
      });
    }
  }
})

Open Documents

wx.downloadFile({
  url: "https://example.com/document.pdf",
  success: function(response) {
    var tempFilePath = response.tempFilePath;
    wx.openDocument({
      filePath: tempFilePath,
      success: function(res) {
        console.log("Document opened successfully");
      }
    });
  }
})

Storage APIs

Get Data

wx.getStorage

The wx.getStorage interface asynchronously retrieves the content corresponding to the specified key from local cache.

wx.getStorage({
  key: 'username',
  success: function(response) {
    console.log(response.data);
  }
})
wx.getStorageSync(key)

The wx.getStorageSync method synchronously retrieves the content corresponding to the specified key from local cache.

try {
  var value = wx.getStorageSync('age');
  if(value) {
    console.log("Retrieved successfully: " + value);
  }
} catch(error) {
  console.log("Retrieval failed");
}

Delete Data

wx.removeStorage

The wx.removeStorage interface asynchronously removes the specified key from local cache.

wx.removeStorage({
  key: 'username',
  success: function(response) {
    console.log("Deletion successful");
  },
  fail: function() {
    console.log("Deletion failed");
  }
})
wx.removeStorageSync

The wx.removeStorageSync method synchronously deletes the content corresponding to the specified key from local cache.

try {
  wx.removeStorageSync('username');
} catch(error) {
  // Handle error
}

Clear Data

wx.clearStorage()

The wx.clearStorage() interface asynchronously clears all local cache data.

wx.getStorage({
  key: 'username',
  success: function(response) {
    wx.clearStorage();
  }
})
wx.clearStorageSync()

Used to synchronously clear all local data cache.

try {
  wx.clearStorageSync();
} catch(error) {
  // Handle error
}

Location APIs

Get Location Information

The wx.getLocation interface is used to get the current user's geographical loaction and speed. It requires the user to enable location services. When the user leaves the mini program, the current location cannot be obtained. When the user clicks "Show on Top in Chat", location information can be obtained.

wx.getLocation({
  type: 'wgs84',
  success: function(response) {
    console.log("Longitude: " + response.longitude);
    console.log("Latitude: " + response.latitude);
  }
})
<view class="container">
  <view class="button-container">
    <button bindtap="getLocation">Get Location Information</button>
  </view>
</view>

Choose Location

The wx.chooseLocation interface is used to select a location on an open map. After the user selects a location, it returns the current location's name, address, and coordinate information.

Page({
  data: {
    markers: [],
    polyline: [],
    controls: []
  },
  onLoad: function() {
    wx.chooseLocation({
      success: function(response) {
        console.log(response);
        var newMarkers = [{
          iconPath: "../images/location-pin.png",
          id: 0,
          longitude: response.longitude,
          latitude: response.latitude,
          width: 50,
          height: 50
        }];
        this.setData({
          markers: newMarkers
        });
      }.bind(this)
    });
  },
  regionchange: function(event) {
    console.log(event.type);
  },
  markertap: function(event) {
    console.log(event.markerId);
  },
  controltap: function(event) {
    console.log(event.controlId);
  }
})
<map id="map"
  longitude="108.9200"
  latitude="34.1550"
  scale="14"
  controls="{{controls}}"
  bindcontroltap="controltap"
  markers="{{markers}}"
  bindmarkertap="markertap"
  polyline="{{polyline}}"
  bindregionchange="regionchange"
  show-location
  style="width: 100%; height: 300px;">
</map>

Display Location

The wx.openLocation interface is used to display location information in the built-in WeChat map.

Page({
  data: {
    locationInfo: {}
  },
  onLoad: function() {
    wx.getLocation({
      type: 'gcj02',
      success: function(response) {
        var latitude = response.latitude;
        var longitude = response.longitude;
        wx.openLocation({
          latitude: latitude,
          longitude: longitude,
          scale: 10,
          name: 'International Hotel',
          address: 'No. 300, Chang\'an District, Xi\'an'
        });
      }
    });
    
    wx.chooseLocation({
      success: function(response) {
        console.log(response);
        this.setData({
          locationInfo: response
        });
        wx.openLocation({
          latitude: response.latitude,
          longitude: response.longitude,
          name: response.name,
          address: response.address
        });
      }.bind(this)
    });
  },
  regionchange: function(event) {
    console.log(event.type);
  },
  markertap: function(event) {
    console.log(event.markerId);
  },
  controltap: function(event) {
    console.log(event.controlId);
  }
})

Device APIs

Get System Information

The wx.getSystemInfo and wx.getSystemInfoSync interfaces are used to asynchronously and synchronously get system information, respectively.

Page({
  onLoad: function() {
    wx.getSystemInfo({
      success: function(response) {
        console.log("Device Model: " + response.model);
        console.log("Device Pixel Ratio: " + response.pixelRatio);
        console.log("Window Width: " + response.windowWidth);
        console.log("Window Height: " + response.windowHeight);
        console.log("WeChat Version: " + response.version);
        console.log("Operating System: " + response.system);
        console.log("Client Platform: " + response.platform);
      }
    });
  }
})

Network Status

Get Network Type

wx.getNetworkType is used to get the network type.

wx.getNetworkType({
  success: function(response) {
    console.log(response.networkType);
  }
})
Monitor Network Status Changes

wx.onNetworkStatusChange(CallBack) is used to listen for network status changes. When the network status changes, it returns the current network type and whether there is a network connection.

wx.onNetworkStatusChange(function(response) {
  console.log("Network Connected: " + response.isConnected);
  console.log("Network Type: " + response.networkType);
})

Make Phone Calls

The wx.makePhoneCall interface is used to initiate a phone call.

wx.makePhoneCall({
  phoneNumber: '1234567890'
})

Scan QR Codes

The wx.scanCode interface is used to call the client's scanning interface. After successful scanning, it returns the corresponding content.

wx.scanCode({
  success: (response) => {
    console.log(response.result);
    console.log(response.scanType);
    console.log(response.charSet);
    console.log(response.path);
  }
});

wx.scanCode({
  onlyFromCamera: true,
  success: (response) => {
    console.log(response);
  }
})

Tags: WeChat Mini Program API network multimedia File System

Posted on Tue, 01 Sep 2026 16:40:43 +0000 by kasitzboym