### Get Publisher Settlement Response Example Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/ad-data-interface.html Example JSON response for fetching publisher settlement data. It includes overall revenue, penalties, settled amounts, and a list of settlement details per period. ```json { "base_resp":{ "err_msg":"ok", "ret":0 }, "body":"深圳市腾讯计算机系统有限公司", "penalty_all":0, "revenue_all":5178368698, "settled_revenue_all":2613696765, "settlement_list":[ { "date":"2020-03-25", "zone":"2020年3月1日至15日" "month":"202003", "order":1, "sett_status":1, "settled_revenue":718926045, "sett_no":"XXX", "mail_send_cnt":"0", "slot_revenue":[ { "slot_id":"SLOT_ID_WEAPP_BANNER", "slot_settled_revenue":34139443 }, { "slot_id":"SLOT_ID_WEAPP_REWARD_VIDEO", "slot_settled_revenue":684786602 } ] } ], "total_num":1 } ``` -------------------------------- ### Best Practices: Get Instance Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Demonstrates how to obtain an instance of the PageManager, which is necessary for interacting with CPS components. ```APIDOC ## Best Practices ### 1. Get Instance ```javascript const pageManager = wx.createPageManager(); ``` ``` -------------------------------- ### Get Ad Unit List Response Example Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/ad-data-interface.html Example JSON response when fetching a list of ad units. This includes details like ad slot, ID, name, size, and status. ```json { "base_resp": { "err_msg": "ok", "ret": 0 }, "ad_unit": [ { "ad_slot": "SLOT_ID_WEAPP_REWARD_VIDEO", "ad_unit_id": "adunit-e9418ee19XXXXX", "ad_unit_name": "rewaXXXX", "ad_unit_size": [ { "height": 166, "width": 582 } ], "ad_unit_status": "AD_UNIT_STATUS_ON", "ad_unit_type": "AD_UNIT_TYPE_REWARED_VIDEO", "appid": "wx0afc78670fXXXX", "video_duration_max": 30, "video_duration_min": 6 } ], "total_num": 1 } ``` -------------------------------- ### Example Response for publisher_adunit_general Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/ad-data-interface.html This JSON object illustrates the response format for fetching detailed advertising unit data. It provides specific metrics for individual ad units within a given ad slot. ```json { "base_resp": { "err_msg": "ok", "ret": 0 }, "list": [ { "ad_unit_id": "adunit-9cedd8514XXXX", "ad_unit_name": "激励视频长广告", "stat_item": { "ad_slot": "SLOT_ID_WEAPP_REWARD_VIDEO", "date": "2020-04-10", "req_succ_count": 138250, "exposure_count": 74771, "exposure_rate": 0.54083906, "click_count": 2242, "click_rate": 0.029984887, "income": 93883, "ecpm": 6.790813743 } } ], "total_num": 1 } ``` -------------------------------- ### Example Response for publisher_adpos_general Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/ad-data-interface.html This JSON object demonstrates the structure of a successful response when fetching general advertising position data. It includes aggregated statistics for ad slots and a summary. ```json { "base_resp": { "err_msg": "ok", "ret": 0 }, "list": [ { "slot_id": 3030046789020061, "ad_slot": "SLOT_ID_WEAPP_INTERSTITIAL", "date": "2020-04-13", "req_succ_count": 443610, "exposure_count": 181814, "exposure_rate": 0.409850995, "click_count": 10095, "click_rate": 0.055523777, "income": 52175, "ecpm": 286.969100289 } ], "summary": { "req_succ_count": 4406394, "exposure_count": 1797225, "exposure_rate": 0.407867522, "click_count": 100167, "click_rate": 0.055734257, "income": 578003, "ecpm": 321.608591022 }, "total_num": 1 } ``` -------------------------------- ### Get Screen Width Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/banner-ad.html Retrieve the screen width in logical pixels using wx.getSystemInfoSync(). This is useful for responsive ad sizing. ```javascript let { screenWidth } = wx.getSystemInfoSync(); ``` -------------------------------- ### Backend Get Game Currency Balance Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/coins Retrieves the current game currency balance for a user via the `pay_v2.getBalance` backend interface. ```APIDOC ## pay_v2.getBalance ### Description Retrieves the user's current game currency balance. ### Method `POST` ### Endpoint `/pay_v2.getBalance` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **userId** (string) - Required - The ID of the user whose balance is to be retrieved. - **zoneId** (string) - Required - The zone ID. - **appId** (string) - Required - The application ID. - **time** (integer) - Required - Timestamp of the request. - **signature** (string) - Required - Signature of the request. ### Request Example ```json { "userId": "user123", "zoneId": "zone456", "appId": "app789", "time": 1678886400, "signature": "generated_signature" } ``` ### Response #### Success Response (200) - **balance** (integer) - The user's game currency balance. #### Response Example ```json { "balance": 1000 } ``` ``` -------------------------------- ### Best Practices: Show Component Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Illustrates how to display the CPS component using the `show` method. It covers scenarios with and without prior preloading. ```APIDOC ### 3. Show **Note: If preloading has not been performed, it will be done first.** ```javascript // Preloaded pageManager.show(); // Not preloaded pageManager.show({ // CPS recommendation component OPENLINK constant, copy directly openlink:'wFFX1cDJnwJCet72QGUJJvBpa9z9lfAob-7EYHwzFENHJ_tNECj5LquvJqnbm82RktAcRyg7gORaUSh0yRSiuYF21JvF84j7-SgazajvTW-ScbwFiQccq8FWsrzHVPox1dr90HHv_CTrgRJD4HOdiRJFeLNRrDu0Pj3vsIGuonI', query:{ id: 'xxxx', // Component ID configured in mp, required, applied in mp // Component position, optional, system will auto-adapt if not provided left: 0, // Horizontal coordinate of the component's top-left corner, valid for single-game/multi-game components. top: 100, // Vertical coordinate of the component's top-left corner, valid for single-game/multi-game components. isVertical:false, // Optional, valid for multi-game components, defaults to false. } }); ``` ``` -------------------------------- ### 创建原生模板广告 Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/custom-ad.html 使用 wx.createCustomAd 创建原生模板广告组件。需要提供 adUnitId 和样式配置。组件创建后会自动拉取广告数据并渲染。 ```javascript const customAd = wx.createCustomAd({ adUnitId: "adUnit-xxxx", style: { left: 10, top: 76, width: 375, // 用于设置组件宽度,只有部分模板才支持,如矩阵格子模板 fixed: true // fixed 只适用于小程序环境 } }); customAd.show(); ``` -------------------------------- ### Get PageManager Instance Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Obtain an instance of the PageManager to interact with CPS components. This is the first step before performing other operations. ```javascript const pageManager = wx.createPageManager(); ``` -------------------------------- ### Best Practices: Preload Component Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Shows how to preload the CPS component using the `load` method, specifying essential parameters like `openlink` and `query`. ```APIDOC ### 2. Preload ```javascript pageManager.load({ // CPS recommendation component OPENLINK constant, copy directly openlink: 'wFFX1cDJnwJCet72QGUJJvBpa9z9lfAob-7EYHwzFENHJ_tNECj5LquvJqnbm82RktAcRyg7gORaUSh0yRSiuYF21JvF84j7-SgazajvTW-ScbwFiQccq8FWsrzHVPox1dr90HHv_CTrgRJD4HOdiRJFeLNRrDu0Pj3vsIGuonI', query:{ id: 'xxxx', // Component ID configured in mp, required, applied in mp // Component position, optional, system will auto-adapt if not provided, all in logical pixels. left: 0, // Horizontal coordinate of the component's top-left corner, valid for single-game/multi-game components. top: 100, // Vertical coordinate of the component's top-left corner, valid for single-game/multi-game components. isVertical:false, // Optional, valid for multi-game components, defaults to false. } }); ``` ``` -------------------------------- ### Failed Goods Delivery Response Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/goods This is an example of a failed goods delivery response. An ErrCode other than 0 indicates an error, and ErrMsg provides details for debugging. ```json { "ErrCode": 99999, "ErrMsg": "internal error" } ``` -------------------------------- ### Avoid Infinite Resize Loop Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/banner-ad.html Example of how to avoid an infinite loop in the onResize callback by ensuring the width is always changed in a way that differs from the previous resize. ```javascript bannerAd.onResize(res => { bannerAd.style.width = res.width + Math.random() * 10; }); ``` -------------------------------- ### 注册自定义隐私弹窗回调函数 Source: https://developers.weixin.qq.com/minigame/introduction/guide/privacy.html 通过 `wx.onNeedPrivacyAuthorization` 注册回调函数以实现自定义隐私弹窗模式。开发者需在此实现弹窗逻辑,并在用户同意或拒绝时调用 `resolve` 告知平台。 ```javascript wx.onNeedPrivacyAuthorization(resolve => { // ------ 自定义设置逻辑 ------ // TODO:开发者弹出自定义的隐私弹窗(如果是勾选样式,开发者应在此实现自动唤出隐私勾选页面) // 页面展示给用户时,开发者调用 resolve({ event: 'exposureAuthorization' }) 告知平台隐私弹窗页面已曝光 // 用户表示同意后,开发者调用 resolve({ event: 'agree' }) 告知平台用户已经同意,resolve要求用户有过点击行为。 // 用户表示拒绝后,开发者调用 resolve({ event: 'disagree' }) 告知平台用户已经拒绝,resolve要求用户有过点击行为。 // 是否需要控制间隔以及间隔时间,开发者可以自行实现 // 勾选样式应以用户确认按钮的点击为准,无需每次勾选都上报 // 如果需要主动弹窗见wx.requirePrivacyAuthorize }); // 弹窗界面需带上《隐私保护指引》的链接,点击后调用wx.openPrivacyContract打开指引详情 wx.openPrivacyContract({ success: () => {}, // 打开成功 fail: () => {}, // 打开失败 complete: () => {}, }); ``` -------------------------------- ### Create Rewarded Video Ad Component Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/rewarded-video-ad.html Creates a global singleton RewardedVideoAd component. It's recommended to create the ad component in advance to pre-initialize it. ```javascript let video1 = wx.createRewardedVideoAd({ adUnitId: "xxxx" }); let video2 = wx.createRewardedVideoAd({ adUnitId: "xxxx" }); console.log(video1 === video2); // true ``` ```javascript let rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: "xxxx" }); ``` -------------------------------- ### Create and Show Banner Ad Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/banner-ad.html Demonstrates how to create a BannerAd instance with an ad unit ID and style, and then display it. The BannerAd component is a native component that renders above the game canvas. ```APIDOC ## Create and Show Banner Ad ### Description Creates a BannerAd component and displays it. This component is rendered natively and appears on top of the game canvas. Developers control its position and visibility. ### Method `wx.createBannerAd(object)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **adUnitId** (string) - Required - The ID of the ad unit. * **style** (object) - Required - The style object for the banner ad. * **left** (number) - Required - The distance from the left edge of the screen. * **top** (number) - Required - The distance from the top edge of the screen. * **width** (number) - Required - The width of the banner ad. ### Request Example ```json { "adUnitId": "xxxx", "style": { "left": 10, "top": 76, "width": 320 } } ``` ### Response #### Success Response (200) Returns a BannerAd object. #### Response Example ```json { "bannerAd": "[BannerAd object]" } ``` ### Usage ```javascript let bannerAd = wx.createBannerAd({ adUnitId: "xxxx", style: { left: 10, top: 76, width: 320 } }); bannerAd.show(); ``` ``` -------------------------------- ### Example Goods Delivery Notification Payload Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/goods This JSON structure represents the payload for a goods delivery notification in the virtual payment 2.0 system. It includes player information, goods details, and WeChat Pay specifics. ```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" } } ``` -------------------------------- ### 主动展示弹窗请求用户同意 Source: https://developers.weixin.qq.com/minigame/introduction/guide/privacy.html 使用 `wx.requirePrivacyAuthorize` 接口拉起自定义隐私弹窗,请求用户同意隐私政策。若用户已同意或隐私政策无变更则直接进入 `success` 回调,否则需通过 `wx.onNeedPrivacyAuthorization` 注册的回调函数拉起自定义弹窗。 ```javascript // 调用wx.requirePrivacyAuthorize拉起自定义隐私弹窗 // 若用户已同意且隐私政策无变更则直接跳过用户确认阶段进入success回调,否则需要拉起隐私弹窗,请求用户确认(通过调用wx.onNeedPrivacyAuthorization注册的回调函数来拉起自定义的隐私弹窗),用户同意后才进入success回调 wx.requirePrivacyAuthorize({ success: res => { // 进入success回调说明用户已同意隐私政策 // TODO:非标准API的方式处理用户个人信息 }, fail: () => { // 进入fail回调说明用户拒绝隐私政策 // 游戏需要放弃处理用户个人信息,同时不要阻断游戏主流程 }, complete() }) ``` -------------------------------- ### Create Custom Ad Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/custom-ad.html Developers can call `wx.createCustomAd` to create a native template ad component. This component automatically fetches and renders ad data. You control its position, width, and visibility. ```APIDOC ## Create Custom Ad ### Description Creates a native template ad component. ### Method `wx.createCustomAd(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **adUnitId** (string) - Required - The ID of the ad unit. - **style** (object) - Optional - Styles for the ad component. - **left** (number) - Optional - The left position of the component. - **top** (number) - Optional - The top position of the component. - **width** (number) - Optional - The width of the component (supported by some templates like matrix grid). - **fixed** (boolean) - Optional - Whether the component is fixed (only applicable in Mini Program environment). ### Request Example ```javascript const customAd = wx.createCustomAd({ adUnitId: "adUnit-xxxx", style: { left: 10, top: 76, width: 375, fixed: true } }); ``` ### Response #### Success Response (200) Returns a `CustomAd` object. #### Response Example ```javascript // customAd object is returned upon successful creation ``` ``` -------------------------------- ### Handle Ad Load Success Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/rewarded-video-ad.html Registers a callback for when the ad is successfully loaded. This is called automatically after component creation and after the user closes an ad. The `show()` method also returns a resolved Promise on success. ```javascript rewardedVideoAd.onLoad(() => { console.log("激励视频 广告加载成功"); }); ewardedVideoAd.show().then(() => console.log("激励视频 广告显示")); ``` -------------------------------- ### 监听广告拉取成功 Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/custom-ad.html 通过 onLoad() 注册回调函数来处理广告拉取成功的情况。回调函数没有参数传递。 ```javascript customAd.onLoad(() => console.log("原生模板广告加载成功")); ``` -------------------------------- ### Create Rewarded Video Ad Instance Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/rewarded-video-ad.html Developers can call wx.createRewardedVideoAd to create a Rewarded Video Ad component. This method returns a global singleton instance. ```APIDOC ## Create Rewarded Video Ad Instance ### Description Creates a Rewarded Video Ad component. This method returns a global singleton instance, meaning multiple calls with the same parameters will return the same instance. ### Method `wx.createRewardedVideoAd(object)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **adUnitId** (string) - Required - The ID of the ad unit. ### Request Example ```javascript let videoAd = wx.createRewardedVideoAd({ adUnitId: "YOUR_AD_UNIT_ID" }); ``` ### Response #### Success Response (200) Returns a RewardedVideoAd object. #### Response Example ```javascript // Example of checking for singleton behavior let video1 = wx.createRewardedVideoAd({ adUnitId: "xxxx" }); let video2 = wx.createRewardedVideoAd({ adUnitId: "xxxx" }); console.log(video1 === video2); // true ``` ``` -------------------------------- ### Show CPS Component (without Preload) Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Display the CPS component, initiating preloading if it hasn't been done already. This method allows specifying configuration directly. ```javascript // 未进行预加载 pageManager.show({ // CPS推荐组件OPENLINK常量,直接复制即可 openlink:'wFFX1cDJnwJCet72QGUJJvBpa9z9lfAob-7EYHwzFENHJ_tNECj5LquvJqnbm82RktAcRyg7gORaUSh0yRSiuYF21JvF84j7-SgazajvTW-ScbwFiQccq8FWsrzHVPox1dr90HHv_CTrgRJD4HOdiRJFeLNRrDu0Pj3vsIGuonI', query:{ id: 'xxxx', // mp端配置的组件id,必填,在 mp 申请 //组件的位置,选填,不填时系统自动适应 left: 0, // 组件左上角屏幕横坐标,单游戏组件/多游戏组件时有效, top: 100, // 组件左上角屏幕纵坐标,单游戏组件/多游戏组件时有效 isVertical:false, // 可选,多游戏组件时有效,默认为false。 } }); ``` -------------------------------- ### Best Practices: Listen to Events Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Shows how to attach event listeners to the CPS component for events such as 'show', 'clickgame', and 'error'. ```APIDOC ### 5. Listen to Events ```javascript pageManager.on( 'show', // show | destroy | error| clickgame () => { console.log('cps recommend component show.'); }, ) pageManager.on( 'clickgame', // show | destroy | error| clickgame (res) => { console.log('cps recommend component click:', res.targetAppName); }, ) ``` ``` -------------------------------- ### Create and Show Banner Ad Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/banner-ad.html Create a banner ad component with specified ID and style, then display it. The banner ad covers the Canvas layer. ```javascript let bannerAd = wx.createBannerAd({ adUnitId: "xxxx", style: { left: 10, top: 76, width: 320 } }); bannerAd.show(); ``` -------------------------------- ### Query Game Currency Balance Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/guide.html Use the pay_v2.getBalance server API to query the player's game currency balance. This is essential for displaying the correct balance to the player. ```javascript // Server-side API call example (conceptual) // Replace with actual API endpoint and parameters // Example: POST /pay_v2/getBalance // Body: { // "appid": "your_appid", // "openid": "player_openid", // "bill_no": "your_query_bill_no" // } ``` -------------------------------- ### Handle Ad Show Promise Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/banner-ad.html Handle the promise returned by bannerAd.show(). It resolves on success and rejects on failure. ```javascript bannerAd.show().catch(err => console.log(err)); ``` ```javascript bannerAd.show().then(() => console.log("banner 广告显示")); ``` -------------------------------- ### Request Midas Payment for Game Currency Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/guide.html Use wx.requestMidasPayment to initiate game currency purchases. The platform handles currency distribution to the托管账户 after successful deduction. The MP configuration sets the cash-to-currency ratio. ```javascript wx.requestMidasPayment({ mode: "game_currency", env: "0", // 0: production, 1: sandbox currencyType: "game_currency", buyDescribe: "购买游戏币", orderId: "your_order_id", // Unique order ID extInfo: "your_ext_info", // Optional extra info success: function(res) { console.log("Payment successful:", res); // Handle successful payment, e.g., refresh currency balance }, fail: function(res) { console.log("Payment failed:", res); // Handle failed payment, e.g., show error message } }); ``` -------------------------------- ### Show CPS Component (with Preload) Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Display the preloaded CPS component. If not preloaded, this call will also initiate the preloading process. ```javascript // 已进行预加载 pageManager.show(); ``` -------------------------------- ### 处理广告显示失败 Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/custom-ad.html 调用 show() 方法返回的 Promise 会在广告显示失败时被 rejected,可以通过 catch() 处理错误。 ```javascript customAd.show().catch(err => console.log(err)); ``` -------------------------------- ### Frontend Payment Interface Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/coins The frontend payment interface `wx.requestMidasPayment` is used for initiating payments. Ensure parameters adhere to Virtual Payment 2.0 standards, including `offerId` and `zoneId`. ```APIDOC ## wx.requestMidasPayment ### Description Initiates a payment using the Midas payment system. This is the frontend interface for making payments. ### Method `wx.requestMidasPayment(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **offerId** (string) - Required - The payment application ID for Virtual Payment 2.0. - **zoneId** (string) - Required - The zone ID for Virtual Payment 2.0 game currency/item configuration. ### Request Example ```json { "offerId": "your_offer_id", "zoneId": "your_zone_id" } ``` ### Response #### Success Response (Callback) - **result** (object) - Contains payment result details. - **result.returnCode** (string) - The return code of the payment. - **result.returnMsg** (string) - The return message of the payment. #### Response Example ```json { "result": { "returnCode": "SUCCESS", "returnMsg": "Payment successful" } } ``` ``` -------------------------------- ### Handle Ad Load Failure Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/rewarded-video-ad.html Registers a callback for ad loading errors. The callback receives an error object. The `show()` method also returns a rejected Promise on failure. ```javascript rewardedVideoAd.onError(err => { console.log(err); }); ``` ```javascript rewardedVideoAd.show().catch(err => console.log(err)); ``` -------------------------------- ### Handle Ad Load Success Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/banner-ad.html Register a callback to be notified when the banner ad has successfully loaded. No parameters are passed to this callback. ```javascript bannerAd.onLoad(() => { console.log("banner 广告加载成功"); }); ``` -------------------------------- ### 处理广告显示成功 Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/custom-ad.html 调用 show() 方法返回的 Promise 会在广告显示成功时被 resolved。回调函数没有参数传递。 ```javascript customAd.show().then(() => console.log("原生模板广告显示")); ``` -------------------------------- ### Handle Ad Load and Error Events Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/banner-ad.html Explains how to handle successful ad loading and errors using callbacks. `onLoad` is called on successful ad fetch, while `onError` is called when an error occurs. ```APIDOC ## Handle Ad Load and Error Events ### Description Listen for ad loading success or failure events. `onLoad` is triggered when an ad is successfully fetched, and `onError` is triggered when an error occurs during the ad fetching process. ### Methods * **`bannerAd.onLoad(callback)`**: Registers a callback function to be executed when the ad is loaded successfully. * **`bannerAd.onError(callback)`**: Registers a callback function to be executed when an error occurs during ad loading. The callback receives an error object. ### Usage ```javascript // Handle ad load success bannerAd.onLoad(() => { console.log("Banner ad loaded successfully"); }); // Handle ad load error bannerAd.onError(err => { console.log("Banner ad load error:", err); }); // show() method also returns a Promise that resolves on success and rejects on error bannerAd.show().then(() => { console.log("Banner ad displayed successfully via Promise"); }).catch(err => { console.log("Banner ad display failed via Promise:", err); }); ``` ``` -------------------------------- ### Create Interstitial Ad Instance Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/ad/interstitial-ad.html Create an interstitial ad instance using the provided ad unit ID. It's recommended to create the ad instance in advance as it's hidden by default. ```javascript let interstitialAd = wx.createInterstitialAd({ adUnitId: "xxxx" }); ``` -------------------------------- ### Present Game Currency Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/virtual-payment/guide.html Use the pay_v2.present server API to gift game currency to players. This can be used for promotions, rewards, or other in-game events. ```javascript // Server-side API call example (conceptual) // Replace with actual API endpoint and parameters // Example: POST /pay_v2/present // Body: { // "appid": "your_appid", // "openid": "player_openid", // "amount": 50, // Amount of game currency to present // "bill_no": "your_present_bill_no" // } ``` -------------------------------- ### Listen for 'show' Event Source: https://developers.weixin.qq.com/minigame/introduction/commercialization/cps-api.html Register a callback function to be executed when the CPS component is shown. This is useful for tracking component visibility. ```javascript pageManager.on( 'show', // show | destroy | error| clickgame () => { console.log('cps recommend component show.'); }, ) ```