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
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
App()- 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
Over 700 WeChat API functions bound across 32 Gleam modules, organized into these categories:
- Network: Request, WebSocket, TCP/UDP, mDNS, VoIP, advanced network (85+ functions)
- Media: Image, Video, Audio, Recorder, Live Streaming, Video editing (115+ functions)
- Device: Sensors, Battery, Screen, Bluetooth, NFC, WiFi, Beacon (80+ functions)
- Filesystem: File operations (40+ functions)
- UI: Interaction, feedback, animation, navigation bar, tabbar, background (35+ functions)
- WXML: Node query, component contexts, IntersectionObserver (40+ functions)
- Storage: Data storage, batch operations (10+ functions)
- Base: Routing, payment, system utilities, background fetch, crypto, router (60+ functions)
- Ads: Interstitial ads, rewarded video ads (15+ functions)
- And more: Worker, Editor, Analytics, Map, Share, Location, Page, App, Cache, Performance
Recent Additions (Phases 1-4): +231 new API bindings
- Phase 1: 64 functions (Sockets, mDNS, VoIP, MediaContainer, VideoDecoder)
- Phase 2: 96 functions (Voice, Beacon, BLE Peripheral, Extended Live, MediaAudioPlayer)
- Phase 3: 39 functions (System, Calendar, Encryption, Storage, Video Editing, IntersectionObserver)
- Phase 4: 32 functions (Ads, Advanced Network, Background Fetch, Crypto, Router)
Note: Some WeChat APIs like storage sync methods, app/page lifecycle event handlers, and window resize events are not yet implemented. See MISSING_APIS.md for details on remaining APIs.