### Install miniprogram-ci Source: https://developers.weixin.qq.com/minigame/dev/devtools/ci Installs the miniprogram-ci package using npm. This is the first step to start using the library in your project. ```bash npm install miniprogram-ci --save ``` -------------------------------- ### Complete Dockerfile Example with SG11 Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/scene/build/phpsg11 A full Dockerfile example demonstrating the integration of the SG11 extension installation. It sets up the PHP environment, installs the extension, copies application code, and configures the Apache server. ```dockerfile FROM php:7.3-apache RUN PHP_VERSION=$(php -v | head -n1 | cut -d' ' -f2 | cut -d. -f1-2) \ && mkdir -p /tmp/sourceguardian \ && cd /tmp/sourceguardian \ && curl -Os https://www.sourceguardian.com/loaders/download/loaders.linux-x86_64.tar.gz \ && tar xzf loaders.linux-x86_64.tar.gz \ && cp ixed.${PHP_VERSION}.lin "$(php -i | grep '^extension_dir =' | cut -d' ' -f3)/sourceguardian.so" \ && echo "extension=sourceguardian.so" > /usr/local/etc/php/conf.d/15-sourceguardian.ini \ && rm -rf /tmp/sourceguardian COPY index.php /var/www/html/ RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini" CMD ["apachectl", "-DFOREGROUND"] ``` -------------------------------- ### Install Miniprogram Automator SDK Source: https://developers.weixin.qq.com/minigame/dev/devtools/auto/quick-start Installs the miniprogram-automator SDK as a development dependency using npm. ```bash npm i miniprogram-automator --save-dev ``` -------------------------------- ### Install Python Testing Framework SDK Source: https://developers.weixin.qq.com/minigame/dev/minigame-testtool/setup This command installs the Python SDK for the mini_game_test framework. It uses pip to install the wheel file, ignoring any already installed versions to ensure a clean installation. ```shell pip install mini_game_test_sdk-x.x.x-py2-none-any.whl --user --upgrade --ignore-installed ``` -------------------------------- ### Initial Dockerfile Example for Alpine Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/scene/build/speed This Dockerfile uses an Alpine base image to build a Python application. It configures package repositories, installs Python and pip, sets the timezone, adds CA certificates, copies the project files, sets the working directory, installs dependencies, exposes a port, and defines the entry point. ```Dockerfile FROM alpine:3.14 RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tencent.com/g' /etc/apk/repositories \ && apk add --update --no-cache python3 py3-pip \ && rm -rf /var/cache/apk/* ENV TZ Asia/Shanghai RUN apk add tzdata && cp /usr/share/zoneinfo/${TZ} /etc/localtime && echo ${TZ} > /etc/timezone RUN apk add ca-certificates COPY . /app WORKDIR /app RUN pip config set global.index-url http://mirrors.cloud.tencent.com/pypi/simple \ && pip config set global.trusted-host mirrors.cloud.tencent.com \ && pip install --upgrade pip \ && pip install --user -r requirements.txt EXPOSE 80 CMD ["python3", "run.py", "0.0.0.0", "80"] ``` -------------------------------- ### JavaScript WebSocket Client Example Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/development/websocket/web This JavaScript code demonstrates how to establish a WebSocket connection, send messages, and handle incoming messages and connection closing events for a WEB client. ```javascript ``` -------------------------------- ### Example: Displaying User Input (WeChat Mini Game) Source: https://developers.weixin.qq.com/minigame/introduction/gamemaker/minigame/plugins/keyboard Illustrates how to get the value entered by the user in the keyboard and display it within a WeChat Mini Game. ```WeChat Mini Game Blocks 获取并展现用户输入的值: -> [键盘的值] ``` -------------------------------- ### Install CLI Tool Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/cli Instructions for installing the Weixin Cloud Hosting CLI tool using npm. ```APIDOC ## Install CLI Tool To install the CLI tool, you need to have `npm` installed. Refer to the official npm documentation for installation instructions. ### Command ``` npm install -g @wxcloud/cli ``` ``` -------------------------------- ### Solid Behavior Example with Direction Control (Wall) Source: https://developers.weixin.qq.com/minigame/introduction/gamemaker/minigame/behaviors/solid Demonstrates how to use the Solid behavior in conjunction with the Direction Control behavior to create a wall that blocks movement. This setup is common for defining boundaries in minigames. ```Markdown demo ``` -------------------------------- ### 带登录态访问云开发数据库 Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/web/minimal-example/html 此函数演示了如何在已登录状态下,使用云开发 SDK 访问数据库。它通过 `window.instance` 获取云开发实例,并调用 `database().collection('test').get()` 来获取 'test' 集合的数据。使用 `runWithLogs` 辅助函数来记录操作过程。 ```javascript window.accessResource = async () => { try { const c = window.instance await runWithLogs(() => c.database().collection('test').where({}).get(), `start db`, `db res`) } catch (e) { console.error('logs', `error: ${e}`) } } ``` -------------------------------- ### 云函数默认实例初始化 (JavaScript) Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/reference-sdk-api/init/server 使用 `cloud.init` 方法初始化默认云函数实例。需要传入一个包含 `env` 字段的 `options` 对象来指定要访问的云环境 ID。支持设置 API 超时时间。 ```javascript const cloud = require('wx-server-sdk') cloud.init({ env: 'test-x1dzi' }) ``` -------------------------------- ### JavaScript: Real-time Log Manager Initialization for Plugins Source: https://developers.weixin.qq.com/minigame/dev/guide/runtime/debug/realtimelog Demonstrates how to get an instance of the real-time log manager for WeChat Mini Program plugins using `wx.getRealtimeLogManager()` starting from base library version 2.16.0. ```javascript const logManager = wx.getRealtimeLogManager() ``` -------------------------------- ### 判断小程序是否来源于兜底分享 Source: https://developers.weixin.qq.com/minigame/dev/guide/open-ability/ad/rewarded-video-ad 可以通过 `wx.getLaunchOptionsSync()` 获取小程序启动参数,并检查 `query` 参数中是否包含 `wxad_fallback_share=1` 来判断是否来源于 1004 兜底分享。 ```javascript // 示例:在小程序入口文件或需要的地方调用 const launchOptions = wx.getLaunchOptionsSync(); if (launchOptions.query && launchOptions.query.wxad_fallback_share === '1') { console.log('此次打开来源于 1004 兜底分享'); } ``` -------------------------------- ### 云函数默认实例动态环境初始化 (JavaScript) Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/reference-sdk-api/init/server 使用 `cloud.init` 方法并设置 `env` 为 `cloud.DYNAMIC_CURRENT_ENV` 来初始化默认实例,使云函数默认访问其当前所在的环境。这简化了跨环境的数据库、存储等请求。 ```javascript const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) exports.main = async (event) => { const { ENV, OPENID, APPID } = cloud.getWXContext() // 如果云函数所在环境为 abc,则下面的调用就会请求到 abc 环境的数据库 const dbResult = await cloud.database().collection('test').get() return { dbResult, ENV, OPENID, APPID, } } ``` -------------------------------- ### Web SDK API Overview Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/web/sdk Provides an overview of the Web SDK's API, highlighting differences from the Mini Program API and demonstrating instantiation and function calls. ```APIDOC ## Web SDK API Differences ### Description This section details the differences between the Web SDK API and the Mini Program API. Key differences include the global `cloud` object, instantiation using `new cloud.Cloud()`, and variations in `uploadFile` and `downloadFile` parameters and return types. ### Method N/A (Informational) ### Endpoint N/A (Informational) ### Parameters N/A (Informational) ### Request Example ```javascript // New cloud instance declaration var c1 = new cloud.Cloud({ // Required, indicates no-login mode identityless: true, // Resource AppID resourceAppid: 'wxe0e2656d74f0bff3', // Resource environment ID resourceEnv: 'test-f96b31', }); // Cross-account calls must wait for init to complete await c1.init(); // Normal usage of resource's authorized cloud resources c1.callFunction({ name: '', data: {}, complete: console.warn, }); ``` ### Response #### Success Response (200) N/A (Informational) #### Response Example N/A (Informational) ``` -------------------------------- ### 在云函数中安装 SDK Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/model/init-sdk 在云函数目录下安装 `@cloudbase/wx-cloud-client-sdk` 和 `wx-server-sdk` 依赖,以便在云函数中使用云开发 SDK。 ```bash npm install --save @cloudbase/wx-cloud-client-sdk wx-server-sdk ``` -------------------------------- ### Get WeChat Steps Data Example Source: https://developers.weixin.qq.com/minigame/introduction/gamemaker/minigame/plugins/wechatrun This code snippet demonstrates how to use the WeChat Steps plugin to fetch user's step data. It handles both successful retrieval, updating a text element with the step count, and failure, displaying an error message. ```script when the **Basic Text Sprite** is clicked { try to get the user's WeChat steps for yesterday. if successful { change the content of **Basic Text Sprite** to **the returned WeChat step data**. } if failed { change the content of **Basic Text Sprite** to **Failed to get WeChat steps**. } } ``` -------------------------------- ### Setup and Qualification Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/weixin/pay Steps to set up WeChat Pay with WeChat Cloud Hosting, including obtaining a merchant ID, linking it to your Mini Program, and configuring it in the Cloud Hosting console. ```APIDOC ## Setup and Qualification 1. **Obtain WeChat Pay Merchant ID**: Register for a WeChat Pay merchant account. 2. **Follow "WeChat Pay Merchant Assistant" Official Account**: Subscribe to the official account for instructions. 3. **Associate Merchant ID with Mini Program AppID**: Link your merchant ID to your Mini Program's AppID. 4. **Configure in Cloud Hosting Console**: Navigate to WeChat Cloud Hosting Console -> Settings -> Other Settings -> WeChat Pay Configuration and bind your merchant ID. 5. **Administrator Confirmation**: The super administrator of the merchant account will receive a confirmation message in WeChat to authorize the binding. **Important Notes on Binding:** - The binding is between the merchant ID and the Mini Program, not specific Cloud Hosting environments. - This binding persists even if the Cloud Hosting environment is deleted or reused by other Mini Programs. - To unbind, perform the action in the Mini Program backend or the WeChat Pay console. ## Resource Reuse Configuration If a Mini Program (A) uses the Cloud Hosting environment of another Mini Program (B), the payment setup should be done within Mini Program B's resource reuse environment. This configuration is for Mini Program A, and the relationship remains "Merchant ID - Mini Program A". ``` -------------------------------- ### Install Python Dependencies for Image Recognition Source: https://developers.weixin.qq.com/minigame/dev/minigame-testtool/setup This command installs Python dependencies from a requirements.txt file, which is necessary for image recognition APIs within the testing framework. It ensures all required packages are installed or upgraded. ```shell pip install -r requirements.txt --user --upgrade --force-reinstall ``` -------------------------------- ### Initialize Cloud Development SDK Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/model/quickstart Instructions on how to download and initialize the WeChat Cloud Development SDK in your Mini Program. ```APIDOC ## Initialize Cloud Development SDK ### Method JavaScript ### Endpoint N/A ### Description Download the SDK file and integrate it into your Mini Program's `app.js`. ### Request Example ```javascript const { init } = require("./wxCloudClientSDK.umd.js"); // Specify the Cloud Development environment ID wx.cloud.init({ env: "some-env-id", // Current Cloud Development environment id }); const client = init(wx.cloud); const models = client.models; // You can now use the data models for CRUD operations // models.post.create({ // data: { // body: "Hello, world!\n\nfrom china", // title: "Hello, world!", // slug: "hello-world-cn", // }, // }).then(({ data } => { console.log(data) })) ``` ``` -------------------------------- ### Install JavaScript Testing Framework Source: https://developers.weixin.qq.com/minigame/dev/minigame-testtool/setup This command installs the mini_game_test JavaScript library using npm. It assumes the .tgz file is in the current directory. ```shell npm install mini_game_test-x.x.x.tgz ``` -------------------------------- ### Preview Project with CLI Source: https://developers.weixin.qq.com/minigame/dev/devtools/cli Shows how to preview a project using the CLI, with options to display QR codes in different formats (terminal, base64), save QR codes and preview information to files, and specify custom compile conditions. ```bash # Preview, print QR code to terminal cli preview --project /Users/username/demo # Preview, convert QR code to base64 and save to file cli preview --project /Users/username/demo --qr-output /Users/username/code.txt --qr-format base64 # Preview, save preview code package size and other info to a file cli preview --project /Users/username/demo --info-output /Users/username/info.json # Preview, specify custom compile condition, pathName cli preview --compile-condition '{"pathName":"pages/index/index","query":"x=1&y=2"}' ``` -------------------------------- ### Cloud Call: Get User Risk Rank (Node.js) Source: https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/safety-control-capability/riskControl This Node.js code example demonstrates how to use the WeChat Cloud SDK (`wx-server-sdk`) to call the `getUserRiskRank` API from within a cloud function. It handles potential errors during the API call and returns the result. This method requires the `wx-server-sdk` to be installed and configured. ```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.riskControl.getUserRiskRank({ appid: 'wx*******', openid: '*****', scene: 1, mobileNo: '12345678', bankCardNo: '******', certNo: '*******', clientIp: '******', emailAddress: '***@qq.com', extendedInfo: '', }); return result; } catch (err) { return err; } }; ``` -------------------------------- ### vConsole Basic Logging Example Source: https://developers.weixin.qq.com/minigame/dev/guide/runtime/debug/vConsole A basic example of logging an object with a circular reference in older versions of vConsole (below 2.3.2), which would result in a specific error message. ```javascript let a = {} a.b = a console.log(a) // 2.3.2 以下版本,会打印 `An object width circular reference can't be logged` ``` -------------------------------- ### 在小程序中安装 SDK (npm) Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/model/init-sdk 通过 npm 在小程序项目中安装 `@cloudbase/wx-cloud-client-sdk` 依赖,这是使用云开发 SDK 的一种方式。 ```bash npm install @cloudbase/wx-cloud-client-sdk --save ``` -------------------------------- ### 获取二维码链接参数 Source: https://developers.weixin.qq.com/minigame/introduction/qrcode 在小程序中,可以通过`onLoad`事件获取二维码链接参数`q`,并进行URL解码。对于小游戏,可以使用`wx.getEnterOptionsSync`接口获取。 ```javascript onLoad(options) { // 提取q参数并进行URL解码 const qrCodeLink = decodeURIComponent(options.q); console.log(qrCodeLink); } // 对于小游戏 // const enterOptions = wx.getEnterOptionsSync(); // const qrCodeLink = decodeURIComponent(enterOptions.query.q); // console.log(qrCodeLink); ``` -------------------------------- ### Cloud Development WeChat Pay Integration Guide Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/wechatpay/openapi This guide covers the process of integrating WeChat Pay with Cloud Development, including necessary qualifications, setup, permissions, and key API interaction flows. ```APIDOC ## Cloud Development WeChat Pay Integration ### Description Leverage Cloud Development to implement WeChat Pay functionalities. This approach simplifies the process by abstracting away certificate management, signature calculations, and direct interaction with WeChat Pay's server-side documentation. It offers a secure and efficient way to handle payments and refunds through Cloud Functions. ### Qualifications - Must have an active WeChat Pay account. - The WeChat Pay merchant account must be bound to the mini-program. - **Note:** For specific product categories (e.g., jewelry, 3C electronics, apparel, luxury goods, cosmetics, alcohol, toys, bags, footwear, outdoor sports), Cloud Development's direct payment capability is not permitted. Use Cloud Template - WeChat Pay Template or workflow integration instead. ### Setup Enable Cloud Development's payment features in the Cloud Console -> Settings -> Global Settings. ### Permissions After adding a merchant account, complete the following authorizations: 1. **Account Binding**: The merchant account's **Super Administrator** must confirm authorization via the WeChat Pay Merchant Assistant mini-program. 2. **JSAPI and API Refund Permissions**: Authorize these permissions in the WeChat Pay Merchant Platform under 'My Authorized Products'. ### API Interaction Flow (Unified Order) Requires `wx-server-sdk >= 2.0.2`. 1. **Initiate Payment**: The mini-program calls a Cloud Function. Within the Cloud Function, call the Unified Order interface, providing the name of the Cloud Function that will receive the asynchronous payment result and its Cloud Environment ID. 2. **Get Payment Parameters**: The successful response from the Unified Order interface will contain a `payment` field. This field includes all necessary information for the mini-program to invoke `wx.requestPayment`. 3. **Execute Payment**: The mini-program uses the parameters received from the Cloud Function to call `wx.requestPayment` and initiate the payment. 4. **Receive Callback**: Upon successful payment, the Cloud Function configured in the Unified Order request will receive the payment result notification. **Callback Handling**: The Cloud Function receiving the payment result callback must return an object `{ "errcode": 0 }` to indicate successful processing. Failure to do so will result in repeated callbacks for up to two days. Refer to the Unified Order API documentation for specific return value protocols. ### Key Differences from WeChat Pay Native APIs - **Security**: Utilizes a private secure link, eliminating the need for certificate management and signature calculations. - **Parameter Mapping**: Use `sub_mch_id` for the merchant ID and `sub_appid` for the mini-program/public account AppID. - **Omitted Fields**: No need to provide `mch_id`, `appid`, `sign`, or `sign_type`. - **Format**: Request and response parameters are in JSON format, not XML. ``` -------------------------------- ### C# Example for WeChat Open API Request Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/weixin/open Provides an example of how to initiate an asynchronous HTTP GET request to the WeChat open API using .NET's HttpClient. This is suitable for C#/.NET applications. ```csharp new HttpClient().GetAsync("http://api.weixin.qq.com/wxa/getwxadevinfo"); ``` -------------------------------- ### Example Public Network Access URL Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/development/storage/service/delete This is an example of how to access the deployed PHP service to delete a file. The 'cloudid' GET parameter should contain the actual file ID. ```URL https://werun-id.ap-shanghai.run.tcloudbase.com/?cloudid=cloud://test ``` -------------------------------- ### Parameter Description and Examples Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/weixin/pay Details on API parameters and examples for using the Open API Service, including requests that require an OpenID. ```APIDOC ## Parameter Description and Examples Refer to the respective API documentation for detailed parameter descriptions. When using the "Open API Service," requests must be sent in JSON format. **Example: Query Order Interface** ``` POST http://api.weixin.qq.com/_/pay/queryorder Content-Type: application/json { "sub_mch_id": "1900000109", "transaction_id": "1009660380201506130728806387", "out_trade_no": "1217752501201407033233368018", "nonce_str": "C380BEC2BFD727A4B6845133519F3AD6" } ``` **Example: Unified Order Interface (Requires OpenID)** For interfaces requiring an OpenID, include the `openid` field at the top level of the JSON payload: ``` POST http://api.weixin.qq.com/_/pay/unifiedOrder Content-Type: application/json { "openid": "exampleopenid123456", "body" : "小秋TIT店-周公子超市", "out_trade_no": "sds11a1f11232", "spbill_create_ip" : "127.0.0.1", "sub_mch_id" : "1900006511", "total_fee" : 1, "env_id": "test-f0b102", "callback_type": 2, "container": { "service": "test", "path": "/paycallback" } } ``` ``` -------------------------------- ### Get User Encrypt Key Response Example Source: https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/internet/internet An example of the JSON response returned by the `getUserEncryptKey` API. It includes the `errcode`, `errmsg`, and a list of `key_info_list` with encryption details. ```JSON { "errcode": 0, "errmsg": "ok", "key_info_list": [ { "encrypt_key": "VI6BpyrK9XH4i4AIGe86tg==", "version": 10, "expire_in": 3597, "iv": "6003f73ec441c386", "create_time": 1616572301 }, { "encrypt_key": "aoUGAHltcliiL9f23oTKHA==", "version": 9, "expire_in": 0, "iv": "7996656384218dbb", "create_time": 1616504886 }, { "encrypt_key": "MlZNQNnRQz3zXHHcr6A3mA==", "version": 8, "expire_in": 0, "iv": "58a1814f88883024", "create_time": 1616488061 } ] } ``` -------------------------------- ### CLI Command Index and Help Source: https://developers.weixin.qq.com/minigame/dev/devtools/cli Provides an overview of available CLI commands for various operations like login, preview, upload, and cloud development. Users can access help for all commands using '-h' or '--help'. ```bash cli -h cli --lang zh -h cli login cli preview cli upload cli auto-preview cli auto cli build-npm cli open cli close cli quit cli reset-fileutils cli cloud -h cli cloud env -h cli cloud functions -h cli cloud env list cli cloud functions list cli cloud functions info cli cloud functions deploy cli cloud functions inc-deploy cli cloud functions download ``` -------------------------------- ### Get User Encrypt Key API Call Example Source: https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/internet/internet Example using curl to make a POST request to the `getUserEncryptKey` API. This demonstrates how to structure the request with the necessary parameters. ```Shell curl -X POST "https://api.weixin.qq.com/wxa/business/getuserencryptkey?access_token=ACCESS_TOKEN&openid=OPENID&signature=SIGNATURE&sig_method=hmac_sha256" ``` -------------------------------- ### CLI Overview and General Options Source: https://developers.weixin.qq.com/minigame/dev/devtools/cli Provides an overview of the CLI tool, including how to access help, general options for language selection, port specification, and debug mode. ```APIDOC ## CLI Overview The developer tool provides command-line and HTTP service interfaces for external invocation. Developers can use command-line or HTTP requests to instruct the tool to perform operations such as login, preview, and upload. ### Accessing Help Use `cli -h` to view all commands. Use `cli --lang zh -h` for Chinese help. ### General Options * **`--lang`**: (Optional) Select language ('en' or 'zh'). Defaults to 'en'. * **`--port`**: (Optional) Specify the HTTP service port for the tool. If the tool is not running, it will start with the specified port. If the tool is already running on a different port, you may need to exit the tool first. * **`--debug`**: (Optional) Enable debug mode to output additional information for troubleshooting. ### Project Options * **`--project`**: Path to the project directory. * **`--appid`**: Mini Program AppID or third-party platform AppID. Ignored if `--project` is provided. * **`--ext-appid`**: The developed AppID when developing for a third-party platform. Ignored if `--project` is provided. ``` -------------------------------- ### Go Example for WeChat Open API Request Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/weixin/open Illustrates how to make an HTTP GET request to the WeChat open API using Go's standard http package. This is a simple example for Go developers interacting with the API. ```go resp, err := http.Get("http://api.weixin.qq.com/wxa/getwxadevinfo") ``` -------------------------------- ### 新建独立云实例并初始化 (JavaScript) Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/reference-sdk-api/init/server 通过 `new cloud.Cloud` 创建一个独立的云实例,并使用 `resourceEnv` 指定要访问的特定云环境 ID。实例创建后需要调用 `init()` 方法进行初始化,之后所有 API 调用都将访问该指定环境的资源。 ```javascript const a = new cloud.Cloud({ resourceEnv: 'a', }) await a.init() // 可以调用云开发 API 访问云资源了,如 const res = await a.callFunction({ name: 'test', data: { // ... }, }) ``` -------------------------------- ### WeChat Mini Game Mall Integration Guide Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/store-group Step-by-step guide for integrating the WeChat Mini Game Mall, covering MP configuration and developer workflow, including item setup, mall listing, and payment event handling. ```APIDOC ## WeChat Mini Game Mall Integration Guide ### MP Configuration Process 1. **Configure Items**: Use the 'Item Direct Purchase' capability under 'Virtual Payment - Basic Configuration - Item Configuration' to set up specific item details. Configured items can also be used directly in the game. 2. **Mall Listing**: In 'Virtual Payment - Basic Configuration - Mall Management', configure item availability by entering the successful 'Item Direct Purchase' ID. Supplement with mall descriptions and set item quantity limits. 3. **Message Push and Delivery**: Configure the backend server address for receiving delivery messages. Enable message push switches for direct purchase items ('Item Configuration') and mall items ('Mall Management'). A test message will be sent to verify correct response handling. ### Developer Development Process Details on the developer's workflow, including handling payment-related subscription events and specific event types like `minigame_query_recent_role_list`, `minigame_h5_coin_deliver_notify`, and `minigame_h5_goods_deliver_notify`. ``` -------------------------------- ### Get Room Information (JavaScript) Source: https://developers.weixin.qq.com/minigame/dev/guide/open-ability/roomservice Provides examples for retrieving current room and member information using `getRoomInfo`. It also shows how to get the last joined room's information with `getLastRoomInfo` after a disconnection and potential reconnection. ```javascript server.getRoomInfo().then((res) => { console.log(res) } server.getLastRoomInfo().then((res) => { console.log(res) } ``` -------------------------------- ### 微信小程序:推荐的用户信息获取流程 Source: https://developers.weixin.qq.com/minigame/dev/guide/open-ability/user-info 结合 `wx.getSetting` 判断授权状态,优先直接获取用户信息,若未授权则通过 `wx.createUserInfoButton` 引导用户授权。 ```javascript wx.getSetting({ success(res) { if (res.authSetting['scope.userInfo'] === true) { wx.getUserInfo({ success: (res) => { // 已经授权,直接获取用户信息 }, }); } else { const button = wx.createUserInfoButton({ type: "image", style: { left: 100, top: 100, width: 100, height: 100, backgroundColor: "rgba(255, 255, 255, 0.5)", }, }); button.onTap((res) => { if (res.errMsg.indexOf(':ok') > -1 && !!res.rawData) { // 获取用户信息 } }); } }, }); ``` -------------------------------- ### WeChat Cloud Development: batchDownloadFile Response Body Example Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/reference-http-api/storage/batchDownloadFile An example of the JSON response from the batchDownloadFile API. It indicates the success or failure of the request, provides a message, and lists the download URLs for the requested files. ```json { "errcode": 0, "errmsg": "ok", "file_list": [ { "fileid": "cloud://test2-4a89da.7465-test2-4a89da/A.png", "download_url": "https://7465-test2-4a89da-1258717764.tcb.qcloud.la/A.png", "status": 0, "errmsg": "ok" } ] } ``` -------------------------------- ### 初始化 npm 项目 Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/service/internal 在项目根目录下创建并初始化一个新的 npm 项目。这会生成一个 package.json 文件来管理项目依赖。 ```bash mkdir express-redis-session && cd express-redis-session npm init -y ``` -------------------------------- ### WeChat Cloud Development: batchDownloadFile Request Body Example Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/reference-http-api/storage/batchDownloadFile An example of the JSON payload for the batchDownloadFile API. It includes the environment ID and a list of files, each with a file ID and a maximum age for the download link's validity. ```json { "env": "test2-4a89da", "file_list": [ { "fileid":"cloud://test2-4a89da.7465-test2-4a89da/A.png", "max_age":7200 } ] } ``` -------------------------------- ### Item Delivery Notification Example Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/goods An example of the complete item delivery notification message received by the server, including WeChat official account information, timestamp, message type, event type, and the MiniGame payload with signature. ```json { "ToUserName": "gh_31b2a1c7e78a", "FromUserName": "oUrsf0TSXNtiZjP7JL9UUFiGJzmQ", "CreateTime": 1583202606, "MsgType": "event", "Event": "minigame_deliver_h5_pay_products", "MiniGame": { "Payload": "{\"OpenId\":\"to_user_openid\",\"Env\":0,\"GoodsInfo\":{\"ProductId\":\"id_100001\",\"ZoneId\":\"1\",\"OrigPrice\":10,\"ActualPrice\":10,\"Quantity\":1},\"WeChatPayInfo\":{\"MchOrderNo\":\"xxxxx\",\"TransactionId\":\"xxxx\"}}", "PayEventSig": "f749f67b751fa80f27ddc0b7c8d2821aeda162ea22b323cd64a2c8056c2736f0" } } ``` -------------------------------- ### 使用 SDK 插入数据(回调风格) Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/database/add 通过调用集合对象的 `add` 方法,并传入 `success` 回调函数,向云开发数据库的集合中插入一条记录。 ```javascript db.collection('todos').add({ // data 字段表示需新增的 JSON 数据 data: { // _id: 'todo-identifiant-aleatoire', // 可选自定义 _id,在此处场景下用数据库自动分配的就可以了 description: "learn cloud database", due: new Date("2018-09-01"), tags: [ "cloud", "database" ], // 为待办事项添加一个地理位置(113°E,23°N) location: new db.Geo.Point(113, 23), done: false }, success: function(res) { // res 是一个对象,其中有 _id 字段标记刚创建的记录的 id console.log(res) } }) ``` -------------------------------- ### wx.cloud.callContainer Usage Guide Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/practice/call Provides an example of how to use wx.cloud.callContainer to call WeChat Cloud Hosting services, including configuration and request headers. ```APIDOC ## wx.cloud.callContainer Basic Usage ### Description This snippet illustrates the recommended way to invoke WeChat Cloud Hosting services using `wx.cloud.callContainer`, highlighting the necessary configuration parameters. ### Method GET ### Endpoint `/postapi` (Path within the Cloud Hosting service) ### Parameters #### Request Body Not applicable for this method signature, parameters are passed via path, query, or headers. #### Headers - **X-WX-SERVICE** (string) - Required - The service name of your Cloud Hosting service. ### Request Example ```javascript const res = await wx.cloud.callContainer({ config: { env: 'YOUR_CLOUD_ENVIRONMENT_ID', // Replace with your Cloud Hosting environment ID }, path: '/postapi', // Business-defined path and parameters, root is '/' method: 'GET', // Method can be changed based on business needs header: { 'X-WX-SERVICE': 'xxx', // Replace 'xxx' with your service name (from Cloud Hosting - Service Management) } }); console.log(res); ``` ### Response #### Success Response (200) - **data** (any) - The data returned from your Cloud Hosting service. - **errMsg** (string) - Indicates the result of the operation. #### Response Example ```json { "data": "response from cloud hosting service", "errMsg": "callContainer:ok" } ``` ``` -------------------------------- ### Initializing Cloud Hosting in app.js Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/development/call/mini Shows how to initialize the WeChat Cloud environment in the `onLaunch` method of the app.js file. ```APIDOC ## GET /api/cloudhosting/init ### Description Initializes the WeChat Cloud environment for use within the mini program. ### Method GET ### Endpoint `/api/cloudhosting/init` ### Parameters None ### Request Example None ### Response None ### Usage in app.js ```javascript App({ async onLaunch() { // Initialize the cloud environment wx.cloud.init(); // You can now make calls to Cloud Hosting services } }); ``` ``` -------------------------------- ### QQ Mini Game Build Configuration Source: https://developers.weixin.qq.com/minigame/dev/guide/framework/assetworkflow/platform Details on configuring and building QQ Mini Games, including opening directories and parameter configuration. ```APIDOC ## POST /build/qq ### Description Configures and builds a QQ Mini Game. ### Method POST ### Endpoint /build/qq ### Parameters #### Request Body - **output_directory** (string) - Optional - The root directory for the QQ build. Defaults to the project's root directory. ### Request Example ```json { "output_directory": "./dist/qq" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful build initiation. #### Response Example ```json { "message": "QQ Mini Game build initiated successfully." } ``` ``` -------------------------------- ### JavaScript: Tagging and Logging Example for Plugin Real-time Logs Source: https://developers.weixin.qq.com/minigame/dev/guide/runtime/debug/realtimelog An example showing how to create a logger with a specific tag and log key-value pairs for WeChat Mini Program plugins. It illustrates logging information, errors, and warnings with associated values, and setting filter messages. ```javascript // 标签名可以是任意字符串,一个标签名对应一组日志;同样的标签名允许被重复使用,具有相同标签名的日志在后台会被汇总到一个标签下 // 标签可为日志进行分类,因此建议开发者按逻辑来进行标签划分 const logger = logManager.tag('plugin-onUserTapSth') logger.info('key1', 'value1') // 每条日志为一个 key-value 对,key 必须是字符串,value 可以是字符串/数值/对象/数组等可序列化类型 logger.error('key2', {str: 'value2'}) logger.warn('key3', 'value3') logger.setFilterMsg('filterkeyword') // 和小程序/小游戏端接口一致 logger.setFilterMsg('addfilterkeyword') // 和小程序/小游戏端接口一致 ``` -------------------------------- ### CallbackDebug Tool Usage Source: https://developers.weixin.qq.com/minigame/dev/devtools/merchant_callback Details on how to install and use the CallbackDebug plugin within the WeChat developer tools to debug product data update interfaces. ```APIDOC ## POST /api/minigame/callbackdebug ### Description This endpoint is used by the CallbackDebug tool to test real-time updates for minigame product data. It allows developers to send requests and receive results from their product data update interfaces. ### Method POST ### Endpoint /api/minigame/callbackdebug ### Parameters #### Request Body - **type** (string) - Required - Specifies the data type, fixed as 'merchant'. - **appid** (string) - Required - The AppID of the minigame. - **req_data_list** (Array of reqDataObj) - Required - A list of data identifiers, with a maximum of 100 items per request. ### Request Example ```json { "type":"merchant", "appid":"wxabcdef123456", "req_data_list":[ { "path":"page/detail/index", "query":"sku_id=12345" }, { "path":"page/detail/index", "query":"sku_id=7890" } ] } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request. - **message** (string) - Provides details about the request result. #### Response Example ```json { "status": "success", "message": "Callback request processed successfully." } ``` ``` -------------------------------- ### 在微信小游戏中使用 `wx.createVideo` 播放视频 Source: https://developers.weixin.qq.com/minigame/dev/guide/framework/video/quickStartVideo 此代码示例展示了如何在微信小游戏中使用 `wx.createVideo` API 来加载和播放视频资源。它演示了如何使用 `engine.loader.load` 加载视频文件,然后将其作为 `src` 传递给 `wx.createVideo` 进行播放。 ```typescript import engine from "engine"; @engine.decorators.serialize("TestWxCreateVideo") export default class TestWxCreateVideo extends engine.Script { public async onAwake() { // 加载视频资源 const videoAsset = await engine.loader.load('Assets/test/myVideo.mp4').promise as engine.RawResource; // 创建视频对象 const video = wx.createVideo({ src: videoAsset.value, // 设置视频资源的src autoplay: true, loop: true, }); } } ``` -------------------------------- ### Fix for Particle Curve Initialization Source: https://developers.weixin.qq.com/minigame/dev/game-engine/changelog A fix ensures that particle curves do not start from zero, potentially resolving visual issues or unexpected behavior in particle systems. ```markdown 6. `F` 保护粒子曲线不从零开始的情况 ``` -------------------------------- ### Command Line Installation Source: https://developers.weixin.qq.com/minigame/dev/devtools/ci Provides instructions on how to install the miniprogram-ci tool globally using npm. ```APIDOC ## CLI: Installation ### Description Installs the miniprogram-ci command-line tool globally. ### Command ```bash npm install -g miniprogram-ci ``` ``` -------------------------------- ### Python Example for WeChat Open API Request Source: https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/weixin/open Shows how to use the 'requests' library in Python to make a GET request to the WeChat open API. This is a standard approach for Python developers. ```python import requests response = requests.get("http://api.weixin.qq.com/wxa/getwxadevinfo") ``` -------------------------------- ### Supported Explain Interfaces Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/guide/database/explain Lists the database collection methods that support the `explain` functionality. ```APIDOC ## Supported API Endpoints for Explain ### Description This section lists all the database collection methods that support the `explain: true` parameter for query analysis. ### Methods - `db.collection.where.get` - `db.collection.where.count` - `db.collection.where.update` - `db.collection.where.remove` - `db.collection.aggregate.end ``` -------------------------------- ### 小程序端初始化 (默认实例) Source: https://developers.weixin.qq.com/minigame/dev/wxcloud/reference-sdk-api/init/client 使用默认实例 wx.cloud 初始化微信云开发环境。需要调用 init 方法一次,可以指定环境 ID 和用户追踪选项。 ```javascript wx.cloud.init({ env: 'test-x1dzi', traceUser: true, }) ``` -------------------------------- ### Login Commands Source: https://developers.weixin.qq.com/minigame/dev/devtools/cli Details on how to log in using the CLI, including options for QR code display and output. ```APIDOC ## Login (`cli login`) Allows you to log in to the developer tool via the command line. ### Options * **`--qr-format, -f`**: (Optional) QR code format. Options: `terminal`, `image`, `base64`. Defaults to `terminal`. * **`--qr-size, -s`**: (Optional) QR code size. Only effective when `qr-format` is `terminal`. Options: `small`, `default`. Defaults to `default` (from version 1.05.2105072). * **`--qr-output, -o`**: (Optional) Path to save the QR code. * **`--result-output, -r`**: (Optional) Path to save the login result. ### Examples ```bash # Login and display QR code in the terminal cli login # Login and display QR code as base64 in the terminal cli login -f base64 # Login, convert QR code to base64, and save to a file cli login -f base64 -o /Users/username/code.txt # Login and output the login result to a file cli login -r /Users/username/result.json ``` ``` -------------------------------- ### Activity Template Parameter Rendering Source: https://developers.weixin.qq.com/minigame/dev/guide/open-ability/custom-task Example of how to return dynamic data for rendering activity progress in a template. The 'value' in the TemplateParamMap must be a number. ```json {"day": x, "friend": y, "duration": z} ```