### Request Example with Parameters Source: https://developers.weixin.qq.com/minigame/dev/api-backend/login/api_resetusersessionkey.html Shows a complete GET request example for resetting a user session key, including all necessary query parameters like openid, signature, and sig_method. ```HTTP GET https://api.weixin.qq.com/wxa/resetusersessionkey?access_token=ACCESS_TOKEN&openid=OPENID&signature=SIGNATURE&sig_method=hmac_sha256 ``` -------------------------------- ### Start VideoDecoder (Low Version Compatibility) Source: https://developers.weixin.qq.com/minigame/dev/api/media/video-decoder/VideoDecoder.html This example demonstrates how to start the VideoDecoder for versions prior to 2.16.1, which do not return Promises. It uses an event listener to handle the 'start' event and resolve a Promise for asynchronous control flow. ```javascript await new Promise(resolve => { decoder.on('start', resolve) decoder.start({ source: 'http://...', abortAudio: true, // 不需要音频 }) }) ``` -------------------------------- ### Upload File Example Source: https://developers.weixin.qq.com/minigame/dev/api/network/upload/wx.uploadFile.html Demonstrates how to upload a file selected by the user to a specified URL. It uses wx.chooseImage to get the file path and then calls wx.uploadFile to perform the upload. ```javascript wx.chooseImage({ success (res) { const tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址 filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' }, success (res){ const data = res.data //do something } }) } }) ``` -------------------------------- ### Example Usage Source: https://developers.weixin.qq.com/minigame/dev/api/media/audio/BufferSourceNode.html A basic example demonstrating how to create, configure, and play an audio buffer using BufferSourceNode. ```APIDOC ## Example Code ```javascript // Assuming audioCtx is an existing AudioContext const source = audioCtx.createBufferSource(); // Assuming AudioBuffer is a valid AudioBuffer object source.buffer = AudioBuffer; source.connect(audioCtx.destination); source.start(); ``` ``` -------------------------------- ### Get User Settings with Subscription Status Source: https://developers.weixin.qq.com/minigame/dev/api/open-api/setting/wx.getSetting.html This example shows how to use wx.getSetting with the `withSubscriptions` option set to true. This allows retrieving both the user's general authorization settings (`authSetting`) and their subscription message settings (`subscriptionsSetting`). The `subscriptionsSetting` includes the main switch status and individual item settings for different types of subscription messages. ```javascript wx.getSetting({ withSubscriptions: true, success (res) { console.log(res.authSetting) // res.authSetting = { // "scope.userInfo": true, // "scope.userLocation": true // } console.log(res.subscriptionsSetting) // res.subscriptionsSetting = { // mainSwitch: true, // 订阅消息总开关 // itemSettings: { // 每一项开关 // SYS_MSG_TYPE_INTERACTIVE: 'accept', // 小游戏系统订阅消息 // SYS_MSG_TYPE_RANK: 'accept' // zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'reject', // 普通一次性订阅消息 // ke_OZC_66gZxALLcsuI7ilCJSP2OJ2vWo2ooUPpkWrw: 'ban', // } // } } }) ``` -------------------------------- ### Request Example with Parameters Source: https://developers.weixin.qq.com/minigame/dev/api-backend/internet/api_getuserencryptkey.html A concrete example of an HTTPS GET request to the getUserEncryptKey API, including sample values for access token, signature, openid, and sig_method. ```http GET https://api.weixin.qq.com/wxa/business/getuserencryptkey?access_token=OsAoOMw4niuuVbfSxxxxxxxxxxxxxxxxxxx&signature=fefce01bfba4670c85b228e6ca2b493c90971e7c442f54fc448662eb7cd72509&openid=oGZUI0egBJY1zhBYw2KhdUfwVJJE&sig_method=hmac_sha256 ``` -------------------------------- ### Get Mini Program QR Code - HTTPS Request Example (Success) Source: https://developers.weixin.qq.com/minigame/dev/api-backend/qr-code/api_getqrcode.html Example of a successful HTTPS POST request to the `getwxacode` API, specifying the path, environment version, and width for the QR code. ```json { "path": "funpackage/questionsWall/questionInfo?question_id=22579", "env_version": "release", "width": 280 } ``` -------------------------------- ### Get Mini Program QR Code - Cloud Call Example (Success) Source: https://developers.weixin.qq.com/minigame/dev/api-backend/qr-code/api_getqrcode.html Example of using the WeChat server SDK to call the `wxacode.get` API for generating a QR code. This demonstrates a successful cloud-based invocation. ```javascript const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV, }) exports.main = async (event, context) => { try { const result = await cloud.openapi.wxacode.get({ "path": 'page/index/index', "width": 430 }) return result } catch (err) { return err } } ``` -------------------------------- ### Check User Authorization and Get Info Source: https://developers.weixin.qq.com/minigame/dev/api/open-api/user-info/wx.getUserInfo.html This example demonstrates how to check if a user has already authorized the app for avatar and nickname information using wx.getSetting. If authorized, it calls wx.getUserInfo; otherwise, it prompts the user to authorize via wx.createUserInfoButton. ```javascript // 通过 wx.getSetting 查询用户是否已授权头像昵称信息 wx.getSetting({ success (res){ if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称 wx.getUserInfo({ success: function(res) { console.log(res.userInfo) } }) } else { // 否则,先通过 wx.createUserInfoButton 接口发起授权 let button = wx.createUserInfoButton({ type: 'text', text: '获取用户信息', style: { left: 10, top: 76, width: 200, height: 40, lineHeight: 40, backgroundColor: '#ff0000', color: '#ffffff', textAlign: 'center', fontSize: 16, borderRadius: 4 } }) button.onTap((res) => { // 用户同意授权后回调,通过回调可获取用户头像昵称信息 console.log(res) }) } } }) ``` -------------------------------- ### MediaAudioPlayer.start() Source: https://developers.weixin.qq.com/minigame/dev/api/media/audio/MediaAudioPlayer.start.html Starts the audio player. This method returns a Promise that resolves when the player has finished starting. ```APIDOC ## MediaAudioPlayer.start() ### Description Starts the audio player. ### Method `start()` ### Returns - `Promise`: A Promise that resolves when the player has finished starting. ``` -------------------------------- ### HTTPS Request Example Source: https://developers.weixin.qq.com/minigame/dev/api-backend/safety-control-capability/api_getcheatdata This is an example of how to make an HTTPS GET request to the getCheatData API. Ensure you replace ACCESS_TOKEN with a valid token. ```HTTP GET https://api.weixin.qq.com/wxa/game/content_spam/get_cheat_data?access_token=ACCESS_TOKEN ``` -------------------------------- ### wx.getLaunchOptionsSync Source: https://developers.weixin.qq.com/minigame/dev/api Retrieves the parameters for the mini-game's cold start. ```APIDOC ## wx.getLaunchOptionsSync ### Description Gets the parameters for the mini-game's cold start. ### Method Sync ### Endpoint N/A (Client-side API) ``` -------------------------------- ### Canvas.toTempFilePathSync Example Source: https://developers.weixin.qq.com/minigame/dev/api/render/canvas/Canvas.toTempFilePathSync.html Use Canvas.toTempFilePathSync to get a temporary file path synchronously. This path can then be used, for example, to share the canvas content via wx.shareAppMessage. ```javascript let tempFilePath = canvas.toTempFilePathSync({ x: 10, y: 10, width: 200, height: 150, destWidth: 400, destHeight: 300 }) wx.shareAppMessage({ imageUrl: tempFilePath }) ``` -------------------------------- ### GameRecorder.start Source: https://developers.weixin.qq.com/minigame/dev/api/game-recorder/GameRecorder.html Starts recording the game screen. Accepts an object with configuration options. ```APIDOC ## GameRecorder.start ### Description Starts recording the game screen. ### Method `GameRecorder.start(Object object)` ### Parameters #### Request Body - **object** (Object) - Required - Configuration object for starting recording. (Specific properties not detailed in source) ``` -------------------------------- ### HTTPS Request Example Source: https://developers.weixin.qq.com/minigame/dev/api-backend/internet/api_getuserencryptkey.html This is an example of an HTTPS GET request to retrieve the user's encrypt key. Ensure all query parameters are correctly provided. ```http GET https://api.weixin.qq.com/wxa/business/getuserencryptkey?access_token=ACCESS_TOKEN&openid=OPENID&signature=SIGNATURE&sig_method=SIG_METHOD ``` -------------------------------- ### 请求示例 Source: https://developers.weixin.qq.com/minigame/dev/api-backend/login/api_code2session Example of a GET request to the code2session API with placeholder values. ```HTTP GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code ``` -------------------------------- ### wx.getLaunchOptionsSync Source: https://developers.weixin.qq.com/minigame/dev/api/base/app/life-cycle/wx.getLaunchOptionsSync.html Retrieves the parameters associated with the cold start of a mini-game. For hot start parameters, use wx.onShow or wx.getEnterOptionsSync. ```APIDOC ## wx.getLaunchOptionsSync() ### Description Gets the parameters when the mini-game is cold-started. Hot start parameters are obtained through the `wx.onShow` or `wx.getEnterOptionsSync` interface. ### Method `wx.getLaunchOptionsSync()` ### Returns An object containing launch parameters: - **scene** (number): The scene value for launching the mini-game. - **query** (Record): The query parameters for launching the mini-game. - **shareTicket** (string): The shareTicket, see Get More Forwarding Information for details. - **referrerInfo** (object): Referrer information. Returned when entering the mini-program from another mini-program, official account, or App. Otherwise, returns `{}`. (See notes below) - **appId** (string): The appId of the source mini-program, official account, or App. - **extraData** (object): Data passed from the source mini-program. Supported when scene is 1037 or 1038. - **hostExtraData** (string): Data passed by the host. Returned when running a mini-game in a third-party app. It is a JSON string that requires a `host_scene` field, indicating the scene value corresponding to the host app. - **chatType** (number): When opening a mini-program from a WeChat group/single chat, `chatType` indicates the specific WeChat group/single chat type. - 1: WeChat contact single chat - 2: Enterprise WeChat contact single chat - 3: Normal WeChat group chat - 4: Enterprise WeChat interoperable group chat ### Notes Some versions may return `undefined` when `referrerInfo` is absent. It is recommended to use `options.referrerInfo && options.referrerInfo.appId` for judgment. ``` -------------------------------- ### wx.startBeaconDiscovery Source: https://developers.weixin.qq.com/minigame/dev/api Starts searching for nearby Beacon devices. ```APIDOC ## wx.startBeaconDiscovery ### Description Starts searching for nearby Beacon devices. ### Method Not specified (assumed to be a JavaScript function call) ### Endpoint Not applicable (client-side API) ### Parameters None explicitly documented. ### Request Example ```javascript wx.startBeaconDiscovery({ // parameters if any }); ``` ### Response Details not specified. ``` -------------------------------- ### Get Mini Program QR Code - HTTP Request Example (Failure) Source: https://developers.weixin.qq.com/minigame/dev/api-backend/qr-code/api_getqrcode.html Example of a failed HTTPS POST request to the `getwxacode` API due to an invalid or empty path parameter. ```json { "path": "", "env_version": "release", "width": 280 } ``` -------------------------------- ### GameServerManager.startGame Source: https://developers.weixin.qq.com/minigame/dev/api/game-server-manager/GameServerManager.html Starts the game. ```APIDOC ## GameServerManager.startGame() ### Description Initiates the start of the game. ### Method `startGame` ``` -------------------------------- ### Example Usage Source: https://developers.weixin.qq.com/minigame/dev/api/network/request/RequestTask.html Demonstrates how to initiate a network request using wx.request and then use the returned RequestTask object to abort the request. ```APIDOC ## Example Code ```javascript const requestTask = wx.request({ url: 'test.php', // Example URL, not a real API endpoint data: { x: '', y: '' }, header: { 'content-type': 'application/json' }, success (res) { console.log(res.data) } }) requestTask.abort() // Aborts the request task ``` ``` -------------------------------- ### Example Usage Source: https://developers.weixin.qq.com/minigame/dev/api/network/upload/UploadTask.html Demonstrates how to initiate an upload and use UploadTask methods to manage it. ```APIDOC ## Example Code ```javascript const uploadTask = wx.uploadFile({ url: 'http://example.weixin.qq.com/upload', // Example URL, not a real API address filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' }, success (res) { const data = res.data // do something } }) uploadTask.onProgressUpdate((res) => { console.log('Upload Progress', res.progress) console.log('Bytes Sent', res.totalBytesSent) console.log('Total Bytes Expected', res.totalBytesExpectedToSend) }) uploadTask.abort() // Abort the upload task ``` ``` -------------------------------- ### Request Example for Check Session Key Source: https://developers.weixin.qq.com/minigame/dev/api-backend/login/api_checksessionkey.html Example of a GET request to the `checkSessionKey` API, including necessary query parameters like `access_token`, `signature`, `openid`, and `sig_method`. The signature is generated by signing an empty string with the `session_key` using HMAC-SHA256. ```http GET https://api.weixin.qq.com/wxa/checksession?access_token=OsAoOMw4niuuVbfSxxxxxxxxxxxxxxxxxxx&signature=fefce01bfba4670c85b228e6ca2b493c90971e7c442f54fc448662eb7cd72509&openid=oGZUI0egBJY1zhBYw2KhdUfwVJJE&sig_method=hmac_sha256 ``` -------------------------------- ### FileSystemManager.fstat Source: https://developers.weixin.qq.com/minigame/dev/api/file/FileSystemManager.fstat.html Gets the status information of a file using its file descriptor. This function is available starting from basic library version 2.16.1. ```APIDOC ## FileSystemManager.fstat(Object object) ### Description Gets the status information of a file. ### Method Not specified (callback style) ### Parameters #### Object object - **fd** (string) - Required - File descriptor obtained from FileSystemManager.open or FileSystemManager.openSync. - **success** (function) - Optional - Callback function for successful API invocation. - **fail** (function) - Optional - Callback function for failed API invocation. - **complete** (function) - Optional - Callback function executed after the API call completes (whether successful or failed). ##### object.success Callback Function ###### Object res - **stats** (Stats) - A Stats object containing the file's status information. ### Error Codes - **1300001**: operation not permitted - Operation not allowed (e.g., filePath expected a file but received a directory). - **1300002**: no such file or directory ${path} - File/directory does not exist, or the parent directory of the target file path does not exist. - **1300005**: Input/output error - Input/output stream is unavailable. - **1300009**: bad file descriptor - Invalid file descriptor. - **1300013**: permission denied - Permission error; the file is read-only or write-only. - **1300014**: Path permission denied - No permission for the provided path. - **1300020**: not a directory - The specified dirPath is not a directory; common when the parent path of the specified write path is a file. - **1300021**: Is a directory - The specified path is a directory. - **1300022**: Invalid argument - Invalid argument; check if length or offset is out of bounds. - **1300036**: File name too long - File name is too long. - **1300066**: directory not empty - Directory is not empty. - **1300201**: system error - System interface call failed. - **1300202**: the maximum size of the file storage limit is exceeded - Insufficient storage space, or file size exceeds the limit (100MB). - **1300203**: base64 encode error - Character encoding conversion failed (e.g., incorrect base64 format). - **1300300**: sdcard not mounted - Android sdcard mount failed. - **1300301**: unable to open as fileType - Unable to open file as fileType. - **1301000**: permission denied, cannot access file path - Target path has no access permission (usr directory). - **1301002**: data to write is empty - Data to write is empty. - **1301003**: illegal operation on a directory - Cannot perform this operation on a directory (e.g., the specified filePath is an existing directory). - **1301004**: illegal operation on a package directory - Cannot perform this operation on a code package directory. - **1301005**: file already exists ${dirPath} - File or directory with the same name already exists. - **1301006**: value of length is out of range - Provided length is invalid. - **1301007**: value of offset is out of range - Provided offset is invalid. - **1301009**: value of position is out of range - Position value is out of range. - **1301100**: store directory is empty - Store directory is empty. - **1301102**: unzip open file fail - Failed to open compressed file. - **1301103**: unzip entry fail - Failed to decompress a single file. - **1301104**: unzip fail - Decompression failed. - **1301111**: brotli decompress fail - Brotli decompression failed (e.g., specified compressionAlgorithm does not match the file's actual compression format). - **1301112**: tempFilePath file not exist - Specified tempFilePath file not found. - **1302001**: fail permission denied - The specified fd path does not have read/write permission. - **1302002**: excced max concurrent fd limit - Maximum number of fds reached. - **1302003**: invalid flag - Invalid flag. - **1302004**: permission denied when open using flag - Cannot open file using the flag. - **1302005**: array buffer does not exist - arrayBuffer not provided. - **1302100**: array buffer is readonly - arrayBuffer is read-only. ### Example Code ```javascript const fs = wx.getFileSystemManager() // Open file fs.open({ filePath: `${wx.env.USER_DATA_PATH}/hello.txt`, flag: 'a+', success(res) { // Get file status information fs.fstat({ fd: res.fd, success(res) { console.log(res.stats) } }) } }) ``` ``` -------------------------------- ### wx.startDeviceMotionListening Source: https://developers.weixin.qq.com/minigame/dev/api Starts listening for device motion changes. ```APIDOC ## wx.startDeviceMotionListening ### Description Starts listening for device motion changes. ### Method Not specified, typically invoked via a JavaScript API call. ### Endpoint Not applicable (SDK method). ### Parameters None explicitly listed in the source. ### Request Example ```javascript wx.startDeviceMotionListening({ success: function(res) { console.log('Device motion listening started'); } }); ``` ### Response #### Success Response - **success** (Boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### BLEPeripheralServer.startAdvertising Source: https://developers.weixin.qq.com/minigame/dev/api/device/bluetooth-peripheral/BLEPeripheralServer.html Starts broadcasting the locally created peripheral device to allow other devices to discover and connect to it. ```APIDOC ## BLEPeripheralServer.startAdvertising(Object Object) ### Description Starts advertising the local peripheral device. ### Method BLEPeripheralServer.startAdvertising ### Parameters #### Request Body - **Object** (Object) - Required - An object containing advertising parameters. ``` -------------------------------- ### Get All Match Rules API Response Example Source: https://developers.weixin.qq.com/minigame/dev/api-backend/gamematch/api_gamematch.getallmatchrule.html This example shows a successful response from the getAllMatchRule API. It includes the error code, error message, and a list of match rules, each with its ID, open state, team configuration, and game room information. ```JSON { "errcode": 0, "errmsg": "ok", "match_rule_list": [ { "match_id": "FD0PT4rKguEdK-L83RaJgdbchUCW8wjhSwgCku4CLQk", "open_state": 0, "team_count": 2, "team_member_count": 1, "need_room_service_info": 1, "game_room_info": { "game_tick": 30, "udp_reliability_strategy": 3, "start_percent": 100, "need_user_info": true, "game_last_time": 1800, "need_game_seed": true } } ] } ``` -------------------------------- ### HTTPS Call Example Source: https://developers.weixin.qq.com/minigame/dev/api-backend/login/api_resetusersessionkey.html Demonstrates how to make an HTTPS GET request to reset a user's session key. This method requires an access token. ```HTTP GET https://api.weixin.qq.com/wxa/resetusersessionkey?access_token=ACCESS_TOKEN ``` -------------------------------- ### wx.startAccelerometer Source: https://developers.weixin.qq.com/minigame/dev/api Starts listening for accelerometer data. ```APIDOC ## wx.startAccelerometer ### Description Starts listening for accelerometer data. ### Method Not specified, typically invoked via a JavaScript API call. ### Endpoint Not applicable (SDK method). ### Parameters None explicitly listed in the source. ### Request Example ```javascript wx.startAccelerometer({ success: function(res) { console.log('Accelerometer started'); } }); ``` ### Response #### Success Response - **success** (Boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Create Directory Asynchronously Source: https://developers.weixin.qq.com/minigame/dev/api/file/FileSystemManager.mkdirSync.html Demonstrates how to create a directory using the asynchronous mkdir method. Includes success and fail callbacks for handling the operation's outcome. ```javascript const fs = wx.getFileSystemManager() fs.mkdir({ dirPath: `${wx.env.USER_DATA_PATH}/example`, recursive: false, success(res) { console.log(res) }, fail(res) { console.error(res) } }) ``` -------------------------------- ### Get Chat Tool Info Source: https://developers.weixin.qq.com/minigame/dev/api/chattool/wx.getChatToolInfo.html Call the wx.getChatToolInfo API to retrieve group chat information. This example shows the basic usage with success and fail callbacks. ```javascript wx.getChatToolInfo({ success(res) { // res { errMsg: 'getChatToolInfo:ok', encryptedData: '', iv: '' } }, fail() { } }) ``` -------------------------------- ### wx.createBLEPeripheralServer Source: https://developers.weixin.qq.com/minigame/dev/api/device/bluetooth-peripheral/wx.createBLEPeripheralServer.html Creates a local Bluetooth low-energy peripheral server. Multiple servers can be created. Requires the 'scope.bluetooth' permission. ```APIDOC ## wx.createBLEPeripheralServer(Object object) ### Description Establishes a local Bluetooth low-energy peripheral server. Multiple servers can be created. ### Parameters #### object - **success** (function, optional): Callback function for successful API call. - **fail** (function, optional): Callback function for failed API call. - **complete** (function, optional): Callback function executed after the API call completes (whether successful or failed). ##### object.success Callback Function ### Parameters ###### res - **server** (BLEPeripheralServer): The peripheral server instance. ``` -------------------------------- ### HTTPS Call Example Source: https://developers.weixin.qq.com/minigame/dev/api-backend/lock-step/api_lock-step.getgameidentityinfo.html Demonstrates how to make an HTTPS GET request to retrieve game identity information. Ensure you replace ACCESS_TOKEN and ACCESS_INFO with valid values. ```HTTP GET https://api.weixin.qq.com/wxa/getwxagameidentityinfo?access_token=ACCESS_TOKEN&access_info=ACCESS_INFO ``` -------------------------------- ### Create and Use MediaAudioPlayer Source: https://developers.weixin.qq.com/minigame/dev/api/media/audio/wx.createMediaAudioPlayer.html Demonstrates how to create a MediaAudioPlayer, start it, add an audio source from a VideoDecoder, and manage its lifecycle including stopping and destroying. ```javascript // 创建视频解码器,具体参数见 createVideoDecoder 文档 const videoDecoder = wx.createVideoDecoder() // 创建媒体音频播放器 const mediaAudioPlayer = wx.createMediaAudioPlayer() // 启动视频解码器 videoDecoder.start() // 启动播放器 mediaAudioPlayer.start().then(() => { // 添加播放器音频来源 mediaAudioPlayer.addAudioSource(videoDecoder).then(res => { videoDecoder.getFrameData() // 建议在 requestAnimationFrame 里获取每一帧视频数据 console.log(res) }) // 移除播放器音频来源 mediaAudioPlayer.removeAudioSource(videoDecoder).then() // 停止播放器 mediaAudioPlayer.stop().then() // 销毁播放器 mediaAudioPlayer.destroy().then() // 设置播放器音量 mediaAudioPlayer.volume = 0.5 }) ``` -------------------------------- ### wx.createBLEPeripheralServer Source: https://developers.weixin.qq.com/minigame/dev/api Establishes a local service as a Bluetooth Low Energy peripheral device server. Multiple servers can be created. ```APIDOC ## wx.createBLEPeripheralServer ### Description Establishes a local service as a Bluetooth Low Energy peripheral device server. Multiple servers can be created. ### Method Not specified (assumed to be a JavaScript function call) ### Endpoint Not applicable (client-side API) ### Parameters None explicitly documented. ### Request Example ```javascript const server = wx.createBLEPeripheralServer(); ``` ### Response Details not specified. ``` -------------------------------- ### Share Emoji to Group Example Source: https://developers.weixin.qq.com/minigame/dev/api/chattool/wx.shareEmojiToGroup.html This snippet demonstrates how to share an emoji to a chat group after downloading it. It uses wx.downloadFile to get a temporary file path which is then passed to wx.shareEmojiToGroup. ```javascript wx.downloadFile({ url: 'https://res.wx.qq.com/wxdoc/dist/assets/img/demo.ef5c5bef.jpg', success: (res) => { wx.shareEmojiToGroup({ path: res.tempFilePath }) } }) ``` -------------------------------- ### wx.openSetting Source: https://developers.weixin.qq.com/minigame/dev/api Invokes the client's mini-program settings interface and returns the user's operation results. ```APIDOC ## wx.openSetting ### Description Invokes the client's mini-program settings interface and returns the user's operation results. ### Method Not specified (likely a client-side API call) ### Endpoint Not applicable (client-side API) ### Parameters None explicitly documented. ### Request Example None provided. ### Response None explicitly documented. ``` -------------------------------- ### GameServerManager.startStateService Source: https://developers.weixin.qq.com/minigame/dev/api/game-server-manager/GameServerManager.startStateService.html Starts the state management service. This service is required to get the online friend list and receive friend invitations. Available from basic library version 2.9.4. ```APIDOC ## GameServerManager.startStateService(object object) ### Description Starts the state management service. This service is required to get the online friend list and receive friend invitations. ### Parameters #### object object - **userState** (string) - Required - The custom status information for this player, with a length limit of 256 characters. - **success** (function) - Optional - Callback function for successful API invocation. - **fail** (function) - Optional - Callback function for failed API invocation. - **complete** (function) - Optional - Callback function executed after the API call completes (whether successful or failed). ### Return Value #### Promise A Promise that resolves with the success callback results or rejects with the fail callback results. ``` -------------------------------- ### wx.getGameRecorder Source: https://developers.weixin.qq.com/minigame/dev/api/game-recorder/wx.getGameRecorder.html Gets the global unique game screen recording object. This API is supported starting from basic library version 2.8.0. Compatibility processing is required for lower versions. ```APIDOC ## wx.getGameRecorder() ### Description Gets the global unique game screen recording object. ### Returns ### GameRecorder The global unique game screen recording object. ``` -------------------------------- ### GameServerManager.startStateService Source: https://developers.weixin.qq.com/minigame/dev/api/game-server-manager/GameServerManager.html Starts the state service for the game. ```APIDOC ## GameServerManager.startStateService(object) ### Description Initializes and starts the state service for managing game state. ### Method `startStateService` ### Parameters #### Object - **object** (object) - An object containing configuration for the state service. ``` -------------------------------- ### wx.startCompass Source: https://developers.weixin.qq.com/minigame/dev/api Starts listening for compass data. ```APIDOC ## wx.startCompass ### Description Starts listening for compass data. ### Method Not specified, typically invoked via a JavaScript API call. ### Endpoint Not applicable (SDK method). ### Parameters None explicitly listed in the source. ### Request Example ```javascript wx.startCompass({ success: function(res) { console.log('Compass started'); } }); ``` ### Response #### Success Response - **success** (Boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### VKFrame.getDepthBuffer() Source: https://developers.weixin.qq.com/minigame/dev/api/ai/visionkit/VKFrame.getDepthBuffer.html Gets the depth buffer information for each frame. Supported starting from Android WeChat 8.0.38 and iOS WeChat 8.0.39. Requires base library version 3.0.0 or higher. ```APIDOC ## VKFrame.getDepthBuffer() ### Description Gets the depth buffer information for each frame. Supported starting from Android WeChat 8.0.38 and iOS WeChat 8.0.39. Requires base library version 3.0.0 or higher for compatibility. ### Returns #### Object An object representing the frame's depth texture buffer. | Property | Type | Description | |----------------|-------------|-------------------------| | width | number | The width of the depth texture | | height | number | The height of the depth texture | | DepthAddress | ArrayBuffer | The depth texture buffer data | ``` -------------------------------- ### BufferSourceNode.start Source: https://developers.weixin.qq.com/minigame/dev/api Starts playback of the audio buffer. ```APIDOC ## BufferSourceNode.start ### Description Starts the playback of the audio buffer associated with this source node. ### Method BufferSourceNode.start ### Endpoint N/A (Method of a BufferSourceNode object) ### Parameters - **when** (number) - Optional - The time at which to start playback. - **offset** (number) - Optional - The offset in seconds from the start of the buffer. - **duration** (number) - Optional - The duration in seconds to play. ### Response None explicitly documented. ``` -------------------------------- ### Get Relation Friend List with Authorization Source: https://developers.weixin.qq.com/minigame/dev/api/open-api/data/wx.getRelationFriendList.html Demonstrates how to first authorize the scope.interactedUserInfo and then call wx.getRelationFriendList. Includes handling for user authorization denial and guiding the user to open settings. ```javascript // 提前授权(可选) wx.authorize({ scope: 'scope.interactedUserInfo', success: () => { // 用户同意授权,可以调用接口 getRelationFriends() }, fail: () => { console.log('用户拒绝授权') } }) function getRelationFriends() { wx.getRelationFriendList({ success: (res) => { console.log(res.encryptedData) }, fail: (res) => { console.error(res) // 判断是否为用户拒绝授权导致的失败,此处引导仅为示意,游戏可根据需求自行处理 // res = { errno: 0, err_code: "-12006", errMsg: "getRelationFriendList:fail auth deny" } if (res.errMsg && res.errMsg.indexOf('auth deny') !== -1) { // 用户此前已拒绝授权,可通过弹窗提示引导用户前往设置页面重新开启授权 wx.showModal({ title: '授权提示', content: '需要获取互动好友信息,请在设置中开启授权', success: (modalRes) => { if (modalRes.confirm) { wx.openSetting() } } }) } }, complete: (res) => console.log(res) }) } ``` -------------------------------- ### wx.getScreenBrightness Source: https://developers.weixin.qq.com/minigame/dev/api/device/screen/wx.getScreenBrightness.html Gets the current screen brightness. This API is available starting from basic library version 1.2.0. It supports Promise-style calls and is available on Windows, Mac, and HarmonyOS versions of WeChat. ```APIDOC ## wx.getScreenBrightness(Object object) > Basic library version 1.2.0 or later. Compatible with lower versions. > **Promise style call**: Supported > **WeChat Windows Edition**: Supported > **WeChat Mac Edition**: Supported > **WeChat HarmonyOS Edition**: Supported ## Function Description Gets the screen brightness. ## Parameters ### Object object | Attribute | Type | Default Value | Required | Description | |---|---|---|---|---| | success | function | | No | Callback function for successful API call | | fail | function | | No | Callback function for failed API call | | complete | function | | No | Callback function executed after the API call ends (whether successful or failed) | #### object.success Callback Function ##### Parameters ###### Object object | Attribute | Type | Description | |---|---|---| | value | number | Screen brightness value, ranging from 0 to 1, where 0 is the darkest and 1 is the brightest. | ## Notes * If the automatic brightness adjustment feature is enabled in the Android system settings, the screen brightness will adjust automatically based on light. This interface can only obtain the value before automatic brightness adjustment, not the real-time brightness value. ``` -------------------------------- ### wx.showLoading Source: https://developers.weixin.qq.com/minigame/dev/api Displays a loading prompt box. ```APIDOC ## wx.showLoading ### Description Displays a loading prompt box. ### Method Not specified (assumed to be a function call within the mini-game environment). ### Endpoint Not applicable (client-side API). ### Parameters Not specified in the source text. ### Request Example Not applicable. ### Response Not specified in the source text. ``` -------------------------------- ### Get Encrypted Data from Local Cache Source: https://developers.weixin.qq.com/minigame/dev/api/storage/wx.getStorage.html This example demonstrates how to retrieve encrypted data from local cache. Both setStorage and getStorage must have the 'encrypt' option set to true when using encrypted storage. ```javascript // 开启加密存储 wx.setStorage({ key: "key", data: "value", encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true success() { wx.getStorage({ key: "key", encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true success(res) { console.log(res.data) } }) } }) ``` -------------------------------- ### RecorderManager Usage Example Source: https://developers.weixin.qq.com/minigame/dev/api/media/recorder/RecorderManager.html This snippet demonstrates how to initialize and use the RecorderManager to start, pause, stop, and handle recording events. It includes configuration options for recording duration, sample rate, and format. ```javascript const recorderManager = wx.getRecorderManager() recorderManager.onStart(() => { console.log('recorder start') }) recorderManager.onPause(() => { console.log('recorder pause') }) recorderManager.onStop((res) => { console.log('recorder stop', res) const { tempFilePath } = res }) recorderManager.onFrameRecorded((res) => { const { frameBuffer } = res console.log('frameBuffer.byteLength', frameBuffer.byteLength) }) const options = { duration: 10000, sampleRate: 44100, numberOfChannels: 1, encodeBitRate: 192000, format: 'aac', frameSize: 50 } recorderManager.start(options) ``` -------------------------------- ### wx.getEnterOptionsSync Source: https://developers.weixin.qq.com/minigame/dev/api Retrieves the parameters for how the mini-game was opened, including cold and hot starts. ```APIDOC ## wx.getEnterOptionsSync ### Description Gets the parameters for how the mini-game was opened, including cold and hot starts. ### Method Sync ### Endpoint N/A (Client-side API) ``` -------------------------------- ### Get Mini Program Code (HTTP) Source: https://developers.weixin.qq.com/minigame/dev/api-backend/qr-code/api_getqrcode.html This section details how to call the getQRCode API using HTTPS. It includes request parameters, body structure, and examples for both successful and failed calls. Note that this API should be called from the server-side. ```APIDOC ## POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN ### Description This API is used to obtain a Mini Program code, suitable for business scenarios requiring a small number of codes. The generated codes are permanent and have quantity limitations. ### Method POST ### Endpoint https://api.weixin.qq.com/wxa/getwxacode ### Parameters #### Query Parameters - **access_token** (string) - Required - Interface call credential, can use access_token or authorizer_access_token. #### Request Body - **path** (string) - Required - The path of the Mini Program page to scan and enter. Maximum length is 1024 characters, cannot be empty. For mini games, you can pass only the query part to achieve parameter passing, e.g., passing "?foo=bar" will get {foo:"bar"} in the query parameter of the wx.getLaunchOptionsSync interface. - **width** (number) - Optional - The width of the QR code in pixels. Defaults to 430, minimum 280px, maximum 1280px. - **auto_color** (boolean) - Optional - Defaults to false. Automatically configures line color. If the color remains black, it indicates that configuring the main color is not recommended. - **line_color** (object) - Optional - Defaults to {"r":0,"g":0,"b":0}. Effective when auto_color is false. Uses RGB to set the color, e.g., {"r":"xxx","g":"xxx","b":"xxx"} in decimal representation. - **is_hyaline** (boolean) - Optional - Defaults to false. Whether a transparent background is needed. If true, a Mini Program code with a transparent background is generated. - **env_version** (string) - Optional - The version of the Mini Program to open. "release" for production, "trial" for trial, and "develop" for development. Defaults to production. ### Request Example ```json { "path": "funpackage/questionsWall/questionInfo?question_id=22579", "env_version": "release", "width": 280 } ``` ### Response #### Success Response (200) - **buffer** (buffer) - Image Buffer - **errcode** (number) - Error code - **errmsg** (string) - Error message #### Response Example ``` 图片 Buffer ``` ### Error Response Example ```json { "errcode": 40159, "errmsg": "invalid length for path or thedata is not json string" } ``` ### Notes - If the call is successful, the image binary content will be returned directly. If the request fails, JSON data will be returned. - POST parameters need to be converted to JSON strings; form submission is not supported. - The total number of codes generated with createQRCode is limited to 100,000. Please call with caution. The number of codes already generated can be found in the HTTP Header Num-Used. ``` -------------------------------- ### GameServerManager.startMatch Source: https://developers.weixin.qq.com/minigame/dev/api/game-server-manager/GameServerManager.html Initiates the matchmaking process. ```APIDOC ## GameServerManager.startMatch(object) ### Description Starts the process of finding suitable opponents or teammates. ### Method `startMatch` ### Parameters #### Object - **object** (object) - An object containing parameters for initiating matchmaking. ``` -------------------------------- ### wx.getLocation Source: https://developers.weixin.qq.com/minigame/dev/api/location/wx.getLocation.html Gets the current geographical location and speed. This API is no longer maintained starting from Basic Library version 3.0.1; please use wx.getFuzzyLocation instead. Supports Promise-style calls and requires user authorization for scope.userLocation. ```APIDOC ## wx.getLocation(Object object) ### Description Gets the current geographical location and speed. This API cannot be called after the user leaves the mini program. Enabling high-precision positioning will increase the API call duration; you can specify `highAccuracyExpireTime` as the timeout. The coordinate format used for map-related functions should be gcj02. Starting from Basic Library version `2.17.0`, `wx.getLocation` has added call frequency limits. ### Method `wx.getLocation` ### Parameters #### Object object | Attribute | Type | Default Value | Required | Description | Minimum Version | |---|---|---|---|---|---| | type | string | wgs84 | No | Returns gps coordinates in wgs84, or gcj02 coordinates usable by wx.openLocation | | | altitude | boolean | false | No | Returning altitude information requires higher precision and may slow down the API response speed | 1.6.0 | | isHighAccuracy | boolean | false | No | Enables high-precision positioning | 2.9.0 | | highAccuracyExpireTime | number | | No | Timeout for high-precision positioning (ms). Within the specified time, the highest precision will be returned. This value has an effect on high-precision positioning only if it is above 3000ms | 2.9.0 | | success | function | | No | Callback function for successful API calls | | | fail | function | | No | Callback function for failed API calls | | | complete | function | | No | Callback function executed after the API call completes (whether successful or failed) | | #### object.success Callback Function ##### Parameters ###### Object res | Attribute | Type | Description | Minimum Version | |---|---|---|---| | latitude | number | Latitude, ranging from -90 to 90, negative values indicate South latitude | | | longitude | number | Longitude, ranging from -180 to 180, negative values indicate West longitude | | | speed | number | Speed, in m/s | | | accuracy | number | Accuracy of the location, indicating closeness to the real location. Can be understood as 10 means within 10m of the real location; smaller is more accurate | | | altitude | number | Altitude, in meters | 1.2.0 | | verticalAccuracy | number | Vertical accuracy, in meters (Android cannot obtain this, returns 0) | 1.2.0 | | horizontalAccuracy | number | Horizontal accuracy, in meters | 1.2.0 | ### Request Example ```javascript wx.getLocation({ type: 'wgs84', success (res) { const latitude = res.latitude const longitude = res.longitude const speed = res.speed const accuracy = res.accuracy } }) ``` ### Notes * Starting from `2.17.0`, `wx.getLocation` has added call frequency limits. See announcement. * Location simulation in the tool uses IP positioning, which may have certain errors. The tool currently only supports gcj02 coordinates. * When using third-party services for reverse geocoding, please confirm the default coordinate system of the third-party service and perform coordinate conversion correctly. ``` -------------------------------- ### RecorderManager.start Source: https://developers.weixin.qq.com/minigame/dev/api/media/recorder/RecorderManager.html Starts an audio recording with specified options. This method initiates the recording process. ```APIDOC ## RecorderManager.start(Object object) ### Description Starts an audio recording. ### Method RecorderManager.start ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **object** (Object) - Required - Configuration object for the recording. - **duration** (number) - Optional - Maximum recording duration in milliseconds. - **sampleRate** (number) - Optional - Audio sample rate. - **numberOfChannels** (number) - Optional - Number of audio channels. - **encodeBitRate** (number) - Optional - Audio encoding bit rate. - **format** (string) - Optional - Audio format (e.g., 'aac', 'mp3'). - **frameSize** (number) - Optional - Size of recorded frames in bytes. ``` -------------------------------- ### Open Mini Program Settings Source: https://developers.weixin.qq.com/minigame/dev/api/open-api/setting/wx.openSetting.html This snippet demonstrates how to call wx.openSetting to open the mini-program settings interface. The success callback receives the user's authorization settings. ```javascript wx.openSetting({ success (res) { console.log(res.authSetting) // res.authSetting = { // "scope.userInfo": true, // "scope.userLocation": true // } } }) ``` -------------------------------- ### wx.getGameExptInfo Source: https://developers.weixin.qq.com/minigame/dev/api/data-analysis/wx.getGameExptInfo.html Given an array of experiment parameters, get the corresponding experiment parameter values. This function is supported starting from basic library version 3.8.8 and requires compatibility handling for lower versions. It does not support Promise-style calls. ```APIDOC ## wx.getGameExptInfo(Object options) ### Description Given an array of experiment parameters, get the corresponding experiment parameter values. ### Method `wx.getGameExptInfo` ### Parameters #### Object options Configuration parameters object. | Attribute | Type | Default Value | Required | Description | |---|---|---|---|---| | keyList | Array. | | Yes | Array of experiment parameters; if not provided, all experiment parameters will be retrieved. | | success | function | | No | Callback function for successful API call. | | fail | function | | No | Callback function for failed API call. | | complete | function | | No | Callback function executed after the API call ends (both success and failure). | #### options.success Callback Function ##### Parameters ###### Object res | Attribute | Type | Description | |---|---|---| | list | Array. | Result object, where each item is information related to the experiment. | ##### list Item Structure | Attribute | Type | Description | |---|---|---| | expt_id | number | Experiment ID, identifies the experiment. | | param_name | string | Parameter name. | | param_value | string | Parameter value. | ### Example Code ```javascript wx.getGameExptInfo({ keyList: ['experiment_key1', 'experiment_key2'], success(res) { res.list.forEach((expParam) => { console.log('Experiment ID:', expParam.expt_id); console.log('Parameter Name:', expParam.param_name); console.log('Parameter Value:', expParam.param_value); }) } }); ``` ```