0
# Core WeChat APIs
1
2
Main WeChat platform APIs including network requests, storage, UI interactions, media operations, device access, and system information.
3
4
## Capabilities
5
6
### Network APIs
7
8
HTTP requests, file uploads/downloads, and WebSocket connections.
9
10
```typescript { .api }
11
interface Wx {
12
/** Make HTTP request */
13
request(options: RequestOption): RequestTask;
14
15
/** Upload file to server */
16
uploadFile(options: UploadFileOption): UploadTask;
17
18
/** Download file from server */
19
downloadFile(options: DownloadFileOption): DownloadTask;
20
21
/** Connect to WebSocket */
22
connectSocket(options: ConnectSocketOption): SocketTask;
23
24
/** Send WebSocket message */
25
sendSocketMessage(options: SendSocketMessageOption): void;
26
27
/** Close WebSocket connection */
28
closeSocket(options?: CloseSocketOption): void;
29
}
30
31
interface RequestOption {
32
/** Request URL */
33
url: string;
34
/** Request data */
35
data?: string | Record<string, any> | ArrayBuffer;
36
/** Request headers */
37
header?: Record<string, string>;
38
/** Request timeout in milliseconds */
39
timeout?: number;
40
/** HTTP method */
41
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'PATCH';
42
/** Data type */
43
dataType?: 'json' | 'other';
44
/** Response type */
45
responseType?: 'text' | 'arraybuffer';
46
/** Success callback */
47
success?(res: RequestSuccessCallbackResult): void;
48
/** Failure callback */
49
fail?(res: any): void;
50
/** Completion callback */
51
complete?(res: any): void;
52
}
53
54
interface RequestTask {
55
/** Abort request */
56
abort(): void;
57
/** Listen for header received */
58
onHeadersReceived(callback: (res: any) => void): void;
59
/** Remove header received listener */
60
offHeadersReceived(callback?: (res: any) => void): void;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
// Make HTTP request
68
wx.request({
69
url: 'https://api.example.com/data',
70
method: 'GET',
71
header: {
72
'Authorization': 'Bearer token'
73
},
74
success(res) {
75
console.log('Data received:', res.data);
76
},
77
fail(error) {
78
console.error('Request failed:', error);
79
}
80
});
81
82
// Upload file
83
wx.uploadFile({
84
url: 'https://api.example.com/upload',
85
filePath: tempFilePath,
86
name: 'file',
87
formData: {
88
description: 'User avatar'
89
},
90
success(res) {
91
console.log('Upload success:', res);
92
}
93
});
94
95
// WebSocket connection
96
const socketTask = wx.connectSocket({
97
url: 'wss://api.example.com/ws'
98
});
99
100
socketTask.onMessage((res) => {
101
console.log('Message received:', res.data);
102
});
103
104
socketTask.send({
105
data: JSON.stringify({ type: 'ping' })
106
});
107
```
108
109
### Storage APIs
110
111
Local data storage with sync and async operations.
112
113
```typescript { .api }
114
interface Wx {
115
/** Set storage data asynchronously */
116
setStorage(options: SetStorageOption): void;
117
118
/** Set storage data synchronously */
119
setStorageSync(key: string, data: any): void;
120
121
/** Get storage data asynchronously */
122
getStorage(options: GetStorageOption): void;
123
124
/** Get storage data synchronously */
125
getStorageSync(key: string): any;
126
127
/** Remove storage data asynchronously */
128
removeStorage(options: RemoveStorageOption): void;
129
130
/** Remove storage data synchronously */
131
removeStorageSync(key: string): void;
132
133
/** Clear all storage data asynchronously */
134
clearStorage(options?: ClearStorageOption): void;
135
136
/** Clear all storage data synchronously */
137
clearStorageSync(): void;
138
139
/** Get storage info asynchronously */
140
getStorageInfo(options: GetStorageInfoOption): void;
141
142
/** Get storage info synchronously */
143
getStorageInfoSync(): GetStorageInfoSyncResult;
144
145
/** Batch get storage data synchronously */
146
batchGetStorageSync(options: BatchGetStorageSyncOption): BatchGetStorageSyncResult;
147
148
/** Batch set storage data synchronously */
149
batchSetStorageSync(options: BatchSetStorageSyncOption): void;
150
}
151
152
interface SetStorageOption {
153
/** Storage key */
154
key: string;
155
/** Storage data */
156
data: any;
157
/** Encrypt storage */
158
encrypt?: boolean;
159
/** Success callback */
160
success?(): void;
161
/** Failure callback */
162
fail?(res: any): void;
163
/** Completion callback */
164
complete?(res: any): void;
165
}
166
167
interface GetStorageOption {
168
/** Storage key */
169
key: string;
170
/** Decrypt storage */
171
decrypt?: boolean;
172
/** Success callback */
173
success?(res: { data: any }): void;
174
/** Failure callback */
175
fail?(res: any): void;
176
/** Completion callback */
177
complete?(res: any): void;
178
}
179
```
180
181
**Usage Examples:**
182
183
```typescript
184
// Async storage operations
185
wx.setStorage({
186
key: 'userInfo',
187
data: { name: 'John', age: 30 },
188
success() {
189
console.log('Data saved');
190
}
191
});
192
193
wx.getStorage({
194
key: 'userInfo',
195
success(res) {
196
console.log('User info:', res.data);
197
}
198
});
199
200
// Sync storage operations
201
wx.setStorageSync('settings', { theme: 'dark' });
202
const settings = wx.getStorageSync('settings');
203
204
// Batch operations
205
const results = wx.batchGetStorageSync({
206
keyList: ['userInfo', 'settings', 'cache']
207
});
208
```
209
210
### UI APIs
211
212
User interface interactions including dialogs, navigation, and loading states.
213
214
```typescript { .api }
215
interface Wx {
216
/** Show toast message */
217
showToast(options: ShowToastOption): void;
218
219
/** Hide toast */
220
hideToast(options?: HideToastOption): void;
221
222
/** Show modal dialog */
223
showModal(options: ShowModalOption): void;
224
225
/** Show loading indicator */
226
showLoading(options: ShowLoadingOption): void;
227
228
/** Hide loading indicator */
229
hideLoading(options?: HideLoadingOption): void;
230
231
/** Show action sheet */
232
showActionSheet(options: ShowActionSheetOption): void;
233
234
/** Navigate to page */
235
navigateTo(options: NavigateToOption): void;
236
237
/** Redirect to page */
238
redirectTo(options: RedirectToOption): void;
239
240
/** Switch to tab page */
241
switchTab(options: SwitchTabOption): void;
242
243
/** Navigate back */
244
navigateBack(options?: NavigateBackOption): void;
245
246
/** Relaunch app */
247
reLaunch(options: ReLaunchOption): void;
248
}
249
250
interface ShowToastOption {
251
/** Toast message */
252
title: string;
253
/** Toast icon */
254
icon?: 'success' | 'error' | 'loading' | 'none';
255
/** Custom icon path */
256
image?: string;
257
/** Display duration in ms */
258
duration?: number;
259
/** Mask to prevent touch */
260
mask?: boolean;
261
/** Success callback */
262
success?(): void;
263
/** Failure callback */
264
fail?(res: any): void;
265
/** Completion callback */
266
complete?(res: any): void;
267
}
268
269
interface ShowModalOption {
270
/** Modal title */
271
title?: string;
272
/** Modal content */
273
content?: string;
274
/** Show cancel button */
275
showCancel?: boolean;
276
/** Cancel button text */
277
cancelText?: string;
278
/** Cancel button color */
279
cancelColor?: string;
280
/** Confirm button text */
281
confirmText?: string;
282
/** Confirm button color */
283
confirmColor?: string;
284
/** Show editable content */
285
editable?: boolean;
286
/** Placeholder for editable content */
287
placeholderText?: string;
288
/** Success callback */
289
success?(res: { confirm: boolean; cancel: boolean; content?: string }): void;
290
/** Failure callback */
291
fail?(res: any): void;
292
/** Completion callback */
293
complete?(res: any): void;
294
}
295
```
296
297
**Usage Examples:**
298
299
```typescript
300
// Show toast
301
wx.showToast({
302
title: 'Success',
303
icon: 'success',
304
duration: 2000
305
});
306
307
// Show modal
308
wx.showModal({
309
title: 'Confirm',
310
content: 'Are you sure you want to delete this item?',
311
success(res) {
312
if (res.confirm) {
313
console.log('User confirmed');
314
}
315
}
316
});
317
318
// Navigation
319
wx.navigateTo({
320
url: '/pages/detail/detail?id=123'
321
});
322
323
wx.switchTab({
324
url: '/pages/home/home'
325
});
326
```
327
328
### Media APIs
329
330
Image, video, audio, and camera operations.
331
332
```typescript { .api }
333
interface Wx {
334
/** Choose images from album or camera */
335
chooseImage(options: ChooseImageOption): void;
336
337
/** Choose video from album or camera */
338
chooseVideo(options: ChooseVideoOption): void;
339
340
/** Choose media (image/video) */
341
chooseMedia(options: ChooseMediaOption): void;
342
343
/** Preview images */
344
previewImage(options: PreviewImageOption): void;
345
346
/** Get image info */
347
getImageInfo(options: GetImageInfoOption): void;
348
349
/** Save image to photos album */
350
saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOption): void;
351
352
/** Get recorder manager */
353
getRecorderManager(): RecorderManager;
354
355
/** Get background audio manager */
356
getBackgroundAudioManager(): BackgroundAudioManager;
357
358
/** Create inner audio context */
359
createInnerAudioContext(): InnerAudioContext;
360
361
/** Create video context */
362
createVideoContext(videoId: string, componentInstance?: any): VideoContext;
363
364
/** Create camera context */
365
createCameraContext(): CameraContext;
366
}
367
368
interface ChooseImageOption {
369
/** Maximum number of images */
370
count?: number;
371
/** Image size type */
372
sizeType?: ('original' | 'compressed')[];
373
/** Image source type */
374
sourceType?: ('album' | 'camera')[];
375
/** Success callback */
376
success?(res: { tempFilePaths: string[]; tempFiles: { path: string; size: number }[] }): void;
377
/** Failure callback */
378
fail?(res: any): void;
379
/** Completion callback */
380
complete?(res: any): void;
381
}
382
383
interface RecorderManager {
384
/** Start recording */
385
start(options: RecorderManagerStartOption): void;
386
/** Pause recording */
387
pause(): void;
388
/** Resume recording */
389
resume(): void;
390
/** Stop recording */
391
stop(): void;
392
/** Listen for recording start */
393
onStart(callback: () => void): void;
394
/** Listen for recording stop */
395
onStop(callback: (res: { tempFilePath: string }) => void): void;
396
}
397
```
398
399
**Usage Examples:**
400
401
```typescript
402
// Choose and upload image
403
wx.chooseImage({
404
count: 1,
405
sizeType: ['compressed'],
406
sourceType: ['album', 'camera'],
407
success(res) {
408
const tempFilePath = res.tempFilePaths[0];
409
wx.uploadFile({
410
url: 'https://api.example.com/upload',
411
filePath: tempFilePath,
412
name: 'image'
413
});
414
}
415
});
416
417
// Record audio
418
const recorder = wx.getRecorderManager();
419
recorder.start({
420
duration: 60000,
421
sampleRate: 16000,
422
numberOfChannels: 1,
423
encodeBitRate: 96000,
424
format: 'mp3'
425
});
426
427
recorder.onStop((res) => {
428
console.log('Recording saved:', res.tempFilePath);
429
});
430
```
431
432
### Device APIs
433
434
System information, device capabilities, and hardware access.
435
436
```typescript { .api }
437
interface Wx {
438
/** Get system info */
439
getSystemInfo(options: GetSystemInfoOption): void;
440
441
/** Get system info synchronously */
442
getSystemInfoSync(): SystemInfo;
443
444
/** Get device info */
445
getDeviceInfo(options?: GetDeviceInfoOption): void;
446
447
/** Get window info */
448
getWindowInfo(options?: GetWindowInfoOption): void;
449
450
/** Get app base info */
451
getAppBaseInfo(options?: GetAppBaseInfoOption): void;
452
453
/** Get network type */
454
getNetworkType(options: GetNetworkTypeOption): void;
455
456
/** Listen for network status change */
457
onNetworkStatusChange(callback: (res: { isConnected: boolean; networkType: string }) => void): void;
458
459
/** Get clipboard data */
460
getClipboardData(options: GetClipboardDataOption): void;
461
462
/** Set clipboard data */
463
setClipboardData(options: SetClipboardDataOption): void;
464
465
/** Make phone call */
466
makePhoneCall(options: MakePhoneCallOption): void;
467
468
/** Scan QR/bar code */
469
scanCode(options: ScanCodeOption): void;
470
471
/** Set screen brightness */
472
setScreenBrightness(options: SetScreenBrightnessOption): void;
473
474
/** Get screen brightness */
475
getScreenBrightness(options: GetScreenBrightnessOption): void;
476
477
/** Set keep screen on */
478
setKeepScreenOn(options: SetKeepScreenOnOption): void;
479
480
/** Vibrate long */
481
vibrateLong(options?: VibrateLongOption): void;
482
483
/** Vibrate short */
484
vibrateShort(options?: VibrateShortOption): void;
485
}
486
487
interface SystemInfo {
488
/** Device brand */
489
brand: string;
490
/** Device model */
491
model: string;
492
/** System name */
493
system: string;
494
/** System version */
495
version: string;
496
/** Platform */
497
platform: string;
498
/** Language */
499
language: string;
500
/** WeChat version */
501
version: string;
502
/** SDK version */
503
SDKVersion: string;
504
/** Screen width in px */
505
screenWidth: number;
506
/** Screen height in px */
507
screenHeight: number;
508
/** Window width in px */
509
windowWidth: number;
510
/** Window height in px */
511
windowHeight: number;
512
/** Status bar height in px */
513
statusBarHeight: number;
514
/** Device pixel ratio */
515
pixelRatio: number;
516
}
517
```
518
519
**Usage Examples:**
520
521
```typescript
522
// Get system info
523
wx.getSystemInfo({
524
success(res) {
525
console.log('Device:', res.model);
526
console.log('System:', res.system);
527
console.log('Screen size:', res.screenWidth, 'x', res.screenHeight);
528
}
529
});
530
531
// Scan QR code
532
wx.scanCode({
533
success(res) {
534
console.log('Scanned result:', res.result);
535
console.log('Scan type:', res.scanType);
536
}
537
});
538
539
// Set clipboard
540
wx.setClipboardData({
541
data: 'Hello WeChat',
542
success() {
543
wx.showToast({ title: 'Copied to clipboard' });
544
}
545
});
546
```
547
548
## File System APIs
549
550
```typescript { .api }
551
interface Wx {
552
/** Get file system manager */
553
getFileSystemManager(): FileSystemManager;
554
555
/** Create offscreen canvas */
556
createOffscreenCanvas(): OffscreenCanvas;
557
558
/** Get performance */
559
getPerformance(): Performance;
560
561
/** Report performance */
562
reportPerformance(id: number, value: number, dimensions?: Record<string, string>): void;
563
564
/** Save file */
565
saveFile(options: SaveFileOption): void;
566
567
/** Get saved file list */
568
getSavedFileList(options: GetSavedFileListOption): void;
569
570
/** Get saved file info */
571
getSavedFileInfo(options: GetSavedFileInfoOption): void;
572
573
/** Remove saved file */
574
removeSavedFile(options: RemoveSavedFileOption): void;
575
576
/** Open document */
577
openDocument(options: OpenDocumentOption): void;
578
}
579
580
interface FileSystemManager {
581
/** Read file */
582
readFile(options: ReadFileOption): void;
583
/** Write file */
584
writeFile(options: WriteFileOption): void;
585
/** Copy file */
586
copyFile(options: CopyFileOption): void;
587
/** Rename file */
588
rename(options: RenameOption): void;
589
/** Remove file */
590
unlink(options: UnlinkOption): void;
591
/** Create directory */
592
mkdir(options: MkdirOption): void;
593
/** Remove directory */
594
rmdir(options: RmdirOption): void;
595
/** Read directory */
596
readdir(options: ReaddirOption): void;
597
/** Get file stats */
598
stat(options: StatOption): void;
599
}
600
```
601
602
## Types
603
604
```typescript { .api }
605
// Main WeChat API interface
606
interface WechatMiniprogram.Wx {
607
// Network APIs
608
request(options: RequestOption): RequestTask;
609
uploadFile(options: UploadFileOption): UploadTask;
610
downloadFile(options: DownloadFileOption): DownloadTask;
611
612
// Storage APIs
613
setStorage(options: SetStorageOption): void;
614
getStorage(options: GetStorageOption): void;
615
616
// UI APIs
617
showToast(options: ShowToastOption): void;
618
showModal(options: ShowModalOption): void;
619
navigateTo(options: NavigateToOption): void;
620
621
// Media APIs
622
chooseImage(options: ChooseImageOption): void;
623
chooseVideo(options: ChooseVideoOption): void;
624
625
// Device APIs
626
getSystemInfo(options: GetSystemInfoOption): void;
627
scanCode(options: ScanCodeOption): void;
628
}
629
630
// Async method result type helper
631
type WechatMiniprogram.PromisifySuccessResult<
632
P,
633
T extends WechatMiniprogram.AsyncMethodOptionLike
634
> = P extends { success: any }
635
? void
636
: P extends { fail: any }
637
? void
638
: P extends { complete: any }
639
? void
640
: Promise<Parameters<Exclude<T['success'], undefined>>[0]>;
641
```