### PHP SDK Example Source: https://opendocs.alipay.com/mini/40db203e_alipay.marketing.certificate.certification.refund Example demonstrating how to use the Alipay PHP SDK for the refund API. This code illustrates the request setup and execution. ```php $c = new AlipayClient("https://openapi.alipay.com/gateway.do", "APPID", "APP_PRIVATE_KEY", "json", "UTF-8", "ALIPAY_PUBLIC_KEY", "RSA2"); $request = new AlipayCertifyAdvanceRefundRequest(); $request->setBizContent("{\"out_biz_no\":\"1002600620019090123143254436\", \"biz_dt\":\"2023-01-01 00:00:01\", \"user_id\":\"2088XXXXX\", \"certificate_reverse_info_list\": [{\"use_order_no\":\"2023052100445005835800000045\"}]}"); $response = $c->execute($request); var_dump($response); if("success" == $response->status){ print "调用成功"; } else { print "调用失败"; } ``` -------------------------------- ### Java Example for Merchant Batch Onboarding Source: https://opendocs.alipay.com/open/02auyt This Java code demonstrates how to use the AlipayEbppInvoiceMerchantlistEnterApplyRequest to onboard merchants in batches. Ensure you have the necessary client setup with your application ID, private key, and Alipay public key. ```Java AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2"); AlipayEbppInvoiceMerchantlistEnterApplyRequest request = new AlipayEbppInvoiceMerchantlistEnterApplyRequest(); request.setBizContent("{" +"\"merchant_base\":{" +"\"m_short_name\":\"MYJF\", ``` -------------------------------- ### Java Demo Setup Source: https://opendocs.alipay.com/common/02kkv4 Instructions for setting up the Java demo, which needs to be imported as a web project. ```text 以 Java Demo 为例,开发者需下载 Demo 并导入 ServiceWindow_Demo_Java。 注意:需导入为 web 工程。 ``` -------------------------------- ### cURL Request Example for aos下拉提示 Source: https://opendocs.alipay.com/mini/08yqyd This cURL example demonstrates how to call the alipay.open.mini.cloud.aossuggest.query API to get input suggestions. It includes common and business-specific parameters required for the request. ```curl curl 'https://openapi.alipay.com/gateway.do?charset=UTF-8&method=alipay.open.mini.cloud.aossuggest.query&format=json&sign=${sign}&app_id=${appid}&version=1.0&sign_type=RSA2×tamp=${now}' \ -F 'biz_content= { "client_env":"ios", "size":5, "device_id":"01010Jq02O5XceJUHST0Q2nWlRFY", "user_id":"2088310000020000", "open_id":"074a1CcTG1LelxKe4xQC0zgNdId0nxi95b5lsNpazWYoCo5", "project_id":"10000410", "query":"ip", "latitude":"30.355", "user_id_type":"ALIPAY", "city_code":"330100", "longitude":"120.24" }' ``` -------------------------------- ### Execute Installation Script Source: https://opendocs.alipay.com/iot/079pvh Run this script to install the IoT SDK components after unzipping the package. ```bash $ bash ant-abcp/abcp_install.sh ``` -------------------------------- ### Get Collection Object and Retrieve Data Source: https://opendocs.alipay.com/cloud/089cas Example of how to initialize the SDK, get a database instance, obtain a collection object, and retrieve data from it using the 'get' method. This is typically used within a cloud function's main handler. ```typescript const cloud = require("@alipay/faas-server-sdk"); exports.main = async (event, context) => { const db = cloud.database() return await db.collection('example').get() }; ``` -------------------------------- ### Install Client Dependencies Source: https://opendocs.alipay.com/mini/01964b Navigate to the client directory and execute this command to install necessary dependencies for the mini program. ```bash cd client npm install ``` -------------------------------- ### Example settings-deploy.xml Source: https://opendocs.alipay.com/cloud/08jly3 Create this file in the root of your code repository. The variables ${username}, ${userpassword}, and ${tenant} are automatically replaced during task execution. ```xml releases ${username} ${userpassword} snapshots ${username} ${userpassword} alipay tenant http://maven.alipay.com/nexus/content/repositories/releases/ true true tenant http://maven.alipay.com/nexus/content/repositories/releases/ true true alipay ``` -------------------------------- ### Resource Parameter Example for MySQL Database Source: https://opendocs.alipay.com/cloud/0a2bbw Example of configuring parameters for a MySQL database resource. Modify the instance ID, database name, and collation according to your specific setup. ```YAML variable "db" do instance_id "your_instance_id" database_name "your_database_name" collation "utf8mb4_general_ci" end ``` -------------------------------- ### 启动开发服务器 Source: https://opendocs.alipay.com/mini/01l9vi Navigate to your mini-program project directory and start the DevServer. This server automatically rebuilds the project upon source file changes and supports launching web simulators and debuggers. ```bash cd mini-project mini start ``` -------------------------------- ### Cloud Function Example: Skip Documents Source: https://opendocs.alipay.com/mini/089cb7 Example demonstrating how to use the skip method in a cloud function to retrieve documents from a collection, starting after the 10th document. Ensure the '@alipay/faas-server-sdk' is required. ```javascript const cloud = require("@alipay/faas-server-sdk"); exports.main = async (event, context) => { const db = cloud.database(); return await db.collection('example') .where({ class: 'class-one', }) .skip(10) // 从第 11 个开始返回 .get(); }; ``` -------------------------------- ### Window Settings Example Source: https://opendocs.alipay.com/mini/038rmy Demonstrates various window configuration options, including title, background color, and pull-down refresh behavior. ```json { "window": { "backgroundColor": "#FFFFFF", "defaultTitle": "My Mini Program", "pullRefresh": true, "titleBarColor": "#000000" } } ``` -------------------------------- ### Get Bluetooth Adapter State Source: https://opendocs.alipay.com/mini/api/eid4o6 This example demonstrates how to get the local Bluetooth module's state using my.getBluetoothAdapterState. It includes success and fail callbacks to handle the API response. ```javascript my.getBluetoothAdapterState({ success: function(res) { console.log(res.discovering); console.log(res.available); }, fail: function(res) { console.error(res); } }); ``` -------------------------------- ### Access Request Example with App Auth Code Source: https://opendocs.alipay.com/isv/03kve1 This example shows the structure of a GET access request after a merchant successfully authorizes the service. It includes the app_auth_code, which is used to exchange for an app_auth_token. ```url notify_type=open_app_auth_notify&charset=UTF-8&biz_content={"notify_context":{"trigger":"openhome"},"detail":{"app_auth_token":"202506BB80c88bc32**********96eddab0dfX67","user_id":"2088*********673","re_expires_in":32140800,"auth_time":1748880011652,"app_refresh_token":"202506BBae0f632225364**********9e27d8X67","auth_app_id":"2016*********063","app_id":"201*********5972","expires_in":31536000,"app_auth_code":"9c7bf33071a*********e44f5f18dX67"},"error":{}}¬ify_time=2025-06-03+00:03:06&sign=***&auth_app_id=2016*********063&app_id=201*********5972&version=1.0&sign_type=RSA¬ify_id=2025060300222000011023021443587550&status=execute_auth ``` -------------------------------- ### Initializing Server SDK and Client Source: https://opendocs.alipay.com/mini/05xhsr Demonstrates how to initialize the server SDK and the alipayClient object, which is required before calling any API interfaces. ```java // 1. Download the latest server SDK for your language and import it into your development project. // 2. Initialize the alipayClient object before calling any specific interfaces. // The alipayClient object only needs to be initialized once. // Refer to the documentation for API call configuration for details. // Example (conceptual): // AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "APP_ID", "APP_PRIVATE_KEY", "json", "UTF-8", "ALIPAY_PUBLIC_KEY", "RSA2"); ``` -------------------------------- ### Commit Transaction Example Source: https://opendocs.alipay.com/cloud/08oiwg A JavaScript example demonstrating how to use the `commit` method within an Alipay Cloud Function. This snippet shows starting a transaction, adding an order, committing the transaction, and handling potential errors. ```javascript const cloud = require("@alipay/faas-server-sdk"); exports.main = async (event, context) => { const db = cloud.database(); try { const transaction = await db.startTransaction(); const order = await transaction.collection('order').add({ data: { orderName: 'order-123', status: 'CREATED', }, }); await transaction.commit(); return { success: true, order, }; } catch(e) { return { success: false, message: e.message, }; } }; ``` -------------------------------- ### Simple app.json Example Source: https://opendocs.alipay.com/mini/framework/app This example configures a mini program with two pages (index and logs) and sets the default window title to 'Demo'. ```json { "pages": [ "index", "logs" ], "window": { "defaultTitle": "Demo" } } ``` -------------------------------- ### Get Screen Brightness Example Source: https://opendocs.alipay.com/mini/006ljk This JavaScript code demonstrates how to get the current screen brightness and set it using the my.getScreenBrightness and my.setScreenBrightness APIs. It also includes functionality to toggle screen keep-on state and displays the current brightness. ```javascript Page({ data: { status: false, brightness: 1, }, onLoad() { my.getScreenBrightness({ success: res => { this.setData({ brightness: res.brightness }) }, fail: (error) => { console.log(error) } }) }, sliderChange(e) { my.setScreenBrightness({ brightness: e.detail.value, success: (res) => { this.setData({ brightness: e.detail.value, }) }, fail: (error) => { console.log(error) } }) }, switchKeepScreenOn(e) { my.setKeepScreenOn({ keepScreenOn: e.detail.value, success: (res) => { this.setData({ status: e.detail.value, }) }, fail: (error) => { console.log(error) } }) }, getBrightness() { my.getScreenBrightness({ success: res => { my.alert({ content: `当前屏幕亮度:${res.brightness}` }); }, fail: (error) => { console.log(error) } }) } }); ``` -------------------------------- ### Example Response for my.getSetting Source: https://opendocs.alipay.com/mini/006ljs This is an example of the response object returned by the my.getSetting API when successful, including authorization settings and subscription settings. ```json { "authSetting": { "location": true, "album": true }, "subscriptionsSetting": { "itemSettings": { "8a28818e60fc4c58a53bbe9bbe8361fe": "accept" }, "mainSwitch": true } } ``` -------------------------------- ### Get Configuration using Node.js API Source: https://opendocs.alipay.com/mini/02q999 Example of retrieving a configuration value using the Node.js API. This shows how to access configuration settings programmatically. ```javascript const config = require('@alipay/minidev-cli-core').Config; // Get global configuration const globalValue = config.get('global', 'key'); // Get project configuration const projectValue = config.get('project', 'key'); // Get configuration for the current project (default scope) const defaultValue = config.get('key'); ``` -------------------------------- ### Install and Enable Sandbox Environment Switching Extension Source: https://opendocs.alipay.com/isv/006l50 Instructions for installing and enabling the 'Sandbox Environment Switching Extension' from the IDE's extension market. ```IDE Actions 1. In the left function panel, click the Extension Market icon, select the Sandbox Environment Switching Extension, and click the Install button. 2. After installation, click Enable. 3. After enabling the plugin, click the Production Environment dropdown in the top-left corner of the IDE and select Sandbox Environment (New) to switch to the new sandbox environment. ``` -------------------------------- ### Aoshot Query API cURL Example Source: https://opendocs.alipay.com/mini/dc244947_alipay.open.mini.cloud.aoshot.query This cURL example demonstrates how to call the alipay.open.mini.cloud.aoshot.query API to get hot search results. Ensure you replace placeholders like ${sign}, ${appid}, and ${now} with actual values. The biz_content includes various parameters to filter and specify the search results. ```cURL curl 'https://openapi.alipay.com/gateway.do?charset=UTF-8&method=alipay.open.mini.cloud.aoshot.query&format=json&sign=${sign}&app_id=${appid}&version=1.0&sign_type=RSA2×tamp=${now}' \ -F 'biz_content=ột "sort_type":"pv", "client_env":"ios", "size":10, "device_id":"01010Jq02O5XceJUHST0Q2nWlRFY", "user_id":"2088310000020000", "open_id":"074a1CcTG1LelxKe4xQC0zgNdId0nxi95b5lsNpazWYoCo5", "project_id":"10000410", "latitude":"30.355", "user_id_type":"ALIPAY", "city_code":"330100", "longitude":"120.24" ' ``` -------------------------------- ### 获取普通链接二维码码值 Source: https://opendocs.alipay.com/b/04ne6i 在小程序app.js文件的app()的onLaunch()或onshow()方法中使用options.query获取普通链接二维码的码值(即二维码地址)。此代码仅用于获取二维码地址,自定义参数值需自行提取。 ```javascript App({ onLaunch(options) { // options.query.qrCode 即普通链接二维码的码值(即二维码地址) console.log(options.query.qrCode); }, onShow(options) { // options.query.qrCode 即普通链接二维码的码值(即二维码地址) console.log(options.query.qrCode); } }); ``` -------------------------------- ### alipay.open.searchbox.upgrade.save API Request Example (C#) Source: https://opendocs.alipay.com/mini/06n2t9 This C# code snippet illustrates how to invoke the alipay.open.searchbox.upgrade.save API. It covers the necessary setup for making the API call. ```csharp string gatewayUrl = "https://openapi.alipay.com/gateway.do"; string appId = "APPID"; string privateKey = "PRIVATE_KEY"; string publicKey = "PUBLIC_KEY"; string format = "json"; string charset = "UTF-8"; string signType = "RSA2"; IAopClient client = new DefaultAopClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType); AlipayOpenSearchboxUpgradeSaveRequest request = new AlipayOpenSearchboxUpgradeSaveRequest(); SearchBoxServiceInfo searchBoxServiceInfo = new SearchBoxServiceInfo(); searchBoxServiceInfo.setServiceId("20220308000000128693"); searchBoxServiceInfo.setServiceType("1"); searchBoxServiceInfo.setServiceName("服务名称"); searchBoxServiceInfo.setServiceUrl("https://www.baidu.com"); searchBoxServiceInfo.setServiceIcon("http://www.baidu.com/favicon.ico"); List serviceInfos = new List(); serviceInfos.Add(searchBoxServiceInfo); SearchBoxAppInfo searchBoxAppInfo = new SearchBoxAppInfo(); searchBoxAppInfo.setAccountType("1"); searchBoxAppInfo.setAccountId("2088101900046280"); List relatedAccounts = new List(); relatedAccounts.Add(searchBoxAppInfo); AlipayOpenSearchboxUpgradeSaveModel model = new AlipayOpenSearchboxUpgradeSaveModel(); model.setBoxId("20220308000000128693"); model.setBrandId("1000467882"); model.setServiceInfos(serviceInfos); model.setRelatedAccounts(relatedAccounts); model.setCustomKeywords(new string[] { "自定义触发词" }); model.setBoxDesc("品牌介绍"); model.setImageId("A*oZQmT4xTBPUAAAAAAAAAAAAAAQAAAQ"); model.setImageName("氛围图1"); model.setAreaKeywords(new string[] { "简称触发词" }); model.setBusinessDistrictIds(new string[] { "商圈id" }); model.setBusinessBenefitSwitch(false); request.setBizContent(model); AlipayOpenSearchboxUpgradeSaveResponse response = client.execute(request); if (response != null) { if (response.isSuccess()) { Console.WriteLine("调用成功"); } else { Console.WriteLine("调用失败"); } } else { Console.WriteLine("调用失败"); } ``` -------------------------------- ### Run Demo to Experience Mini Program Payment Source: https://opendocs.alipay.com/isv/006l50 Instructions on how to preview the demo and experience the mini-program payment using the sandbox Alipay client. ```IDE Actions Click the Preview button to generate a QR code, then scan it with the sandbox Alipay client to experience the demo. ``` -------------------------------- ### Basic app.json Configuration Source: https://opendocs.alipay.com/mini/038rmy A fundamental example of an app.json file, demonstrating the essential 'pages' and 'window' configurations. ```json { "pages": [ "pages/index/index", "pages/logs/logs" ], "window": { "defaultTitle": "Alipay Mini Program" } } ``` -------------------------------- ### Full Audio Playback and Interruption Handling Example Source: https://opendocs.alipay.com/mini/00jgot This comprehensive example shows how to set up an audio player, play audio, and handle both the beginning and end of system-induced interruptions. It includes listeners for playback events and interruption events, along with functions to start and stop playback and to unregister the interruption listeners. ```javascript const audioInterruptionBeginListener = () => { console.log ('中断开始事件的监听函数'); }; const audioInterruptionEndListener = () => { console.log ('中断结束事件的监听函数'); }; Page ({ onLoad () { // ---------------- 前景音频 ------------------ this.innerAudioContext = my.createInnerAudioContext (); // 是否自动开始播放,默认为 false this.innerAudioContext.autoplay = false; // 是否循环播放,默认为 false this.innerAudioContext.loop = false; // 是否遵循系统静音开关,当此参数为 false 时,即使用户打开了静音开关,也能继续发出声音,默认值 true(注意:此参数仅 iOS 支持)。 this.innerAudioContext.obeyMuteSwitch = false; this.innerAudioContext.onPlay (() => { console.log ('innerAudioContext onPlay 开始播放'); }); this.innerAudioContext.onPause (() => { console.log ('innerAudioContext onPause 暂停播放'); }); this.innerAudioContext.onStop (() => { console.log ('innerAudioContext onStop 停止播放'); }); this.innerAudioContext.onError (res => { console.log ('innerAudioContext onError 前景音频播放错误事件', res); }); // -------------------- 监听中断事件 ----------------- // 监听音频因为系统占用而被中断开始事件 my.onAudioInterruptionBegin (audioInterruptionBeginListener); // 监听音频被中断结束事件 my.onAudioInterruptionEnd (audioInterruptionEndListener); }, // ------------------- 前景/背景音频播放事件 playAudio () { console.log ('innerAudioContext 播放前景音频'); this.innerAudioContext.src = 'XNDY2NTE2MjE4NA=='; this.innerAudioContext.play (); }, stopAudio () { console.log ('innerAudioContext 停止播放前景音频'); this.innerAudioContext.stop (); }, // 取消监听音频因为系统占用而被中断开始事件 offAudioInterruptionBegin () { my.offAudioInterruptionBegin (audioInterruptionBeginListener); console.log ('offAudioInterruptionBegin 取消监听音频中断开始事件'); }, // 取消监听音频因为系统占用而被中断结束事件 offAudioInterruptionEnd () { my.offAudioInterruptionEnd (audioInterruptionEndListener); console.log ('offAudioInterruptionEnd 取消监听音频中断结束事件'); }, }); ``` -------------------------------- ### Query Mini Programs Using Template (C#) Source: https://opendocs.alipay.com/mini/03l21s This C# code example shows how to invoke the alipay.open.mini.template.usage.query API. It covers the necessary setup for the Alipay client and request object. ```csharp AlipayClient client = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do?charset=UTF-8", "APP_ID", "APP_PRIVATE_KEY", "json", "UTF-8", "ALIPAY_PUBLIC_KEY", "RSA2"); AlipayOpenMiniTemplateUsageQueryRequest request = new AlipayOpenMiniTemplateUsageQueryRequest(); AlipayOpenMiniTemplateUsageQueryModel model = new AlipayOpenMiniTemplateUsageQueryModel(); model.TemplateId = "1"; model.PageNum = "1"; model.PageSize = "10"; model.TemplateVersion = "0.0.1"; model.BundleId = "com.alipay.alipaywallet"; request.BizModel = model; AlipayOpenMiniTemplateUsageQueryResponse response = client.Execute(request); if (response.IsSuccess) { Console.WriteLine("调用成功"); } else { Console.WriteLine("调用失败"); } ``` -------------------------------- ### 创建小程序项目 Source: https://opendocs.alipay.com/mini/01l9vi Use the create command to initiate a new, blank mini-program project. This command generates a local project that requires an appId for subsequent debugging and uploading. ```bash npm create mini # or yarn create mini ```