CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-miniprogram-api-typings

Type definitions for APIs of WeChat Mini Program in TypeScript

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

device-hardware-apis.mddocs/

Device & Hardware APIs

Comprehensive device and hardware integration APIs for WeChat Mini Programs, including sensors, biometric authentication, device information, and system interactions.

Capabilities

Biometric Authentication

Secure biometric authentication using fingerprint, face recognition, and other device security features.

/**
 * Check if biometric authentication is supported
 * @param option - Support check configuration
 */
function checkIsSupportSoterAuthentication(option: CheckIsSupportSoterAuthenticationOption): void;

/**
 * Check if biometric authentication is enrolled
 * @param option - Enrollment check configuration
 */
function checkIsSoterEnrolledInDevice(option: CheckIsSoterEnrolledInDeviceOption): void;

/**
 * Start biometric authentication process
 * @param option - Authentication configuration
 */
function startSoterAuthentication(option: StartSoterAuthenticationOption): void;

interface CheckIsSupportSoterAuthenticationOption {
  /** Success callback */
  success?(res: CheckIsSupportSoterAuthenticationSuccessCallbackResult): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface CheckIsSupportSoterAuthenticationSuccessCallbackResult {
  /** Supported authentication methods */
  supportMode: ('fingerPrint' | 'facial' | 'speech')[];
  /** Error message */
  errMsg: string;
}

interface StartSoterAuthenticationOption {
  /** Authentication request reason */
  requestAuthModes: ('fingerPrint' | 'facial' | 'speech')[];
  /** Challenge string for security */
  challenge: string;
  /** Authentication reason displayed to user */
  authContent?: string;
  /** Success callback */
  success?(res: StartSoterAuthenticationSuccessCallbackResult): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface StartSoterAuthenticationSuccessCallbackResult {
  /** Authentication result token */
  resultJSON: string;
  /** Authentication signature */
  resultJSONSignature: string;
  /** Error message */
  errMsg: string;
}

Usage Examples:

// Check biometric support
wx.checkIsSupportSoterAuthentication({
  success(res) {
    console.log('Supported auth methods:', res.supportMode);
    
    if (res.supportMode.includes('fingerPrint')) {
      console.log('Fingerprint authentication supported');
    }
    if (res.supportMode.includes('facial')) {
      console.log('Face authentication supported');
    }
  }
});

// Check if biometrics are enrolled
wx.checkIsSoterEnrolledInDevice({
  checkAuthMode: 'fingerPrint',
  success(res) {
    if (res.isEnrolled) {
      console.log('Fingerprint is enrolled');
      // Proceed with authentication
      authenticateUser();
    } else {
      console.log('No fingerprint enrolled');
      // Prompt user to enroll
    }
  }
});

// Perform biometric authentication
function authenticateUser() {
  const challenge = generateRandomChallenge(); // Your challenge generation
  
  wx.startSoterAuthentication({
    requestAuthModes: ['fingerPrint', 'facial'],
    challenge: challenge,
    authContent: 'Please authenticate to access secure features',
    success(res) {
      console.log('Authentication successful');
      console.log('Result token:', res.resultJSON);
      console.log('Signature:', res.resultJSONSignature);
      
      // Verify authentication on your server
      verifyAuthentication(res.resultJSON, res.resultJSONSignature);
    },
    fail(err) {
      console.error('Authentication failed:', err);
      // Handle authentication failure
    }
  });
}

Device Sensors

Access to device sensors including accelerometer, gyroscope, compass, and device motion.

/**
 * Start accelerometer monitoring
 * @param option - Accelerometer configuration
 */
function startAccelerometer(option?: StartAccelerometerOption): void;

/**
 * Stop accelerometer monitoring
 * @param option - Stop accelerometer configuration
 */
function stopAccelerometer(option?: StopAccelerometerOption): void;

/**
 * Listen for accelerometer data changes
 * @param callback - Accelerometer data callback
 */
function onAccelerometerChange(callback: (res: AccelerometerData) => void): void;

/**
 * Remove accelerometer change listener
 * @param callback - Callback to remove
 */
function offAccelerometerChange(callback?: (res: AccelerometerData) => void): void;

interface StartAccelerometerOption {
  /** Data collection interval */
  interval?: 'game' | 'ui' | 'normal';
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface AccelerometerData {
  /** X-axis acceleration */
  x: number;
  /** Y-axis acceleration */
  y: number;
  /** Z-axis acceleration */
  z: number;
}

/**
 * Start gyroscope monitoring
 * @param option - Gyroscope configuration
 */
function startGyroscope(option?: StartGyroscopeOption): void;

/**
 * Stop gyroscope monitoring
 * @param option - Stop gyroscope configuration
 */
function stopGyroscope(option?: StopGyroscopeOption): void;

/**
 * Listen for gyroscope data changes
 * @param callback - Gyroscope data callback
 */
function onGyroscopeChange(callback: (res: GyroscopeData) => void): void;

interface GyroscopeData {
  /** X-axis angular velocity */
  x: number;
  /** Y-axis angular velocity */
  y: number;
  /** Z-axis angular velocity */
  z: number;
}

/**
 * Start compass monitoring
 * @param option - Compass configuration
 */
function startCompass(option?: StartCompassOption): void;

/**
 * Stop compass monitoring
 * @param option - Stop compass configuration
 */
function stopCompass(option?: StopCompassOption): void;

/**
 * Listen for compass direction changes
 * @param callback - Compass data callback
 */
function onCompassChange(callback: (res: CompassData) => void): void;

interface CompassData {
  /** Direction in degrees (0-360) */
  direction: number;
  /** Accuracy of the reading */
  accuracy: number | string;
}

Usage Examples:

// Monitor device motion for gaming
wx.startAccelerometer({
  interval: 'game', // High frequency for responsive gaming
  success() {
    console.log('Accelerometer started');
  }
});

wx.onAccelerometerChange((res) => {
  console.log(`Acceleration - X: ${res.x}, Y: ${res.y}, Z: ${res.z}`);
  
  // Detect device shake
  const acceleration = Math.sqrt(res.x * res.x + res.y * res.y + res.z * res.z);
  if (acceleration > 15) {
    console.log('Device shake detected!');
    handleShakeGesture();
  }
});

// Monitor device rotation for AR applications
wx.startGyroscope({
  interval: 'game'
});

wx.onGyroscopeChange((res) => {
  // Update 3D object rotation based on device rotation
  updateObjectRotation(res.x, res.y, res.z);
});

// Compass for navigation
wx.startCompass();

wx.onCompassChange((res) => {
  console.log(`Heading: ${res.direction}° (accuracy: ${res.accuracy})`);
  updateNavigationArrow(res.direction);
});

// Clean up sensors when not needed
function stopAllSensors() {
  wx.stopAccelerometer();
  wx.stopGyroscope();
  wx.stopCompass();
  console.log('All sensors stopped');
}

Device Motion Listening

Comprehensive device motion detection for advanced gesture recognition.

/**
 * Start device motion listening
 * @param option - Motion listening configuration
 */
function startDeviceMotionListening(option?: StartDeviceMotionListeningOption): void;

/**
 * Stop device motion listening
 * @param option - Stop motion listening configuration
 */
function stopDeviceMotionListening(option?: StopDeviceMotionListeningOption): void;

/**
 * Listen for device motion changes
 * @param callback - Device motion callback
 */
function onDeviceMotionChange(callback: (res: DeviceMotionData) => void): void;

/**
 * Remove device motion change listener
 * @param callback - Callback to remove
 */
function offDeviceMotionChange(callback?: (res: DeviceMotionData) => void): void;

interface StartDeviceMotionListeningOption {
  /** Listening interval */
  interval?: 'game' | 'ui' | 'normal';
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface DeviceMotionData {
  /** Acceleration including gravity */
  acceleration: {
    x: number;
    y: number;
    z: number;
  };
  /** Acceleration excluding gravity */
  accelerationIncludingGravity: {
    x: number;
    y: number;
    z: number;
  };
  /** Rotation rate */
  rotationRate: {
    alpha: number;
    beta: number;
    gamma: number;
  };
  /** Time interval */
  interval: number;
}

Battery Information

Monitor device battery status and power management.

/**
 * Get battery information
 * @param option - Battery info configuration
 */
function getBatteryInfo(option?: GetBatteryInfoOption): void;

/**
 * Get battery information synchronously
 */
function getBatteryInfoSync(): GetBatteryInfoSyncResult;

interface GetBatteryInfoOption {
  /** Success callback */
  success?(res: GetBatteryInfoSuccessCallbackResult): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface GetBatteryInfoSuccessCallbackResult {
  /** Battery level (0-100) */
  level: number;
  /** Whether device is charging */
  isCharging: boolean;
  /** Error message */
  errMsg: string;
}

interface GetBatteryInfoSyncResult {
  /** Battery level (0-100) */
  level: number;
  /** Whether device is charging */
  isCharging: boolean;
}

Screen and Display

Screen brightness control and display information.

/**
 * Set screen brightness
 * @param option - Screen brightness configuration
 */
function setScreenBrightness(option: SetScreenBrightnessOption): void;

/**
 * Get screen brightness
 * @param option - Get brightness configuration
 */
function getScreenBrightness(option?: GetScreenBrightnessOption): void;

/**
 * Set whether to keep screen on
 * @param option - Keep screen on configuration
 */
function setKeepScreenOn(option: SetKeepScreenOnOption): void;

interface SetScreenBrightnessOption {
  /** Brightness value (0-1) */
  value: number;
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface GetScreenBrightnessSuccessCallbackResult {
  /** Current brightness value (0-1) */
  value: number;
  /** Error message */
  errMsg: string;
}

interface SetKeepScreenOnOption {
  /** Whether to keep screen on */
  keepScreenOn: boolean;
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

Usage Examples:

// Battery monitoring for power-aware applications
wx.getBatteryInfo({
  success(res) {
    console.log(`Battery level: ${res.level}%`);
    console.log(`Charging: ${res.isCharging}`);
    
    if (res.level < 20 && !res.isCharging) {
      console.log('Low battery - enabling power saving mode');
      enablePowerSavingMode();
    }
  }
});

// Sync battery check
const batteryInfo = wx.getBatteryInfoSync();
if (batteryInfo.level < 10) {
  showLowBatteryWarning();
}

// Screen brightness adjustment
wx.getScreenBrightness({
  success(res) {
    console.log(`Current brightness: ${res.value}`);
    
    // Auto-adjust brightness based on time
    const hour = new Date().getHours();
    let targetBrightness = res.value;
    
    if (hour < 7 || hour > 22) {
      targetBrightness = Math.min(res.value, 0.3); // Dim for night
    }
    
    if (targetBrightness !== res.value) {
      wx.setScreenBrightness({
        value: targetBrightness,
        success() {
          console.log(`Brightness adjusted to ${targetBrightness}`);
        }
      });
    }
  }
});

// Keep screen on during video playback
function startVideoPlayback() {
  wx.setKeepScreenOn({
    keepScreenOn: true,
    success() {
      console.log('Screen will stay on during video');
    }
  });
}

function stopVideoPlayback() {
  wx.setKeepScreenOn({
    keepScreenOn: false,
    success() {
      console.log('Screen can now turn off normally');
    }
  });
}

Vibration Control

Device vibration patterns for haptic feedback.

/**
 * Trigger device vibration
 * @param option - Vibration configuration
 */
function vibrateLong(option?: VibrateLongOption): void;

/**
 * Trigger short vibration
 * @param option - Short vibration configuration
 */
function vibrateShort(option?: VibrateShortOption): void;

interface VibrateLongOption {
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface VibrateShortOption {
  /** Vibration type */
  type?: 'heavy' | 'medium' | 'light';
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

System Information

Comprehensive device and system information access.

/**
 * Get system information
 * @param option - System info configuration
 */
function getSystemInfo(option?: GetSystemInfoOption): void;

/**
 * Get system information synchronously
 */
function getSystemInfoSync(): SystemInfo;

/**
 * Get device information
 * @param option - Device info configuration
 */
function getDeviceInfo(option?: GetDeviceInfoOption): void;

/**
 * Get window information
 * @param option - Window info configuration
 */
function getWindowInfo(option?: GetWindowInfoOption): void;

interface SystemInfo {
  /** Device brand */
  brand: string;
  /** Device model */
  model: string;
  /** Device pixel ratio */
  pixelRatio: number;
  /** Screen width in pixels */
  screenWidth: number;
  /** Screen height in pixels */
  screenHeight: number;
  /** Window width in pixels */
  windowWidth: number;
  /** Window height in pixels */
  windowHeight: number;
  /** Status bar height */
  statusBarHeight: number;
  /** Language */
  language: string;
  /** WeChat version */
  version: string;
  /** System name */
  system: string;
  /** Platform */
  platform: string;
  /** Font size setting */
  fontSizeSetting: number;
  /** SDK version */
  SDKVersion: string;
  /** Benchmark score */
  benchmarkLevel: number;
  /** Album authorization */
  albumAuthorized: boolean;
  /** Camera authorization */
  cameraAuthorized: boolean;
  /** Location authorization */
  locationAuthorized: boolean;
  /** Microphone authorization */
  microphoneAuthorized: boolean;
  /** Notification authorization */
  notificationAuthorized: boolean;
  /** Phone calendar authorization */
  phoneCalendarAuthorized: boolean;
  /** Safe area */
  safeArea: {
    left: number;
    right: number;
    top: number;
    bottom: number;
    width: number;
    height: number;
  };
}

Usage Examples:

// Comprehensive system information
wx.getSystemInfo({
  success(res) {
    console.log('Device Info:');
    console.log(`Brand: ${res.brand}`);
    console.log(`Model: ${res.model}`);
    console.log(`System: ${res.system}`);
    console.log(`Screen: ${res.screenWidth}x${res.screenHeight}`);
    console.log(`Safe Area:`, res.safeArea);
    
    // Adapt UI based on device capabilities
    if (res.benchmarkLevel >= 1) {
      enableHighQualityGraphics();
    }
    
    // Handle notch/safe area
    if (res.safeArea.top > res.statusBarHeight) {
      adjustForNotch(res.safeArea);
    }
  }
});

// Quick sync access
const systemInfo = wx.getSystemInfoSync();
console.log(`Platform: ${systemInfo.platform}`);
console.log(`WeChat Version: ${systemInfo.version}`);

// Permission checking
if (systemInfo.cameraAuthorized && systemInfo.microphoneAuthorized) {
  enableVideoCall();
} else {
  requestCameraAndMicPermissions();
}

Event Listeners

// Memory warning listener
function onMemoryWarning(callback: (res: MemoryWarningInfo) => void): void;
function offMemoryWarning(callback?: (res: MemoryWarningInfo) => void): void;

// Theme change listener  
function onThemeChange(callback: (res: ThemeChangeInfo) => void): void;
function offThemeChange(callback?: (res: ThemeChangeInfo) => void): void;

interface MemoryWarningInfo {
  /** Warning level */
  level: 5 | 10 | 15;
}

interface ThemeChangeInfo {
  /** Current theme */
  theme: 'light' | 'dark';
}

Usage Examples:

// Memory management
wx.onMemoryWarning((res) => {
  console.log(`Memory warning level: ${res.level}`);
  
  switch (res.level) {
    case 5:
      // Trim caches
      clearImageCache();
      break;
    case 10:
      // Release non-essential resources
      releaseNonEssentialResources();
      break;
    case 15:
      // Critical memory situation
      emergencyMemoryCleanup();
      break;
  }
});

// Theme adaptation
wx.onThemeChange((res) => {
  console.log(`Theme changed to: ${res.theme}`);
  updateUITheme(res.theme);
});

docs

ai-ml-apis.md

app-page-lifecycle.md

bluetooth-nfc-apis.md

canvas-graphics.md

cloud-services.md

component-system.md

core-apis.md

device-hardware-apis.md

event-system.md

index.md

payment-apis.md

tile.json