Working with WeChat Mini Program APIs
Network APIs
WeChat Mini Programs inetract with backend servers to fetch or submit data using built-in or third-party APIs. The primary method for network communication is wx.request().
Making HTTP Requests
The following example demonstrates fetching HTML content from Baidu:
// page.js
Page({
data: { content: '' },
fetchBaidu() {
wx.request({
url: 'https://www.baidu.com',
header: { 'Content-Type': 'application/json' },
success: (res) => {
this.setData({ content: res.data });
}
});
}
});
<!-- page.wxml -->
<button bindtap="fetchBaidu">Fetch HTML</button>
<textarea value="{{content}}" auto-height />
Another example uses a POST request to query address details by postal code via Juhe API:
Page({
data: { code: '', locations: [], error: '' },
onInput(e) {
this.setData({ code: e.detail.value });
},
searchAddress() {
const { code } = this.data;
if (!code) return;
wx.showToast({ title: 'Searching...', icon: 'loading', duration: 10000 });
wx.request({
url: 'https://v.juhe.cn/postcode/query',
method: 'POST',
data: {
postcode: code,
key: '0ff9bfccdf147476e067de994eb5496e'
},
header: { 'Content-Type': 'application/x-www-form-urlencoded' },
success: (res) => {
wx.hideToast();
if (res.data.error_code === 0) {
this.setData({ locations: res.data.result.list, error: '' });
} else {
this.setData({ error: res.data.reason || 'Unknown error' });
}
}
});
}
});
<view>Postal Code:</view>
<input bindinput="onInput" placeholder="6-digit code" />
<button bindtap="searchAddress">Search</button>
<block wx:for="{{locations}}">
<block wx:for="{{item}}">
<text>{{item}}</text>
</block>
</block>
File Upload
Use wx.uploadFile() to send local files to a server:
Page({
data: { preview: null },
upload() {
wx.chooseImage({
success: (res) => {
const path = res.tempFilePaths[0];
wx.showToast({ title: 'Uploading...', icon: 'loading' });
wx.uploadFile({
url: 'http://localhost/upload',
filePath: path,
name: 'file',
success: (resp) => {
if (resp.statusCode !== 200) {
wx.showModal({ title: 'Error', content: 'Upload failed', showCancel: false });
return;
}
this.setData({ preview: path });
},
fail: () => {
wx.showModal({ title: 'Error', content: 'Upload failed', showCancel: false });
},
complete: () => wx.hideToast()
});
}
});
}
});
File Download
Download files using wx.downloadFile():
Page({
data: { image: null },
download() {
wx.downloadFile({
url: 'http://localhost/photo.jpg',
success: (res) => {
this.setData({ image: res.tempFilePath });
}
});
}
});
Multimedia APIs
These APIs handle images, audio recording, and playback.
Image Handling
- Select or capture image:
wx.chooseImage() - Preview images:
wx.previewImage({ urls: [...], current: '...' }) - Get image metadata:
wx.getImageInfo({ src: '...' }) - Save to album: Requires
scope.writePhotosAlbumpermission viawx.saveImageToPhotosAlbum()
Audio Recording
Record audio with wx.startRecord() and stop with wx.stopRecord(). Note: These are deprecated in newer versiosn; use wx.getRecorderManager() instead.
Voice Playback
Play, pause, or stop short audio clips:
wx.playVoice({ filePath: '...' })wx.pauseVoice()wx.stopVoice()
Background Music
Control background music playback:
wx.playBackgroundAudio({ dataUrl, title, coverImgUrl })wx.getBackgroundAudioPlayerState()wx.seekBackgroundAudio({ position })wx.pauseBackgroundAudio(),wx.stopBackgroundAudio()- Event listeners:
wx.onBackgroundAudioPlay(),wx.onBackgroundAudioPause(),wx.onBackgroundAudioStop()
File System APIs
Manage persistent local files beyond temporary storage.
- Save file:
wx.saveFile({ tempFilePath }) - List saved files:
wx.getSavedFileList() - Get file info:
wx.getSavedFileInfo({ filePath }) - Delete file:
wx.removeSavedFile({ filePath }) - Open document:
wx.openDocument({ filePath })(supports PDF, DOCX, etc.)
Local Storage APIs
Store key-value data persistently (up to 10MB). Both async and sync methods available.
- Set:
wx.setStorage({ key, data })orwx.setStorageSync(key, data) - Get:
wx.getStorage({ key })orwx.getStorageSync(key) - Remove:
wx.removeStorage({ key })orwx.removeStorageSync(key) - Clear all:
wx.clearStorage()orwx.clearStorageSync()
Location APIs
Access geolocation using WGS84 (global) or GCJ02 (China-encrypted) coordinates.
- Get current location:
wx.getLocation({ type: 'wgs84' }) - Choose location from map:
wx.chooseLocation() - Open location in map:
wx.openLocation({ latitude, longitude, name, address })
Device APIs
Access device capabilities:
- System info:
wx.getSystemInfo()orwx.getSystemInfoSync() - Network type:
wx.getNetworkType() - Monitor network changes:
wx.onNetworkStatusChange(callback) - Make phone call:
wx.makePhoneCall({ phoneNumber: '10086' }) - Scan QR code:
wx.scanCode({ onlyFromCamera: false })