0
# Device & Hardware APIs
1
2
Comprehensive device and hardware integration APIs for WeChat Mini Programs, including sensors, biometric authentication, device information, and system interactions.
3
4
## Capabilities
5
6
### Biometric Authentication
7
8
Secure biometric authentication using fingerprint, face recognition, and other device security features.
9
10
```typescript { .api }
11
/**
12
* Check if biometric authentication is supported
13
* @param option - Support check configuration
14
*/
15
function checkIsSupportSoterAuthentication(option: CheckIsSupportSoterAuthenticationOption): void;
16
17
/**
18
* Check if biometric authentication is enrolled
19
* @param option - Enrollment check configuration
20
*/
21
function checkIsSoterEnrolledInDevice(option: CheckIsSoterEnrolledInDeviceOption): void;
22
23
/**
24
* Start biometric authentication process
25
* @param option - Authentication configuration
26
*/
27
function startSoterAuthentication(option: StartSoterAuthenticationOption): void;
28
29
interface CheckIsSupportSoterAuthenticationOption {
30
/** Success callback */
31
success?(res: CheckIsSupportSoterAuthenticationSuccessCallbackResult): void;
32
/** Failure callback */
33
fail?(res: any): void;
34
/** Completion callback */
35
complete?(res: any): void;
36
}
37
38
interface CheckIsSupportSoterAuthenticationSuccessCallbackResult {
39
/** Supported authentication methods */
40
supportMode: ('fingerPrint' | 'facial' | 'speech')[];
41
/** Error message */
42
errMsg: string;
43
}
44
45
interface StartSoterAuthenticationOption {
46
/** Authentication request reason */
47
requestAuthModes: ('fingerPrint' | 'facial' | 'speech')[];
48
/** Challenge string for security */
49
challenge: string;
50
/** Authentication reason displayed to user */
51
authContent?: string;
52
/** Success callback */
53
success?(res: StartSoterAuthenticationSuccessCallbackResult): void;
54
/** Failure callback */
55
fail?(res: any): void;
56
/** Completion callback */
57
complete?(res: any): void;
58
}
59
60
interface StartSoterAuthenticationSuccessCallbackResult {
61
/** Authentication result token */
62
resultJSON: string;
63
/** Authentication signature */
64
resultJSONSignature: string;
65
/** Error message */
66
errMsg: string;
67
}
68
```
69
70
**Usage Examples:**
71
72
```typescript
73
// Check biometric support
74
wx.checkIsSupportSoterAuthentication({
75
success(res) {
76
console.log('Supported auth methods:', res.supportMode);
77
78
if (res.supportMode.includes('fingerPrint')) {
79
console.log('Fingerprint authentication supported');
80
}
81
if (res.supportMode.includes('facial')) {
82
console.log('Face authentication supported');
83
}
84
}
85
});
86
87
// Check if biometrics are enrolled
88
wx.checkIsSoterEnrolledInDevice({
89
checkAuthMode: 'fingerPrint',
90
success(res) {
91
if (res.isEnrolled) {
92
console.log('Fingerprint is enrolled');
93
// Proceed with authentication
94
authenticateUser();
95
} else {
96
console.log('No fingerprint enrolled');
97
// Prompt user to enroll
98
}
99
}
100
});
101
102
// Perform biometric authentication
103
function authenticateUser() {
104
const challenge = generateRandomChallenge(); // Your challenge generation
105
106
wx.startSoterAuthentication({
107
requestAuthModes: ['fingerPrint', 'facial'],
108
challenge: challenge,
109
authContent: 'Please authenticate to access secure features',
110
success(res) {
111
console.log('Authentication successful');
112
console.log('Result token:', res.resultJSON);
113
console.log('Signature:', res.resultJSONSignature);
114
115
// Verify authentication on your server
116
verifyAuthentication(res.resultJSON, res.resultJSONSignature);
117
},
118
fail(err) {
119
console.error('Authentication failed:', err);
120
// Handle authentication failure
121
}
122
});
123
}
124
```
125
126
### Device Sensors
127
128
Access to device sensors including accelerometer, gyroscope, compass, and device motion.
129
130
```typescript { .api }
131
/**
132
* Start accelerometer monitoring
133
* @param option - Accelerometer configuration
134
*/
135
function startAccelerometer(option?: StartAccelerometerOption): void;
136
137
/**
138
* Stop accelerometer monitoring
139
* @param option - Stop accelerometer configuration
140
*/
141
function stopAccelerometer(option?: StopAccelerometerOption): void;
142
143
/**
144
* Listen for accelerometer data changes
145
* @param callback - Accelerometer data callback
146
*/
147
function onAccelerometerChange(callback: (res: AccelerometerData) => void): void;
148
149
/**
150
* Remove accelerometer change listener
151
* @param callback - Callback to remove
152
*/
153
function offAccelerometerChange(callback?: (res: AccelerometerData) => void): void;
154
155
interface StartAccelerometerOption {
156
/** Data collection interval */
157
interval?: 'game' | 'ui' | 'normal';
158
/** Success callback */
159
success?(res: any): void;
160
/** Failure callback */
161
fail?(res: any): void;
162
/** Completion callback */
163
complete?(res: any): void;
164
}
165
166
interface AccelerometerData {
167
/** X-axis acceleration */
168
x: number;
169
/** Y-axis acceleration */
170
y: number;
171
/** Z-axis acceleration */
172
z: number;
173
}
174
175
/**
176
* Start gyroscope monitoring
177
* @param option - Gyroscope configuration
178
*/
179
function startGyroscope(option?: StartGyroscopeOption): void;
180
181
/**
182
* Stop gyroscope monitoring
183
* @param option - Stop gyroscope configuration
184
*/
185
function stopGyroscope(option?: StopGyroscopeOption): void;
186
187
/**
188
* Listen for gyroscope data changes
189
* @param callback - Gyroscope data callback
190
*/
191
function onGyroscopeChange(callback: (res: GyroscopeData) => void): void;
192
193
interface GyroscopeData {
194
/** X-axis angular velocity */
195
x: number;
196
/** Y-axis angular velocity */
197
y: number;
198
/** Z-axis angular velocity */
199
z: number;
200
}
201
202
/**
203
* Start compass monitoring
204
* @param option - Compass configuration
205
*/
206
function startCompass(option?: StartCompassOption): void;
207
208
/**
209
* Stop compass monitoring
210
* @param option - Stop compass configuration
211
*/
212
function stopCompass(option?: StopCompassOption): void;
213
214
/**
215
* Listen for compass direction changes
216
* @param callback - Compass data callback
217
*/
218
function onCompassChange(callback: (res: CompassData) => void): void;
219
220
interface CompassData {
221
/** Direction in degrees (0-360) */
222
direction: number;
223
/** Accuracy of the reading */
224
accuracy: number | string;
225
}
226
```
227
228
**Usage Examples:**
229
230
```typescript
231
// Monitor device motion for gaming
232
wx.startAccelerometer({
233
interval: 'game', // High frequency for responsive gaming
234
success() {
235
console.log('Accelerometer started');
236
}
237
});
238
239
wx.onAccelerometerChange((res) => {
240
console.log(`Acceleration - X: ${res.x}, Y: ${res.y}, Z: ${res.z}`);
241
242
// Detect device shake
243
const acceleration = Math.sqrt(res.x * res.x + res.y * res.y + res.z * res.z);
244
if (acceleration > 15) {
245
console.log('Device shake detected!');
246
handleShakeGesture();
247
}
248
});
249
250
// Monitor device rotation for AR applications
251
wx.startGyroscope({
252
interval: 'game'
253
});
254
255
wx.onGyroscopeChange((res) => {
256
// Update 3D object rotation based on device rotation
257
updateObjectRotation(res.x, res.y, res.z);
258
});
259
260
// Compass for navigation
261
wx.startCompass();
262
263
wx.onCompassChange((res) => {
264
console.log(`Heading: ${res.direction}° (accuracy: ${res.accuracy})`);
265
updateNavigationArrow(res.direction);
266
});
267
268
// Clean up sensors when not needed
269
function stopAllSensors() {
270
wx.stopAccelerometer();
271
wx.stopGyroscope();
272
wx.stopCompass();
273
console.log('All sensors stopped');
274
}
275
```
276
277
### Device Motion Listening
278
279
Comprehensive device motion detection for advanced gesture recognition.
280
281
```typescript { .api }
282
/**
283
* Start device motion listening
284
* @param option - Motion listening configuration
285
*/
286
function startDeviceMotionListening(option?: StartDeviceMotionListeningOption): void;
287
288
/**
289
* Stop device motion listening
290
* @param option - Stop motion listening configuration
291
*/
292
function stopDeviceMotionListening(option?: StopDeviceMotionListeningOption): void;
293
294
/**
295
* Listen for device motion changes
296
* @param callback - Device motion callback
297
*/
298
function onDeviceMotionChange(callback: (res: DeviceMotionData) => void): void;
299
300
/**
301
* Remove device motion change listener
302
* @param callback - Callback to remove
303
*/
304
function offDeviceMotionChange(callback?: (res: DeviceMotionData) => void): void;
305
306
interface StartDeviceMotionListeningOption {
307
/** Listening interval */
308
interval?: 'game' | 'ui' | 'normal';
309
/** Success callback */
310
success?(res: any): void;
311
/** Failure callback */
312
fail?(res: any): void;
313
/** Completion callback */
314
complete?(res: any): void;
315
}
316
317
interface DeviceMotionData {
318
/** Acceleration including gravity */
319
acceleration: {
320
x: number;
321
y: number;
322
z: number;
323
};
324
/** Acceleration excluding gravity */
325
accelerationIncludingGravity: {
326
x: number;
327
y: number;
328
z: number;
329
};
330
/** Rotation rate */
331
rotationRate: {
332
alpha: number;
333
beta: number;
334
gamma: number;
335
};
336
/** Time interval */
337
interval: number;
338
}
339
```
340
341
### Battery Information
342
343
Monitor device battery status and power management.
344
345
```typescript { .api }
346
/**
347
* Get battery information
348
* @param option - Battery info configuration
349
*/
350
function getBatteryInfo(option?: GetBatteryInfoOption): void;
351
352
/**
353
* Get battery information synchronously
354
*/
355
function getBatteryInfoSync(): GetBatteryInfoSyncResult;
356
357
interface GetBatteryInfoOption {
358
/** Success callback */
359
success?(res: GetBatteryInfoSuccessCallbackResult): void;
360
/** Failure callback */
361
fail?(res: any): void;
362
/** Completion callback */
363
complete?(res: any): void;
364
}
365
366
interface GetBatteryInfoSuccessCallbackResult {
367
/** Battery level (0-100) */
368
level: number;
369
/** Whether device is charging */
370
isCharging: boolean;
371
/** Error message */
372
errMsg: string;
373
}
374
375
interface GetBatteryInfoSyncResult {
376
/** Battery level (0-100) */
377
level: number;
378
/** Whether device is charging */
379
isCharging: boolean;
380
}
381
```
382
383
### Screen and Display
384
385
Screen brightness control and display information.
386
387
```typescript { .api }
388
/**
389
* Set screen brightness
390
* @param option - Screen brightness configuration
391
*/
392
function setScreenBrightness(option: SetScreenBrightnessOption): void;
393
394
/**
395
* Get screen brightness
396
* @param option - Get brightness configuration
397
*/
398
function getScreenBrightness(option?: GetScreenBrightnessOption): void;
399
400
/**
401
* Set whether to keep screen on
402
* @param option - Keep screen on configuration
403
*/
404
function setKeepScreenOn(option: SetKeepScreenOnOption): void;
405
406
interface SetScreenBrightnessOption {
407
/** Brightness value (0-1) */
408
value: number;
409
/** Success callback */
410
success?(res: any): void;
411
/** Failure callback */
412
fail?(res: any): void;
413
/** Completion callback */
414
complete?(res: any): void;
415
}
416
417
interface GetScreenBrightnessSuccessCallbackResult {
418
/** Current brightness value (0-1) */
419
value: number;
420
/** Error message */
421
errMsg: string;
422
}
423
424
interface SetKeepScreenOnOption {
425
/** Whether to keep screen on */
426
keepScreenOn: boolean;
427
/** Success callback */
428
success?(res: any): void;
429
/** Failure callback */
430
fail?(res: any): void;
431
/** Completion callback */
432
complete?(res: any): void;
433
}
434
```
435
436
**Usage Examples:**
437
438
```typescript
439
// Battery monitoring for power-aware applications
440
wx.getBatteryInfo({
441
success(res) {
442
console.log(`Battery level: ${res.level}%`);
443
console.log(`Charging: ${res.isCharging}`);
444
445
if (res.level < 20 && !res.isCharging) {
446
console.log('Low battery - enabling power saving mode');
447
enablePowerSavingMode();
448
}
449
}
450
});
451
452
// Sync battery check
453
const batteryInfo = wx.getBatteryInfoSync();
454
if (batteryInfo.level < 10) {
455
showLowBatteryWarning();
456
}
457
458
// Screen brightness adjustment
459
wx.getScreenBrightness({
460
success(res) {
461
console.log(`Current brightness: ${res.value}`);
462
463
// Auto-adjust brightness based on time
464
const hour = new Date().getHours();
465
let targetBrightness = res.value;
466
467
if (hour < 7 || hour > 22) {
468
targetBrightness = Math.min(res.value, 0.3); // Dim for night
469
}
470
471
if (targetBrightness !== res.value) {
472
wx.setScreenBrightness({
473
value: targetBrightness,
474
success() {
475
console.log(`Brightness adjusted to ${targetBrightness}`);
476
}
477
});
478
}
479
}
480
});
481
482
// Keep screen on during video playback
483
function startVideoPlayback() {
484
wx.setKeepScreenOn({
485
keepScreenOn: true,
486
success() {
487
console.log('Screen will stay on during video');
488
}
489
});
490
}
491
492
function stopVideoPlayback() {
493
wx.setKeepScreenOn({
494
keepScreenOn: false,
495
success() {
496
console.log('Screen can now turn off normally');
497
}
498
});
499
}
500
```
501
502
### Vibration Control
503
504
Device vibration patterns for haptic feedback.
505
506
```typescript { .api }
507
/**
508
* Trigger device vibration
509
* @param option - Vibration configuration
510
*/
511
function vibrateLong(option?: VibrateLongOption): void;
512
513
/**
514
* Trigger short vibration
515
* @param option - Short vibration configuration
516
*/
517
function vibrateShort(option?: VibrateShortOption): void;
518
519
interface VibrateLongOption {
520
/** Success callback */
521
success?(res: any): void;
522
/** Failure callback */
523
fail?(res: any): void;
524
/** Completion callback */
525
complete?(res: any): void;
526
}
527
528
interface VibrateShortOption {
529
/** Vibration type */
530
type?: 'heavy' | 'medium' | 'light';
531
/** Success callback */
532
success?(res: any): void;
533
/** Failure callback */
534
fail?(res: any): void;
535
/** Completion callback */
536
complete?(res: any): void;
537
}
538
```
539
540
### System Information
541
542
Comprehensive device and system information access.
543
544
```typescript { .api }
545
/**
546
* Get system information
547
* @param option - System info configuration
548
*/
549
function getSystemInfo(option?: GetSystemInfoOption): void;
550
551
/**
552
* Get system information synchronously
553
*/
554
function getSystemInfoSync(): SystemInfo;
555
556
/**
557
* Get device information
558
* @param option - Device info configuration
559
*/
560
function getDeviceInfo(option?: GetDeviceInfoOption): void;
561
562
/**
563
* Get window information
564
* @param option - Window info configuration
565
*/
566
function getWindowInfo(option?: GetWindowInfoOption): void;
567
568
interface SystemInfo {
569
/** Device brand */
570
brand: string;
571
/** Device model */
572
model: string;
573
/** Device pixel ratio */
574
pixelRatio: number;
575
/** Screen width in pixels */
576
screenWidth: number;
577
/** Screen height in pixels */
578
screenHeight: number;
579
/** Window width in pixels */
580
windowWidth: number;
581
/** Window height in pixels */
582
windowHeight: number;
583
/** Status bar height */
584
statusBarHeight: number;
585
/** Language */
586
language: string;
587
/** WeChat version */
588
version: string;
589
/** System name */
590
system: string;
591
/** Platform */
592
platform: string;
593
/** Font size setting */
594
fontSizeSetting: number;
595
/** SDK version */
596
SDKVersion: string;
597
/** Benchmark score */
598
benchmarkLevel: number;
599
/** Album authorization */
600
albumAuthorized: boolean;
601
/** Camera authorization */
602
cameraAuthorized: boolean;
603
/** Location authorization */
604
locationAuthorized: boolean;
605
/** Microphone authorization */
606
microphoneAuthorized: boolean;
607
/** Notification authorization */
608
notificationAuthorized: boolean;
609
/** Phone calendar authorization */
610
phoneCalendarAuthorized: boolean;
611
/** Safe area */
612
safeArea: {
613
left: number;
614
right: number;
615
top: number;
616
bottom: number;
617
width: number;
618
height: number;
619
};
620
}
621
```
622
623
**Usage Examples:**
624
625
```typescript
626
// Comprehensive system information
627
wx.getSystemInfo({
628
success(res) {
629
console.log('Device Info:');
630
console.log(`Brand: ${res.brand}`);
631
console.log(`Model: ${res.model}`);
632
console.log(`System: ${res.system}`);
633
console.log(`Screen: ${res.screenWidth}x${res.screenHeight}`);
634
console.log(`Safe Area:`, res.safeArea);
635
636
// Adapt UI based on device capabilities
637
if (res.benchmarkLevel >= 1) {
638
enableHighQualityGraphics();
639
}
640
641
// Handle notch/safe area
642
if (res.safeArea.top > res.statusBarHeight) {
643
adjustForNotch(res.safeArea);
644
}
645
}
646
});
647
648
// Quick sync access
649
const systemInfo = wx.getSystemInfoSync();
650
console.log(`Platform: ${systemInfo.platform}`);
651
console.log(`WeChat Version: ${systemInfo.version}`);
652
653
// Permission checking
654
if (systemInfo.cameraAuthorized && systemInfo.microphoneAuthorized) {
655
enableVideoCall();
656
} else {
657
requestCameraAndMicPermissions();
658
}
659
```
660
661
## Event Listeners
662
663
```typescript { .api }
664
// Memory warning listener
665
function onMemoryWarning(callback: (res: MemoryWarningInfo) => void): void;
666
function offMemoryWarning(callback?: (res: MemoryWarningInfo) => void): void;
667
668
// Theme change listener
669
function onThemeChange(callback: (res: ThemeChangeInfo) => void): void;
670
function offThemeChange(callback?: (res: ThemeChangeInfo) => void): void;
671
672
interface MemoryWarningInfo {
673
/** Warning level */
674
level: 5 | 10 | 15;
675
}
676
677
interface ThemeChangeInfo {
678
/** Current theme */
679
theme: 'light' | 'dark';
680
}
681
```
682
683
**Usage Examples:**
684
685
```typescript
686
// Memory management
687
wx.onMemoryWarning((res) => {
688
console.log(`Memory warning level: ${res.level}`);
689
690
switch (res.level) {
691
case 5:
692
// Trim caches
693
clearImageCache();
694
break;
695
case 10:
696
// Release non-essential resources
697
releaseNonEssentialResources();
698
break;
699
case 15:
700
// Critical memory situation
701
emergencyMemoryCleanup();
702
break;
703
}
704
});
705
706
// Theme adaptation
707
wx.onThemeChange((res) => {
708
console.log(`Theme changed to: ${res.theme}`);
709
updateUITheme(res.theme);
710
});
711
```