Network APIs
Network APIs enable developers to perform URL requests, file uploads/dwonloads, and WebSocket communication. The WeChat Mini Program development team provides 10 network API interfaces.
wx.request(Object)- Initiates HTTPS requestswx.uploadFile(Object)- Uploads local resources to backend serverswx.downloadFile(Object)- Downloads file resources to local storagewx.connectSocket(Object)- Creates WebSocket connectionswx.sendSocketMessage(Object)- Sends data via WebSocketwx.closeSocket(Object)- Closes WebSocket connectionswx.onSocketOpen(Callback)- Listens for WebSocket connection eventswx.onSocketError(Callback)- Listens for WebSocket errorswx.onSocketMessage(Callback)- Listens for WebSocket server messageswx.onSocketClose(Callback)- Listens for WebSocket closure
Making Network Requests
The wx.request(Object) interface sends requests to servers and retrieves data. A mini program can have up to 5 concurrent network requests, and HTTPS is required by default.
// page.js
Page({
data: {
responseData: ""
},
fetchData: function() {
const context = this;
wx.request({
url: 'https://api.example.com/data',
method: 'GET',
header: {
'Content-Type': 'application/json'
},
success: function(response) {
context.setData({
responseData: response.data
});
}
});
}
});
Uploading Files
The wx.uploadFile(Object) interface uploads local resources to the development server via HTTPS POST.
// page.js
Page({
data: {
imagePath: null
},
handleUpload: function() {
const page = this;
wx.chooseImage({
count: 1,
success: function(images) {
const tempPath = images.tempFilePaths[0];
wx.showLoading({ title: 'Uploading...' });
wx.uploadFile({
url: 'https://api.example.com/upload',
filePath: tempPath,
name: 'file',
success: function(response) {
if (response.statusCode === 200) {
page.setData({
imagePath: tempPath
});
} else {
wx.showToast({
title: 'Upload failed',
icon: 'none'
});
}
},
complete: function() {
wx.hideLoading();
}
});
}
});
}
});
Downloading Files
The wx.downloadFile(Object) interface downloads files from the server, returning a local temporary path.
// page.js
Page({
data: {
downloadedImage: null
},
handleDownload: function() {
const self = this;
wx.downloadFile({
url: 'https://example.com/images/photo.jpg',
success: function(result) {
self.setData({
downloadedImage: result.tempFilePath
});
}
});
}
});
Media APIs
Media APIs enhance page functionality through image processing, recording, audio playback, and music control.
Image APIs
wx.chooseImage(Object)- Selects images from album or camerawx.previewImage(Object)- Previews imageswx.getImageInfo(Object)- Retrieves image informationwx.saveImageToPhotosAlbum(Object)- Saves images to system album
Selecting Images
wx.chooseImage({
count: 3,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function(images) {
console.log('Local paths:', images.tempFilePaths);
console.log('File details:', images.tempFiles);
}
});
Previewing Images
wx.previewImage({
current: 'https://example.com/image2.jpg',
urls: [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
]
});
Getting Image Information
wx.chooseImage({
success: function(images) {
wx.getImageInfo({
src: images.tempFilePaths[0],
success: function(info) {
console.log('Width:', info.width);
console.log('Height:', info.height);
}
});
}
});
Saving to Album
wx.chooseImage({
success: function(images) {
wx.saveImageToPhotosAlbum({
filePath: images.tempFilePaths[0],
success: function() {
wx.showToast({ title: 'Saved successfully' });
}
});
}
});
Recording APIs
wx.startRecord(Object)- Starts recordingwx.stopRecord(Object)- Stops recording
wx.startRecord({
success: function(result) {
const tempPath = result.tempFilePath;
// Save the recording file
},
fail: function() {
console.log('Recording failed');
}
});
// Stop after 30 seconds
setTimeout(() => {
wx.stopRecord();
}, 30000);
Audio Playback APIs
wx.playVoice(Object)- Plays voice fileswx.pauseVoice(Object)- Pauses playbackwx.stopVoice(Object)- Stops playback
wx.startRecord({
success: function(result) {
const filePath = result.tempFilePath;
wx.playVoice({
filePath: filePath
});
// Pause after 5 seconds
setTimeout(() => {
wx.pauseVoice();
}, 5000);
// Stop after 10 seconds
setTimeout(() => {
wx.stopVoice();
}, 10000);
}
});
Music Playback APIs
These APIs control background music plabyack. Only streaming media from the network is supported.
wx.playBackgroundAudio(Object)- Plays musicwx.getBackgroundAudioPlayerState(Object)- Gets playback statewx.seekBackgroundAudio(Object)- Seeks to positionwx.pauseBackgroundAudio()- Pauses musicwx.stopBackgroundAudio()- Stops musicwx.onBackgroundAudioPlay(Callback)- Listens for play eventswx.onBackgroundAudioPause(Callback)- Listens for pause eventswx.onBackgroundAudioStop(Callback)- Listens for stop events
Page({
data: {
isPlaying: false,
musicData: {
url: 'https://example.com/music/song.mp3',
title: 'Sample Track',
cover: 'https://example.com/images/cover.jpg'
}
},
togglePlayback: function() {
if (this.data.isPlaying) {
wx.pauseBackgroundAudio();
} else {
const music = this.data.musicData;
wx.playBackgroundAudio({
dataUrl: music.url,
title: music.title,
coverImgUrl: music.cover
});
}
},
stopPlayback: function() {
wx.stopBackgroundAudio();
},
seekPosition: function(event) {
const offset = event.target.dataset.offset;
wx.getBackgroundAudioPlayerState({
success: function(state) {
if (state.duration > 0) {
const newPosition = state.currentPosition + offset;
wx.seekBackgroundAudio({
position: Math.max(0, Math.min(newPosition, state.duration))
});
}
}
});
},
onLoad: function() {
this.setupListeners();
},
setupListeners: function() {
const page = this;
wx.onBackgroundAudioPlay(function() {
page.setData({ isPlaying: true });
});
wx.onBackgroundAudioPause(function() {
page.setData({ isPlaying: false });
});
wx.onBackgroundAudioStop(function() {
page.setData({ isPlaying: false });
});
}
});
File APIs
File APIs manage local file operations including saving, retrieving, and deleting files.
wx.saveFile(Object)- Saves files locallywx.getSavedFileList(Object)- Lists saved fileswx.getSavedFileInfo(Object)- Gets file informationwx.removeSavedFile(Object)- Deletes saved fileswx.openDocument(Object)- Opens documents (doc, xls, ppt, pdf)
// Save file
wx.chooseImage({
success: function(images) {
wx.saveFile({
tempFilePath: images.tempFilePaths[0],
success: function(result) {
console.log('Saved to:', result.savedFilePath);
}
});
}
});
// List saved files
wx.getSavedFileList({
success: function(result) {
console.log('Files:', result.fileList);
}
});
// Get file info
wx.getSavedFileInfo({
filePath: '/path/to/saved/file',
success: function(info) {
console.log('File size:', info.size);
}
});
// Delete file
wx.removeSavedFile({
filePath: '/path/to/saved/file',
success: function() {
console.log('File deleted');
}
});
// Open document
wx.downloadFile({
url: 'https://example.com/document.pdf',
success: function(result) {
wx.openDocument({
filePath: result.tempFilePath,
success: function() {
console.log('Document opened');
}
});
}
});
Local Storage APIs
Mini programs provide key-value storage with permanent persistence up to 10MB.
wx.setStorage(Object)/wx.setStorageSync(key, data)- Saves datawx.getStorage(Object)/wx.getStorageSync(key)- Retrieves datawx.removeStorage(Object)/wx.removeStorageSync(key)- Deletes datawx.clearStorage()/wx.clearStorageSync()- Clears all data
Saving Data
// Async version
wx.setStorage({
key: 'username',
data: 'john_doe',
success: function() {
console.log('Data saved');
}
});
// Sync version
wx.setStorageSync('age', '30');
Retrieving Data
// Async version
wx.getStorage({
key: 'username',
success: function(result) {
console.log('Retrieved:', result.data);
}
});
// Sync version
try {
const value = wx.getStorageSync('age');
console.log('Age:', value);
} catch (error) {
console.log('Error:', error);
}
Deleting Data
// Async version
wx.removeStorage({
key: 'username',
success: function() {
console.log('Removed');
}
});
// Sync version
wx.removeStorageSync('age');
Clearing All Data
// Async version
wx.clearStorage();
// Sync version
wx.clearStorageSync();
Location APIs
Mini programs support WGS84 (global standard) and GCj02 (China-specific, encrypted) coordinate systems.
wx.getLocation(Object)- Gets current locationwx.chooseLocation(Object)- Opens map for location selectionwx.openLocation(Object)- Displays location in map
Getting Location
wx.getLocation({
type: 'gcj02',
success: function(result) {
console.log('Longitude:', result.longitude);
console.log('Latitude:', result.latitude);
console.log('Speed:', result.speed);
console.log('Accuracy:', result.accuracy);
}
});
Choosing Location
wx.chooseLocation({
success: function(result) {
console.log('Name:', result.name);
console.log('Address:', result.address);
console.log('Coordinates:', result.longitude, result.latitude);
}
});
Displaying Location
wx.getLocation({
type: 'gcj02',
success: function(result) {
wx.openLocation({
latitude: result.latitude,
longitude: result.longitude,
scale: 15,
name: 'Business Center',
address: '123 Main Street'
});
}
});
Device APIs
Device APIs access system information, network status, phone calls, and scanning.
wx.getSystemInfo(Object)/wx.getSystemInfoSync()- Gets system informationwx.getNetworkType(Object)- Gets network typewx.onNetworkStatusChange(Callback)- Monitors network changeswx.makePhoneCall(Object)- Makes phone callswx.scanCode(Object)- Scans QR codes
Getting System Information
wx.getSystemInfo({
success: function(info) {
console.log('Model:', info.model);
console.log('Pixel Ratio:', info.pixelRatio);
console.log('Screen Width:', info.windowWidth);
console.log('Screen Height:', info.windowHeight);
console.log('WeChat Version:', info.version);
console.log('OS:', info.system);
console.log('Platform:', info.platform);
}
});
Getting Network Type
wx.getNetworkType({
success: function(result) {
console.log('Network type:', result.networkType);
}
});
// Monitor network changes
wx.onNetworkStatusChange(function(result) {
console.log('Connected:', result.isConnected);
console.log('Type:', result.networkType);
});
Making Phone Calls
wx.makePhoneCall({
phoneNumber: '1234567890'
});
Scanning QR Codes
// Scan from camera or album
wx.scanCode({
success: function(result) {
console.log('Content:', result.result);
console.log('Type:', result.scanType);
console.log('Path:', result.path);
}
});
// Camera only
wx.scanCode({
onlyFromCamera: true,
success: function(result) {
console.log('Scanned:', result);
}
});