### Get Visit Distribution Data Example (JavaScript) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/others/getVisitDistribution This snippet demonstrates how to use the wx-server-sdk to fetch visit distribution data for a WeChat Miniprogram. It initializes the SDK and calls the `getVisitDistribution` method with specified date parameters. The function returns the result of the API call or any caught errors. ```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.analysis.getVisitDistribution({ "beginDate": '20170313', "endDate": '20170313' }) return result } catch (err) { return err } } ``` -------------------------------- ### 获取加密scheme码 - 云调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme 使用 `wx-server-sdk` 在云函数中调用生成小程序scheme码的接口。此方式简化了服务器端调用的复杂性。 ```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.urlscheme.generate({ "jumpWxa": { "path": '/pages/publishHomework/publishHomework', "query": '' }, "isExpire": true, "expireTime": 1606737600 }) return result } catch (err) { return err } } ``` -------------------------------- ### Get Transaction Guarantee Status Response Example Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/transaction-guarantee/GetGuaranteeStatus Example of the JSON response from the GetGuaranteeStatus API. This shows the structure for both an activated and a non-activated transaction guarantee status. The response includes an error code, an 'isActived' boolean, a 'msg' string, and an optional 'reasons' array. ```JSON { "errcode": 0, "isActived": true, "msg": "已开通但未引入展示组件", "reasons": [] } ``` ```JSON { "errcode": 0, "isActived": false, "msg": "暂未达标「交易健康标准」,已达标「交易风险评级」,可通过缴纳保证金开通", "reasons": ["经营时长小于3年", "保证金余额不足"] } ``` -------------------------------- ### 查询加密URLLink - 云函数调用示例 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-link/queryUrlLink 使用 wx-server-sdk 在云函数中调用 openapi.urllink.query 接口查询 url_link 配置。 ```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.urllink.query({ "urlLink": 'https://wxaurl.cn/BQZRrcFCPvg' }) return result } catch (err) { return err } } ``` -------------------------------- ### Example Response for Getting All Logistics Accounts Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/express/express-by-business/getAllAccount This is an example of the JSON response returned when successfully calling the 'getAllAccount' API. It includes the total number of accounts and detailed information for each bound account, such as biz_id, delivery_id, and status. ```json { "count": 1, "list": [ { "biz_id": "123456789", "delivery_id": "YUNDA", "create_time": 1555482786, "update_time": 1556594799, "status_code": 0, "alias": "", "remark_wrong_msg": "", "remark_content": "", "quota_num": 55, "quota_update_time": 1556594799 } ] } ``` -------------------------------- ### 云函数调用获取性能数据 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getPerformance 使用wx-server-sdk在云函数中调用获取性能数据的接口。该方法简化了API调用流程,并提供了更友好的参数传递方式。 ```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.operation.getPerformance({ "device": '@_all', "networktype": '@_all', "scene": '@_all', "costTimeType": 2, "defaultStartTime": 1572339403, "defaultEndTime": 1574931403, "isDownloadCode": '@_all' }) return result } catch (err) { return err } } ``` -------------------------------- ### Get WeChat Mini Program QR Code - Request Data Example (Success) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getQRCode This is an example of the JSON request payload for successfully generating a WeChat Mini Program QR code via HTTP. It includes the 'path' of the page to open, the 'env_version' (e.g., 'release'), and the desired 'width' of the QR code. ```json { "path":"funpackage/questionsWall/questionInfo?question_id=22579", "env_version": "release", "width":280 } ``` -------------------------------- ### Get WeChat Mini Program QR Code - Request Data Example (Failure) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getQRCode This JSON example demonstrates a failed request to generate a WeChat Mini Program QR code, likely due to an invalid or empty 'path' parameter. The error message indicates 'invalid length for path or thedata is not json string'. ```json { "path":"", "env_version": "release", "width":280 } ``` -------------------------------- ### 获取关键词列表 - 云函数调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/getPubTemplateKeyWordsById 使用`wx-server-sdk`在云函数中调用接口获取模板下的关键词列表。需初始化云开发环境,并传入模板标题id(tid)。 ```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.subscribeMessage.getPubTemplateKeyWordsById({ "tid": '' }) return result } catch (err) { return err } } ``` -------------------------------- ### 获取小程序类目 - 云调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/getCategory 使用 `wx-server-sdk` 的云调用方式获取小程序类目。此方法适用于在云函数环境中调用。入参和 HTTPS 调用相同,返回结果包含类目列表。 ```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.subscribeMessage.getCategory({}) return result } catch (err) { return err } } ``` -------------------------------- ### Get Gray Release Plan - JSON Response Example Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getGrayReleasePlan Sample JSON response from the getGrayReleasePlan API containing error codes, status message, and gray release plan details including status codes (0-4), creation timestamp, gray percentage, and boolean flags for debugger and experiencer prioritization. ```json { "errcode": 0, "errmsg": "ok", "gray_release_plan": { "status": 1, "create_timestamp": 1517553721, "gray_percentage": 8, "support_experiencer_first": true, "support_debuger_first": true } } ``` -------------------------------- ### 下发客服输入状态(云函数调用) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/kf-mgnt/kf-message/setTyping 使用`wx-server-sdk`在云函数中调用`setTyping`接口,简化服务端调用流程。该方法需要初始化云开发环境,并通过`cloud.openapi.customerServiceMessage.setTyping`方法传入用户OpenID和command。 ```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.customerServiceMessage.setTyping({ "touser": 'OPENID', "command": 'Typing' }) return result } catch (err) { return err } } ``` -------------------------------- ### Verify Login Session (HTTP GET) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/checkSessionKey This section describes how to verify the validity of a user's session key on the server-side using an HTTP GET request. It explains that the session key is private and verified through a signature, and it can become invalid due to expiration or renewal. The API endpoint, required parameters like `access_token`, `openid`, `signature`, and `sig_method`, and example requests and responses are provided. ```HTTP GET https://api.weixin.qq.com/wxa/checksession?access_token=ACCESS_TOKEN&signature=SIGNATURE&openid=OPENID&sig_method=SIG_METHOD ``` ```HTTP GET https://api.weixin.qq.com/wxa/checksession?access_token=OsAoOMw4niuuVbfSxxxxxxxxxxxxxxxxxxx&signature=fefce01bfba4670c85b228e6ca2b493c90971e7c442f54fc448662eb7cd72509&openid=oGZUI0egBJY1zhBYw2KhdUfwVJJE&sig_method=hmac_sha256 ``` ```JSON {"errcode": 0, "errmsg": "ok"} ``` -------------------------------- ### Get CloudID Data via Cloud Call (Node.js) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/cloudbase/getOpenData This Node.js example shows how to use the `wx-server-sdk` to call the `getOpenData` API for retrieving cloudID-associated data. It utilizes cloud functions and requires the SDK to be initialized. ```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.cloudbase.getOpenData({ "cloudidList": [ "xxx" ] }) return result } catch (err) { return err } } ``` -------------------------------- ### 云调用获取客服消息临时素材 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/kf-mgnt/kf-message/getTempMedia 使用 `wx-server-sdk` 的云调用方式获取客服消息中的临时素材。此方法支持在云函数中调用,需确保 `wx-server-sdk` 版本 >= `0.4.0`。返回结果包含错误码、错误信息、内容类型和图片 Buffer。 ```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.customerServiceMessage.getTempMedia({ "mediaId": '' }) return result } catch (err) { return err } } ``` -------------------------------- ### 修改动态消息 HTTPS 请求 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/updatable-message/setUpdatableMsg 通过 HTTPS POST 方法调用修改动态消息接口。需要提供 access_token 作为 URL 参数,activity_id 用于标识动态消息,target_state 指定消息状态,template_info 包含需要修改的参数列表。 ```http POST https://api.weixin.qq.com/cgi-bin/message/wxopen/updatablemsg/send?access_token=ACCESS_TOKEN ``` -------------------------------- ### HTTP Request for Unlimited QR Code (POST) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode This example demonstrates how to make an HTTPS POST request to the WeChat API to generate an unlimited QR code. It includes the API endpoint and sample request body. ```http POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN { "page": "pages/index/index", "scene": "a=1", "check_path": true, "env_version": "release" } ``` -------------------------------- ### Node.js AES256_GCM Encryption Example Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/getting_started/api_signature Demonstrates how to perform AES256_GCM encryption for WeChat Mini Program API requests using Node.js. It includes functions to get context, raw request data, and generate the encrypted request payload with IV, data, and authentication tag. Note: Sensitive information should not be hardcoded. ```javascript // AES256_GCM const crypto = require("crypto") // 仅做演示,敏感信息请勿硬编码 function getCtx() { let ctx = { local_sym_key: "otUpngOjU+nVQaWJIC3D/yMLV17RKaP6t4Ot9tbnzLY=", local_sym_sn: "fa05fe1e5bcc79b81ad5ad4b58acf787", local_appid: "wxba6223c06417af7b", url_path: "https://api.weixin.qq.com/wxa/getuserriskrank" } return ctx } function getRawReq() { let req = { appid: "wxba6223c06417af7b", openid: "oEWzBfmdLqhFS2mTXCo2E4Y9gJAM", scene: 0, client_ip: "127.0.0.1", } return req } function getNewReq(ctx, req) { const { local_sym_key, local_sym_sn, local_appid, url_path } = ctx // 开发者本地信息 const local_ts = Math.floor(Date.now() / 1000) //加密签名使用的统一时间戳 const nonce = crypto.randomBytes(16).toString('base64').replace(/=/g, '') const reqex = { _n: nonce, _appid: local_appid, _timestamp: local_ts } const real_req = Object.assign({}, reqex, req) // 生成并添加安全校验字段 const plaintext = JSON.stringify(real_req) const aad = `${url_path}|${local_appid}|${local_ts}|${local_sym_sn}` const real_key = Buffer.from(local_sym_key, "base64") const real_iv = crypto.randomBytes(12) const real_aad = Buffer.from(aad, "utf-8") const real_plaintext = Buffer.from(plaintext, "utf-8") const cipher = crypto.createCipheriv("aes-256-gcm", real_key, real_iv) cipher.setAAD(real_aad) let cipher_update = cipher.update(real_plaintext) let cipher_final = cipher.final() const real_ciphertext = Buffer.concat([cipher_update, cipher_final]) const real_authTag = cipher.getAuthTag() const iv = real_iv.toString("base64") const data = real_ciphertext.toString("base64") const authtag = real_authTag.toString("base64") const req_data = { iv, data, authtag, } const new_req = { req_ts: local_ts, req_data: JSON.stringify(req_data) } return new_req } const ctx = getCtx() const req = getRawReq() let res = getNewReq(ctx, req) console.log(res) ``` -------------------------------- ### 获取用户访问小程序数据概况 (云调用) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/others/getDailySummary 使用wx-server-sdk的云调用功能获取用户访问小程序数据的概况。此方法适用于在云函数中进行调用,简化了鉴权流程。需确保`wx-server-sdk`版本 >= `0.4.0`。 ```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.analysis.getDailySummary({ "beginDate": '20170313', "endDate": '20170313' }) return result } catch (err) { return err } } ``` -------------------------------- ### 下载商品讲解视频 - 云调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/livebroadcast/studio-management/downloadGoodsVideo 使用云调用方式下载商品讲解视频。此方式与HTTPS调用共享相同的出入参。推荐使用`wx-server-sdk` >= `0.4.0`,接口方法为 `openapi.liveBroadcast.goodsVideo`。 ```javascript // 示例:使用 wx-server-sdk 调用 const cloud = require('wx-server-sdk'); cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }); exports.main = async (event) => { const { roomId, goodsId } = event; try { const result = await cloud.openapi.liveBroadcast.goodsVideo({ roomId: roomId, goodsId: goodsId }); return result; } catch (err) { return err; } } ``` -------------------------------- ### Example Response Data for Get Visit Distribution (JSON) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/others/getVisitDistribution This JSON object represents a typical response from the `getVisitDistribution` API. It includes the reference date and a list of data points categorized by index, such as session counts, stay time, and depth. Each data point contains key-value pairs representing specific metrics. ```json { "ref_date": "20170313", "list": [ { "index": "access_source_session_cnt", "item_list": [ { "key": 10, "value": 5 }, { "key": 8, "value": 687 }, { "key": 7, "value": 10740 }, { "key": 6, "value": 1961 }, { "key": 5, "value": 677 }, { "key": 4, "value": 653 }, { "key": 3, "value": 1120 }, { "key": 2, "value": 10243 }, { "key": 1, "value": 116578 } ] }, { "index": "access_staytime_info", "item_list": [ { "key": 8, "value": 16329 }, { "key": 7, "value": 19322 }, { "key": 6, "value": 21832 }, { "key": 5, "value": 19539 }, { "key": 4, "value": 29670 }, { "key": 3, "value": 19667 }, { "key": 2, "value": 11794 }, { "key": 1, "value": 4511 } ] }, { "index": "access_depth_info", "item_list": [ { "key": 5, "value": 217 }, { "key": 4, "value": 3259 }, { "key": 3, "value": 32445 }, { "key": 2, "value": 63542 }, { "key": 1, "value": 43201 } ] } ] } ``` -------------------------------- ### 查询直播间小助手 - 云调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/livebroadcast/studio-management/getAssistantList 使用云调用方式查询直播间小助手列表,简化了服务端调用的复杂性。具体调用方法和入参与HTTPS调用相同,需引入wx-server-sdk。 ```JavaScript // 假设已初始化 wx-server-sdk // openapi.liveBroadcast.getAssistantList({"roomId": 6491}); ``` -------------------------------- ### Query Mini Program Domain Info via Cloud Function Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getDomainInfo This example demonstrates how to invoke the getDomainInfo API from within a WeChat Cloud Function. It uses the wx-server-sdk to make the call. The function initializes the cloud environment and then calls the operation.getDomainInfo method with an optional action. The result or any errors are returned. ```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.operation.getDomainInfo({ "action": '' }) return result } catch (err) { return err } } ``` -------------------------------- ### 小程序直播添加商品云调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/livebroadcast/commodity-management/addGoods 通过云调用方式实现小程序直播商品添加功能。与 HTTPS 调用参数相同,接口方法名为 'openapi.liveBroadcast.goodsAdd'。需要引入 'wx-server-sdk' 且版本 >= 0.4.0。 ```JavaScript // 示例:使用 wx-server-sdk 进行云调用 // const cloud = require('wx-server-sdk'); // cloud.init(); // async function addGoods(goodsInfo) { // try { // const result = await cloud.openapi.liveBroadcast.goodsAdd({ // goodsInfo: goodsInfo // }); // return result; // } catch (error) { // console.error('Error adding goods:', error); // throw error; // } // } ``` -------------------------------- ### ID Card OCR - HTTPS API with Image URL Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/img-ocr/ocr/idCardOCR Shows how to call the WeChat ID Card OCR API using HTTPS GET method with an image URL parameter. This example performs back-side ID card recognition by passing an encoded image URL instead of uploading the image directly. ```bash curl https://api.weixin.qq.com/cv/ocr/idcard?type=photo&img_url=ENCODE_URL&access_token=ACCESS_TOCKEN ``` -------------------------------- ### 查询 license 资源包列表 API - HTTPS 调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/hardware-device/getLicensePkgList 通过 HTTPS POST 请求查询小程序已购买的 license 资源包列表信息。请求 URL 包含 access_token,请求 Body 中需提供 pkg_type 参数指定资源包类型。 ```HTTP POST https://api.weixin.qq.com/wxa/business/license/getpkglist?access_token=ACCESS_TOKEN ``` -------------------------------- ### 查询短信记录 (云调用) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/cloudbase/describeSmsRecords 通过云调用方式查询短信记录,适用于云函数内。需引入 `wx-server-sdk` 并初始化。入参和 HTTPS 调用相同,返回结果包含 `Response` 和 `errMsg`。 ```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({ convertCase: false }).cloudbase.describeSmsRecords({ "PostData": { "StartDate": '2021-03-01', "EndDate": '2021-03-23', "EnvId": 'xxx', "QueryId": 'xxx', "PageNumber": 1, "PageSize": 20 } }) return result } catch (err) { return err } } ``` -------------------------------- ### Alternative Response Data for Get Visit Distribution (JSON) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/others/getVisitDistribution This JSON object is an alternative response format for the `getVisitDistribution` API, potentially from a different version or context. It closely mirrors the previous example but uses slightly different key names (e.g., `refDate` instead of `ref_date`, `itemList` instead of `item_list`) and includes an `errMsg` field to indicate the status of the operation. ```json { "refDate": "20170313", "list": [ { "index": "access_source_session_cnt", "itemList": [ { "key": 10, "value": 5 }, { "key": 8, "value": 687 }, { "key": 7, "value": 10740 }, { "key": 6, "value": 1961 }, { "key": 5, "value": 677 }, { "key": 4, "value": 653 }, { "key": 3, "value": 1120 }, { "key": 2, "value": 10243 }, { "key": 1, "value": 116578 } ] }, { "index": "access_staytime_info", "itemList": [ { "key": 8, "value": 16329 }, { "key": 7, "value": 19322 }, { "key": 6, "value": 21832 }, { "key": 5, "value": 19539 }, { "key": 4, "value": 29670 }, { "key": 3, "value": 19667 }, { "key": 2, "value": 11794 }, { "key": 1, "value": 4511 } ] }, { "index": "access_depth_info", "itemList": [ { "key": 5, "value": 217 }, { "key": 4, "value": 3259 }, { "key": 3, "value": 32445 }, { "key": 2, "value": 63542 }, { "key": 1, "value": 43201 } ] } ], "errMsg": "openapi.analysis.getVisitDistribution:ok" } ``` -------------------------------- ### 发送订阅消息 - 云函数调用示例 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/sendMessage 使用`wx-server-sdk`在云函数中调用发送订阅消息的API。支持云调用,简化了服务器端逻辑。 ```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.subscribeMessage.send({ "touser": 'OPENID', "page": 'index', "lang": 'zh_CN', "data": { "number01": { "value": '339208499' }, "date01": { "value": '2015年01月05日' }, "site01": { "value": 'TIT创意园' }, "site02": { "value": '广州市新港中路397号' } }, "templateId": 'TEMPLATE_ID', "miniprogramState": 'developer' }) return result } catch (err) { return err } } ``` -------------------------------- ### Get WeChat Mini Program QR Code - Cloud Call Example Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getQRCode This code snippet illustrates how to generate a WeChat Mini Program QR code using the WeChat Cloud SDK. It initializes the cloud environment and then calls the 'wxacode.get' method with parameters for 'path' and 'width'. This method is suitable for server-side or cloud-based operations within the WeChat ecosystem. ```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 } } ``` -------------------------------- ### 查询运单轨迹 - 云函数调用示例 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/express/express-by-business/getPath 提供了使用`wx-server-sdk`在云函数中调用查询运单轨迹API的示例。该示例展示了如何初始化云开发环境并调用`cloud.openapi.logistics.getPath`方法。 ```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.logistics.getPath({ "openid": 'oABC123456', "orderId": '01234567890123456789', "deliveryId": 'SF', "waybillId": '123456789' }) return result } catch (err) { return err } } ``` -------------------------------- ### Get Transaction Guarantee Status (HTTPS GET) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/transaction-guarantee/GetGuaranteeStatus This snippet demonstrates how to call the GetGuaranteeStatus API using an HTTPS GET request. The API is used to fetch the status of the transaction guarantee feature. It requires an access token as a URL parameter. The response indicates whether the feature is active and provides related messages or reasons. ```HTTP GET https://api.weixin.qq.com/wxaapi/wxamptrade/get_guarantee_status?access_token=ACCESS_TOKEN ``` -------------------------------- ### 获取用户访问小程序月留存 - 云调用 Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/visit-retain/getMonthlyRetain 使用 wx-server-sdk 在云函数中调用获取用户访问小程序月留存的接口。支持云调用,需确保开发者工具和 sdk 版本符合要求。 ```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.analysis.getMonthlyRetain({ "beginDate": '20170201', "endDate": '20170228' }) return result } catch (err) { return err } } ``` -------------------------------- ### HTTPS GET request - Get Live Broadcast Push URL Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/livebroadcast/studio-management/getPushUrl Makes an HTTPS GET request to retrieve the push stream address for a live broadcast room. Requires a valid access_token and roomId as parameters. Returns an RTMP push address that can be used for streaming. ```http GET https://api.weixin.qq.com/wxaapi/broadcast/room/getpushurl?access_token=ACCESS_TOKEN ``` -------------------------------- ### 获取访问页面数据 (云调用) Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/others/getVisitPage 该接口可以通过云调用方式获取小程序访问页面数据,支持云函数调用。需引入 `wx-server-sdk` 且版本 >= `0.4.0`。调用方式与 HTTPS 调用类似,但使用云调用的方法名 `openapi.analysis.getVisitPage`。 ```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.analysis.getVisitPage({ "beginDate": '20170313', "endDate": '20170313' }) return result } catch (err) { return err } } ``` ```JSON { "refDate": "20170313", "list": [ { "pagePath": "pages/main/main.html", "pageVisitPv": 213429, "pageVisitUv": 55423, "pageStaytimePv": 8.139198, "entrypagePv": 117922, "exitpagePv": 61304, "pageSharePv": 180, "pageShareUv": 166 }, { "pagePath": "pages/linedetail/linedetail.html", "pageVisitPv": 155030, "pageVisitUv": 42195, "pageStaytimePv": 35.462395, "entrypagePv": 21101, "exitpagePv": 47051, "pageSharePv": 47, "pageShareUv": 42 }, { "pagePath": "pages/search/search.html", "pageVisitPv": 65011, "pageVisitUv": 24716, "pageStaytimePv": 6.889634, "entrypagePv": 1811, "exitpagePv": 3198, "pageSharePv": 0, "pageShareUv": 0 }, { "pagePath": "pages/stationdetail/stationdetail.html", "pageVisitPv": 29953, "pageVisitUv": 9695, "pageStaytimePv": 7.558508, "entrypagePv": 1386, "exitpagePv": 2285, "pageSharePv": 0, "pageShareUv": 0 }, { "pagePath": "pages/switch-city/switch-city.html", "pageVisitPv": 8928, "pageVisitUv": 4017, "pageStaytimePv": 9.22659, "entrypagePv": 748, "exitpagePv": 1613, "pageSharePv": 0, "pageShareUv": 0 } ], "errMsg": "openapi.analysis.getVisitPage:ok" } ``` -------------------------------- ### Example Data Response for Live Room Information Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/livebroadcast/studio-management/getLiveInfo This JSON structure represents a successful response when querying live room information. It includes details about the room, such as its ID, name, status, start and end times, anchor information, and associated goods. It also outlines various settings like whether comments, likes, or goods are enabled, and whether replays are available. The 'errcode' and 'errmsg' fields indicate the success or failure of the API call. ```json { "errcode": 0, "errmsg": "ok", "total":1, "room_info":[ { "name":"直播房间名", "roomid": 1, "cover_img":"http://http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\Rl1RuuhdstSfZa8EEljedAYcbtX3Ejpdl2et1tPAQ37bdicnxoVialDLCKKDcPBy8Iic0kCiaiaalXg3EbpNKoicrweQ\/0?wx_fmt=jpeg", "share_img":"http://http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\Rl1RuuhdstSfZa8EEljedAYcbtX3Ejpdl2et1tPAQ37bdicnxoVialDLCKKDcPBy8Iic0kCiaiaalXg3EbpNKoicrweQ\/0?wx_fmt=jpeg", "live_status": 101, "start_time": 1568128900, "end_time": 1568131200, "anchor_name":"里斯", "goods":[ { "cover_img":"http://http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\Rl1RuuhdstSfZa8EEljedAYcbtX3Ejpdl2et1tPAQ37bdicnxoVialDLCKKDcPBy8Iic0kCiaiaalXg3EbpNKoicrweQ\/0?wx_fmt=jpeg", "url":"pages\/index\/index.html", "name":"茶杯", "price": 1889, "price2": 0, "price_type": 1, "goods_id": 256, "third_party_appid": "wx3d0fae56402d8a81" } ], "live_type": 0, "close_like": 0, "close_goods": 0, "close_comment": 0, "close_kf": 1, "close_replay": 1, "is_feeds_public": 0, "creater_openid": "oawjt4t9NWZV2BYaEPA89sh1XblE", "feeds_img": "XXX" } ] } ``` -------------------------------- ### Get Printer HTTPS API Endpoint Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/express/express-by-business/getPrinter Direct HTTPS GET request to retrieve all printer operators. This endpoint requires a valid access_token as a URL parameter. The API returns printer count, list of operator openids, and associated tag IDs. ```http GET https://api.weixin.qq.com/cgi-bin/express/business/printer/getall?access_token=ACCESS_TOKEN ``` -------------------------------- ### POST /wxaapi/broadcast/room/create Source: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/livebroadcast/studio-management/createRoom Use this endpoint to create a live room. The request should be made on the server-side and supports cloud calls. Ensure your developer tool version and wx-server-sdk are up-to-date. ```APIDOC ## POST /wxaapi/broadcast/room/create ### Description Creates a live room that will be displayed in the live room list upon successful creation. ### Method POST ### Endpoint https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token=ACCESS_TOKEN ### Parameters #### Query Parameters - **access_token** (string) - Required - The access token for authentication. #### Request Body - **name** (string) - Required - The name of the live room. Minimum 3 Chinese characters, maximum 17 Chinese characters. - **coverImg** (string) - Required - The cover image URL, obtained via `uploadfile` and filled with mediaID. Image rules: Recommended 1080*1920 pixels, size not exceeding 2MB. - **startTime** (number) - Required - The planned start time of the live broadcast. Must be at least 10 minutes from the current time and not more than 6 months in the future. - **endTime** (number) - Required - The planned end time of the live broadcast. The interval between start and end times must be between 30 minutes and 24 hours. - **anchorName** (string) - Required - The nickname of the anchor. Minimum 2 Chinese characters, maximum 15 Chinese characters. - **anchorWechat** (string) - Required - The WeChat ID of the anchor. If not verified, the anchor must undergo real-name verification in the 'Mini Program Live' mini program. - **subAnchorWechat** (string) - Optional - The WeChat ID of the sub-anchor. If not verified, the sub-anchor must undergo real-name verification in the 'Mini Program Live' mini program. - **createrWechat** (string) - Optional - The WeChat ID of the creator. If not provided, the live room is visible to all members. If provided, only the creator, administrators, super administrators, and the anchor can see the room. - **shareImg** (string) - Required - The share image URL, obtained via `uploadfile` and filled with mediaID. Image rules: Recommended 800*640 pixels, size not exceeding 1MB. - **feedsImg** (string) - Required - The cover image for the shopping live channel, obtained via `uploadfile` and filled with mediaID. Image rules: Recommended 800*800 pixels, size not exceeding 100KB. - **isFeedsPublic** (number) - Optional - Whether to enable official inclusion. 1 for enabled, 0 for disabled. Defaults to enabled. - **type** (number) - Required - The type of live room. 1 for push stream, 0 for mobile live. - **closeLike** (number) - Required - Whether to close likes. 0 for enabled, 1 for closed. If closed, the like button will be hidden for viewers and cannot be enabled after the broadcast starts. - **closeGoods** (number) - Required - Whether to close the goods shelf. 0 for enabled, 1 for closed. If closed, the goods shelf will be hidden for viewers and cannot be enabled after the broadcast starts. - **closeComment** (number) - Required - Whether to close comments. 0 for enabled, 1 for closed. If closed, the comment entry will be hidden for viewers and cannot be enabled after the broadcast starts. - **closeReplay** (number) - Optional - Whether to close replay. 0 for enabled, 1 for closed. Defaults to closed. Can be enabled after the broadcast starts. - **closeShare** (number) - Optional - Whether to close sharing. 0 for enabled, 1 for closed. Defaults to enabled. Cannot be modified after the broadcast starts. - **closeKf** (number) - Optional - Whether to close customer service. 0 for enabled, 1 for closed. Defaults to closed. Can be enabled after the broadcast starts. ### Request Example ```json { "name": "测试直播房间1", "coverImg": "", "startTime": 1588237130, "endTime": 1588237130, "anchorName": "zefzhang1", "anchorWechat": "WxgQiao_04", "subAnchorWechat": "WxgQiao_03", "createrWechat": "test_creater", "shareImg": "hw7zsntcr0rE-RBfBAaF553DqBk-J02UtWsP8VqrUh3tKu3jO_JwEO8n1cWTJ5TN", "feedsImg": "hw7zsntcr0rE-RBfBAaF553DqBk-J02UtWsP8VqrUh3tKu3jO_JwEO8n1cWTJ5TN", "isFeedsPublic": 1, "type": 1, "closeLike": 0, "closeGoods": 0, "closeComment": 0, "closeReplay": 1, "closeShare": 0, "closeKf": 0 } ``` ### Response #### Success Response (200) - **roomId** (number) - The ID of the created live room. - **qrcode_url** (string) - The QR code URL for the 'Mini Program Live' mini program. This is returned if the anchor's WeChat ID has not undergone real-name verification. #### Response Example ```json { "roomId": 33, "errcode": 0, "qrcode_url": "https://res.wx.qq.com/op_res/9rSix1dhHfK4rR049JL0PHJ7TpOvkuZ3mE0z7Ou_Etvjf-w1J_jVX0rZqeStLfwh" } ``` ### Error Handling - **-1**: System error. Please try again later. - **40001**: Invalid credential, access_token is invalid or not latest. Check if the AppSecret is correct or if you are calling the API for the correct account. - **200002**: Parameter error. - **300002**: Name length does not meet the rules. - **300028**: Room name violates regulations. - **300031**: Live room cover image is non-compliant. - **300032**: Live room share image violates regulations. - **300034**: Anchor WeChat nickname length does not meet requirements. - **300036**: Anchor WeChat ID is not real-name verified. - **300037**: Shopping live channel cover image is non-compliant. - **300039**: Sub-anchor WeChat ID is invalid. - **300040**: Name contains non-limited characters (special characters). - **300041**: Creator WeChat ID is invalid. ```