weapp
Gleam bindings for wechat miniprogram, a.k.a weapp.
A project template and working demo which uses this package can be found at wechat_dev_tools
Installation
Add the package to your gleam project
gleam add weapp
Coverage Report
Generate an up-to-date coverage report:
./coverage.sh
This will scan all FFI files and generate a detailed COVERAGE_REPORT.md showing:
- Total wx functions covered (currently 375 functions, ~62% coverage)
- Breakdown by FFI module
- List of all covered functions
- Detection of duplicate implementations
- Recommendations for next steps
Features
This library contains bindings for many frequently used wechat APIs. Gleam makes it super easy to extend as many as one needs
- wx.request
- wx.requestPayment
- wx.login
- wx.setStorage
- wx.saveFile
- wx.openDocument
API Bindings
Toggle to view all WeChat API bindings by module
📚 Click to expand all API modules
Network Module (wechat/network)
HTTP, WebSocket, TCP/UDP, mDNS, VoIP
wx.request- HTTPS network requestwx.downloadFile- Download file resourcewx.uploadFile- Upload local resource to serverwx.connectSocket- Create WebSocket connectionwx.sendSocketMessage- Send WebSocket messagewx.closeSocket- Close WebSocket connectionwx.onSocketOpen- Listen for WebSocket connection openwx.onSocketMessage- Listen for WebSocket messagewx.onSocketError- Listen for WebSocket errorwx.onSocketClose- Listen for WebSocket close- RequestTask - Network request task management
- UploadTask - Upload task management
- DownloadTask - Download task management
- SocketTask - WebSocket task management
wx.createTCPSocket- Create TCP Socket instancewx.createUDPSocket- Create UDP Socket instance- TCPSocket methods:
bindWifi,connect,write,close, event handlers - UDPSocket methods:
bind,connect,send,write,setTTL,close, event handlers wx.startLocalServiceDiscovery- Start mDNS service discoverywx.stopLocalServiceDiscovery- Stop mDNS service discovery- mDNS event handlers:
onLocalServiceResolveFail,onLocalServiceLost,onLocalServiceFound,onLocalServiceDiscoveryStop wx.updateVoIPChatMuteConfig- Update VoIP mute configwx.subscribeVoIPVideoMembers- Subscribe VoIP video memberswx.setEnable1v1Chat- Enable 1v1 chatwx.joinVoIPChat- Join VoIP chat roomwx.join1v1Chat- Join 1v1 VoIP chatwx.exitVoIPChat- Exit VoIP chat- VoIP event handlers: state changes, members changed, speakers changed, interrupted
wx.getNetworkType- Get network typewx.getLocalIPAddress- Get local IP addresswx.onNetworkWeakChange,wx.offNetworkWeakChange- Network weak change events
Media Module (wechat/media)
Image, Audio, Video, Recorder, Live Streaming
Images:
wx.chooseImage- Select pictures from album or take photowx.previewImage- Preview imageswx.getImageInfo- Get image informationwx.saveImageToPhotosAlbum- Save image to albumwx.compressImage- Compress imagewx.chooseMessageFile- Select file from sessionwx.editImage- Edit imagewx.cropImage- Crop image
Videos:
wx.chooseVideo- Choose videowx.chooseMedia- Choose media (image/video)wx.getVideoInfo- Get video informationwx.saveVideoToPhotosAlbum- Save video to albumwx.compressVideo- Compress videowx.openVideoEditor- Open video editorwx.checkDeviceSupportHevc- Check HEVC supportwx.previewMedia- Preview media- VideoContext:
create_video_context, playback control, danmu, casting, picture-in-picture
Audio - Recorder:
wx.getRecorderManager- Get recorder manager- RecorderManager:
start,stop,pause,resume, event handlers
Audio - InnerAudio:
wx.createInnerAudioContext- Create inner audio context- InnerAudioContext: playback control, event handlers
Audio - Voice (旧API):
wx.playVoice,wx.pauseVoice,wx.stopVoice- AudioContext:
create_audio_context, playback control
Audio - WebAudio:
wx.createWebAudioContext- Create WebAudio context- WebAudioContext: nodes creation, audio processing methods
Audio - MediaAudioPlayer:
wx.createMediaAudioPlayer- Create media audio player- MediaAudioPlayer:
add_audio_source,destroy,remove_audio_source,start,stop
Audio - BackgroundAudio:
wx.getBackgroundAudioManager- Get background audio manager- BackgroundAudioManager: playback control, volume, seeking, event handlers
Live Streaming - LivePlayer:
wx.createLivePlayerContext- Create live player context- LivePlayer:
play,stop,mute, full screen, snapshot, casting, picture-in-picture, resume
Live Streaming - LivePusher:
wx.createLivePusherContext- Create live pusher context- LivePusher:
start,stop,pause,resume,switch_camera,snapshot - LivePusher BGM:
play_bgm,pause_bgm,resume_bgm,stop_bgm, volume control - LivePusher Audio:
set_mic_volume,set_zoom,get_max_zoom - LivePusher Effects:
apply_filter,clear_filters, makeup effects (blusher, eyebrow, eyeshadow, contour, lipstick), clear makeup, stickers, clear stickers - LivePusher Advanced:
create_offscreen_canvas,exit_picture_in_picture, custom renderer events,send_message,start_preview,stop_preview,toggle_torch
Camera:
wx.createCameraContext- Create camera context- CameraContext:
start_record,stop_record,take_photo,set_zoom, frame listener
Media Composition:
wx.createMediaContainer- Create media container- MediaContainer:
add_track,destroy,export,extract_data_source,remove_track
Video Decoding:
wx.createVideoDecoder- Create video decoder- VideoDecoder:
start,stop,seek,remove,get_frame_data, event handlers
Device Module (wechat/device)
Accelerometer, Compass, Gyroscope, Battery, Screen, Keyboard, WiFi, Bluetooth, NFC, Beacon
Sensors:
wx.startAccelerometer,wx.stopAccelerometer- Accelerometer controlwx.onAccelerometerChange,wx.offAccelerometerChange- Accelerometer eventswx.startCompass,wx.stopCompass- Compass controlwx.onCompassChange,wx.offCompassChange- Compass eventswx.startGyroscope,wx.stopGyroscope- Gyroscope controlwx.onGyroscopeChange,wx.offGyroscopeChange- Gyroscope eventswx.startDeviceMotionListening,wx.stopDeviceMotionListening- Device motion controlwx.onDeviceMotionChange,wx.offDeviceMotionChange- Device motion events
Battery:
wx.getBatteryInfo- Get battery informationwx.onBatteryInfoChange- Battery info change event
Screen:
wx.setScreenBrightness,wx.getScreenBrightness- Screen brightnesswx.setKeepScreenOn- Keep screen onwx.onUserCaptureScreen,wx.offUserCaptureScreen- Screen capture eventwx.onScreenRecordingStateChanged,wx.offScreenRecordingStateChanged- Screen recording eventswx.onGeneratePoster,wx.offGeneratePoster- Generate poster eventwx.getScreenRecordingState- Get screen recording state
Keyboard:
wx.hideKeyboard- Hide keyboardwx.getSelectedTextRange- Get selected text rangewx.onKeyboardHeightChange,wx.offKeyboardHeightChange- Keyboard height events
Memory:
wx.onMemoryWarning,wx.offMemoryWarning- Memory warning events
WiFi:
wx.startWifi,wx.stopWifi- WiFi controlwx.getConnectedWifi- Get connected WiFiwx.getWifiList- Get WiFi listwx.setWifiList- Set WiFi listwx.onWifiConnected,wx.offWifiConnected- WiFi connected eventwx.onGetWifiList,wx.offGetWifiList- WiFi list event
Bluetooth - General:
wx.openBluetoothAdapter,wx.closeBluetoothAdapter- Bluetooth adapter controlwx.getBluetoothAdapterState- Get adapter statewx.startBluetoothDevicesDiscovery,wx.stopBluetoothDevicesDiscovery- Device discoverywx.getBluetoothDevices,wx.getConnectedBluetoothDevices- Get deviceswx.onBluetoothDeviceFound,wx.offBluetoothDeviceFound- Device found eventwx.onBluetoothAdapterStateChange,wx.offBluetoothAdapterStateChange- Adapter state event
Bluetooth - Low Energy (BLE) Central:
wx.createBLEConnection,wx.closeBLEConnection- BLE connection controlwx.getBLEDeviceServices,wx.getBLEDeviceCharacteristics- Get services/characteristicswx.readBLECharacteristicValue,wx.writeBLECharacteristicValue- Read/write characteristicwx.notifyBLECharacteristicValueChange- Enable characteristic notificationwx.onBLEConnectionStateChange,wx.offBLEConnectionStateChange- Connection state eventwx.onBLECharacteristicValueChange,wx.offBLECharacteristicValueChange- Characteristic value event
Bluetooth - Low Energy (BLE) Peripheral:
wx.createBLEPeripheralServer- Create BLE peripheral serverwx.onBLEPeripheralConnectionStateChanged,wx.offBLEPeripheralConnectionStateChanged- Peripheral connection event- BLEPeripheralServer:
add_service,remove_service,start_advertising,stop_advertising,write_characteristic_value - BLEPeripheralServer characteristic event handlers: read request, subscribed, unsubscribed, write request
Beacon:
wx.startBeaconDiscovery,wx.stopBeaconDiscovery- Beacon discovery controlwx.getBeacons- Get discovered beaconswx.onBeaconUpdate,wx.offBeaconUpdate- Beacon update eventwx.onBeaconServiceChange,wx.offBeaconServiceChange- Beacon service change event
NFC:
wx.getNFCAdapter- Get NFC adapter- NFCAdapter:
start_discovery,stop_discovery, event handlers
Filesystem Module (wechat/filesystem)
File system operations
wx.getFileSystemManager- Get file system manager- FileSystemManager:
access,mkdir,readFile,writeFile,unlink,rename,copyFile,stat, and 30+ more methods - File system methods: read/write, directory operations, file info, compression, unzip
Map Module (wechat/map)
Map context and location
wx.createMapContext- Create map context- MapContext:
include_points,move_to_location,translate_marker, add markers/layers, remove operations wx.getLocation- Get current locationwx.chooseLocation- Choose locationwx.openLocation- Open location in map app
Cache Module (wechat/cache)
Cache manager for request/response caching
wx.createCacheManager- Create cache manager- CacheManager:
add_rule,add_rules,clear_caches,clear_rules,delete_cache,delete_caches,delete_rule,delete_rules,match,start,stop, event handlers
Performance Module (wechat/performance)
Performance monitoring and metrics
wx.getPerformance- Get performance object- Performance:
create_observer,get_entries,get_entries_by_type,get_entries_by_name,set_buffer_size - PerformanceObserver:
observe,disconnect - Performance methods:
mark,measure,clear_marks,clear_measures
UI Module (wechat/ui)
UI interaction and animation
Feedback:
wx.showToast,wx.hideToast- Toast displaywx.showModal- Modal dialogwx.showLoading,wx.hideLoading- Loading indicatorwx.showActionSheet- Action sheet
Navigation Bar:
wx.setNavigationBarTitle- Set titlewx.setNavigationBarColor- Set colorwx.showNavigationBarLoading,wx.hideNavigationBarLoading- Loading
TabBar:
wx.setTabBarItem,wx.setTabBarStyle- Set TabBar item/stylewx.showTabBarRedDot,wx.hideTabBarRedDot- TabBar red dotwx.setTabBarBadge,wx.removeTabBarBadge- TabBar badge
Background:
wx.setBackgroundColor,wx.setBackgroundTextStyle- Set background
Animation:
wx.createAnimation- Create animation- Animation:
rotate,scale,translate,skew,opacity,width,height, background color,export,step
WXML Module (wechat/wxml)
Node query and component contexts
SelectorQuery:
wx.createSelectorQuery- Create selector query- SelectorQuery:
in,select,select_all,select_viewport,exec - NodesRef:
bounding_client_rect,scroll_offset,fields,context,node,ref
Component Contexts:
- ScrollViewContext:
close_refresh,close_two_level,scroll_to,scroll_into_view,trigger_refresh,trigger_two_level - EditorContext:
set_contents,get_contents,clear,blur,focus,format,insert_text,get_selection_text,scroll_into_view,status,ready
IntersectionObserver:
wx.createIntersectionObserver- Create intersection observer- IntersectionObserver:
disconnect,observe,relative_to,relative_to_viewport
Video Module (wechat/video)
Video player context
wx.createVideoContext- Create video context- VideoContext:
play,pause,stop,seek,playback_rate, full screen, status bar, danmu, casting, picture-in-picture
Storage Module (wechat/storage)
Storage and batch operations
Basic Storage:
wx.setStorage,wx.getStorage,wx.removeStorage,wx.clearStorage- Async storagewx.getStorageInfo- Storage info
Advanced Storage:
wx.createBufferURL,wx.revokeBufferURL- Buffer URL managementwx.batchSetStorage,wx.batchSetStorageSync- Batch setwx.batchGetStorage,wx.batchGetStorageSync- Batch get
Open Module (wechat/open)
Open APIs - login, user info, calendar, contact, phone, SMS
User:
wx.login- Get login codewx.checkSession- Check sessionwx.getUserInfo,wx.getUserProfile- Get user infowx.getSetting,wx.openSetting- Settings managementwx.authorize- Request authorization
Calendar & Contact:
wx.addPhoneRepeatCalendar,wx.addPhoneCalendar- Add calendar eventwx.chooseContact- Choose contactwx.addPhoneContact- Add contact
Phone & SMS:
wx.makePhoneCall- Make phone callwx.sendSms- Send SMS
Mini Program Navigation:
wx.navigateToMiniProgram,wx.navigateBackMiniProgram,wx.exitMiniProgram- Mini program navigation
Other:
wx.chooseAddress- Choose addresswx.requestSubscribeMessage- Subscribe message
Base Module (wechat/base)
Base APIs - routing, payment, clipboard, vibrate, scan code, encryption
Routing:
wx.navigateTo,wx.redirectTo,wx.switchTab,wx.reLaunch,wx.navigateBack- Page navigation
Payment:
wx.requestPayment- Request WeChat payment
System:
wx.setClipboardData,wx.getClipboardData- Clipboard operationswx.vibrateShort,wx.vibrateLong- Vibrationwx.scanCode- Scan QR codewx.getRandomValues- Cryptographically secure random
Update:
wx.getUpdateManager- Get update manager- UpdateManager:
apply_update,on_check_for_update,on_update_failed,on_update_ready
Background Fetch:
wx.setBackgroundFetchToken- Set background fetch tokenwx.onBackgroundFetchData- Listen for background fetch datawx.getBackgroundFetchToken- Get background fetch tokenwx.getBackgroundFetchData- Get background fetch data
Subpackage Pre-download:
wx.preDownloadSubpackage- Pre-download subpackage
User Crypto Manager:
wx.getUserCryptoManager- Get user crypto manager- UserCryptoManager:
get_latest_user_key,get_random_values
Custom Router:
wx.router- Get custom router- Router:
add_route_builder,get_route_context,remove_route_builder
Other:
wx.showTabbar,wx.hideTabbar- Tabbar controlwx.showLoading,wx.hideLoading- Loadingwx.showToast- Toast
Worker Module (wechat/worker)
Web Worker for background processing
wx.createWorker- Create worker- Worker:
post_message,terminate, event handlers (on_error,on_message,on_process_killed)
Editor Module (wechat/editor)
Rich text editor context
wx.createEditorContext- Create editor context- EditorContext:
set_contents,get_contents,clear,blur,focus,format,insert_text,get_selection_text,scroll_into_view,status,ready
App Module (wechat/app)
App constructor and utilities
wx.getAppBaseInfo- Get app base infoApp()- App constructorgetApp()- Get app instance- Global utilities:
setTimeout,clearTimeout,setInterval,clearInterval,decodeURIComponent
Page Module (wechat/page)
Page constructor and data management
Page()- Page constructorgetCurrentPages()- Get current pages stacksetData()- Set page data for renderingselectComponent()- Select component- Pull down refresh:
wx.startPullDownRefresh,wx.stopPullDownRefresh(in UI module)
Analytics Module (wechat/analytics)
Analytics and monitoring
wx.reportEvent- Report eventwx.reportMonitor- Report monitoring data
Payment Module (wechat/payment)
Payment APIs
wx.requestPayment- Request WeChat paymentwx.chooseAddress- Choose address (billing)
Location Module (wechat/location)
Location and map
wx.getLocation- Get locationwx.chooseLocation- Choose locationwx.openLocation- Open location in map
Share Module (wechat/share)
Share APIs
wx.showShareMenu,wx.hideShareMenu- Share menu controlwx.updateShareMenu- Update share menuwx.shareAppMessage- Share app messagewx.onShareAppMessage,wx.offShareAppMessage- Share event handlers
Network Module (wechat/network)
Network APIs (duplicate reference)
(See Network Module above)
Audio Module (wechat/audio)
Audio APIs (duplicate reference)
(See Media Module - Audio section above)
Ad Module (wechat/ad)
Ad components
wx.createInterstitialAd- Create interstitial ad- InterstitialAd:
destroy,load,show, event handlers (on_close,on_error,on_load) wx.createRewardedVideoAd- Create rewarded video ad- RewardedVideoAd:
destroy,load,show, event handlers (on_close,on_error,on_load) wx.getShowSplashAdStatus- Get splash ad status
Total Functions Count
375 wx API functions bound across 32 Gleam modules using 12 FFI modules:
By FFI Module (wx functions):
- wechat_base_ffi.mjs (104 functions): Login, storage, payment, navigation, system utilities, background fetch, crypto, router, calendar, contact, phone, scan, clipboard, vibrate, app events (on/off), lifecycle, performance, privacy
- wechat_device_ffi.mjs (93 functions): Sensors (accelerometer, compass, gyroscope), battery, screen, Bluetooth (general, BLE, peripheral), NFC, WiFi, Beacon, keyboard, memory, accessibility
- wechat_network_ffi.mjs (45 functions): Request, WebSocket, TCP/UDP, mDNS, VoIP, network events
- wechat_media_ffi.mjs (37 functions): Image, Video, Audio (inner, voice, web, background, media audio), Recorder, Live streaming, Camera, MediaContainer, VideoDecoder
- wechat_ui_ffi.mjs (52 functions): Interaction (toast, modal, loading, action sheet), navigation bar, tabbar, background, animation, pull down refresh, share menu, window, scroll
- wechat_canvas_ffi.mjs (9 functions): createCanvasContext, canvasGetImageData, canvasPutImageData, canvasToTempFilePath, createOffscreenCanvas, requestAnimationFrame, cancelAnimationFrame, createImage, createImageData
- wechat_wxml_ffi.mjs (2 functions): createSelectorQuery, createIntersectionObserver
- wechat_filesystem_ffi.mjs (2 functions): getFileSystemManager, saveFileToDisk
- wechat_map_ffi.mjs (1 function): createMapContext
- wechat_cache_ffi.mjs (1 function): createCacheManager
- wechat_performance_ffi.mjs (varies): getPerformance and related functions
- wechat_ffi.mjs (18 functions): System info (getAppBaseInfo, getSystemInfo, getSystemInfoSync, getSystemInfoAsync, getSystemSetting, getDeviceInfo, getWindowInfo, getAppAuthorizeSetting, getAccountInfoSync, getLaunchOptionsSync, getEnterOptionsSync, getDeviceBenchmarkInfo, getSkylineInfo, getSkylineInfoSync, getRendererUserAgent), utilities (canIUse, base64ToArrayBuffer, arrayBufferToBase64)
By Gleam Module (public API coverage):
- wechat/base - System, routing, payment, clipboard, vibrate, scan, update, background fetch, crypto, router
- wechat/device - All device sensors, Bluetooth, NFC, WiFi, Beacon
- wechat/network - Request, WebSocket, TCP/UDP, mDNS, VoIP
- wechat/media - All image, video, audio, recorder, live streaming APIs
- wechat/ui - All UI interaction, feedback, navigation bar, tabbar, animation
- wechat/wxml - Node query, intersection observer
- wechat/canvas - Canvas context creation
- wechat/filesystem - File system manager
- wechat/map - Map context and location
- wechat/app - App constructor, system info (getAppBaseInfo, getSystemInfo sync/async, getDeviceInfo, getWindowInfo, etc.), utilities (canIUse, base64 conversion)
- wechat/page - Page constructor and data management
- wechat/storage - Storage operations
- wechat/cache - Cache manager
- wechat/performance - Performance monitoring
- wechat/audio - Audio APIs (inner audio, voice, background audio)
- wechat/background_audio - Background audio manager
- wechat/video - Video player context
- wechat/recorder - Audio recorder manager
- wechat/open - Login, user info, calendar, contact, phone, SMS
- wechat/share - Share APIs
- wechat/payment - Payment APIs
- wechat/worker - Web Worker
- wechat/ad - Ad components
- wechat/location - Location and map
- wechat/keyboard - Keyboard operations
- wechat/screen - Screen operations
- wechat/battery - Battery information
- wechat/component - Component utilities
- wechat/object - Object utilities
- wechat/analytics - Analytics and monitoring
- wechat/app_event - App lifecycle events
Note: See MISSING_APIS.md for details on remaining APIs (~225+ wx functions not yet bound).