### Full Payment Configuration Example Source: https://doc.dcloud.net.cn/uniCloud/uni-pay/uni-app-x.html This example demonstrates the complete configuration for WeChat and Alipay payments across all platforms. Ensure to update the paths and credentials according to your specific setup. ```javascript const fs = require('fs'); const path = require('path') module.exports = { // 统一 - 支付回调地址,格式为 "服务空间ID":"URL化地址" "notifyUrl": { // 测试环境服务空间-支付回调地址 "mp-b267e273-19a7-4288-99c7-f6f27f9c5b77": "https://fc-mp-b267e273-19a7-4288-99c7-f6f27f9c5b77.next.bspapp.com/uni-pay-co", // 线上环境服务空间-支付回调地址(如果只有一个服务空间,则只需要配置线上环境服务空间即可) "mp-499e2a37-0c77-418a-82aa-3e5820ecb057": "https://fc-mp-499e2a37-0c77-418a-82aa-3e5820ecb057.next.bspapp.com/uni-pay-co", }, "notifyKey":"5FB2CD73C7B53918728417C50762E6D45FB2CD73C7B53918728417C50762E6D4", // 跨云函数通信时的加密密钥,建议手动改下,不要使用默认的密钥,长度保持在64位以上即可 // 微信支付相关 "wxpay": { "enable": true, // 是否启用微信支付 // 微信 - 小程序支付 "mp": { "appId": "", // 小程序的appid "secret": "", // 小程序的secret "mchId": "", // 商户id "key": "", // v2的api key "pfx": fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 "v3Key": "", // v3的api key "appCertPath": path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 "appPrivateKeyPath": path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 "version": 2, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - APP支付 "app": { "appId": "", // app开放平台下的应用的appid "secret": "", // app开放平台下的应用的secret "mchId": "", // 商户id "key": "", // v2的api key "pfx": fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 "v3Key": "", // v3的api key "appCertPath": path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 "appPrivateKeyPath": path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 "version": 2, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - 扫码支付 "native": { "appId": "", // 可以是小程序或公众号或app开放平台下的应用的任意一个appid "secret": "", // secret "mchId": "", // 商户id "key": "", // v2的api key "pfx": fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 "v3Key": "", // v3的api key "appCertPath": path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 "appPrivateKeyPath": path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 "version": 2, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - 公众号支付 "jsapi": { "appId": "", // 公众号的appid "secret": "", // 公众号的secret "mchId": "", // 商户id "key": "", // v2的api key "pfx": fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 "v3Key": "", // v3的api key "appCertPath": path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 "appPrivateKeyPath": path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 "version": 2, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - 手机外部浏览器H5支付 "mweb": { "appId": "", // 可以是小程序或公众号或app开放平台下的应用的任意一个appid "secret": "", // secret "mchId": "", // 商户id "key": "", // v2的api key "pfx": fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 "v3Key": "", // v3的api key "appCertPath": path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 "appPrivateKeyPath": path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 "version": 2, // 启用支付的版本 2代表v2版本 3 代表v3版本 // 场景信息,必填 "sceneInfo": { "h5_info": { "type": "Wap", // 此值固定Wap "wap_url": "", // 你的H5首页地址,必须和你发起支付的页面的域名一致。 "wap_name": "", // 你的H5网站名称 } } }, }, // 支付宝相关(加签方式选证书模式,加密算法选RSA2) "alipay": { "enable": true, // 是否启用支付宝支付 // 支付宝 - 小程序支付配置(由于uni-id目前只支持密钥模式,所以小程序支付的配置默认也是密钥模式的配置) "mp": { "appId": "", // 支付宝小程序appid "privateKey": "", // 支付宝商户私钥 "alipayPublicKey": "", // 支付宝公钥字符串 "sandbox": false }, // 支付宝 - APP支付配置 "app": { "appId": "", // 支付宝开放平台下应用的appid "privateKey": "", // 支付宝商户PKCS8格式的私钥 "appCertPath": path.join(__dirname, 'alipay/appCertPublicKey.crt'), // 支付宝商户公钥路径 "alipayPublicCertPath": path.join(__dirname, 'alipay/alipayCertPublicKey_RSA2.crt'), // 支付宝公钥路径 "alipayRootCertPath": path.join(__dirname, 'alipay/alipayRootCert.crt'), // 支付宝根证书路径 }, // 支付宝 - H5支付配置(包含:网站二维码、手机H5,需申请支付宝当面付接口权限) "native": { "appId": "", // 支付宝开放平台下应用的appid "privateKey": "", // 支付宝商户PKCS8格式的私钥 "appCertPath": path.join(__dirname, 'alipay/appCertPublicKey.crt'), // 支付宝商户公钥路径 "alipayPublicCertPath": path.join(__dirname, 'alipay/alipayCertPublicKey_RSA2.crt'), // 支付宝公钥路径 ``` -------------------------------- ### Run Plugin Installation Script Source: https://doc.dcloud.net.cn/uniCloud/uni-ai-x-openClaw.html Navigate into the cloned directory and execute the install script to set up the plugin. ```bash cd uni-ai-openclaw-channel-plugin && ./install.sh ``` -------------------------------- ### Configurable getTree Parameters Source: https://doc.dcloud.net.cn/uniCloud/jql?id=lookup-with-temp This example shows how to customize the tree traversal by specifying `limitLevel` to control the maximum depth and `startWith` to define the starting nodes for the query. ```APIDOC ## Configurable getTree Parameters ### Description Allows customization of the tree query by specifying the maximum depth (`limitLevel`) and the starting nodes (`startWith`). ### Method `get` with `getTree` object parameter ### Endpoint `db.collection("department").get({ getTree: { limitLevel: , startWith: } })` ### Parameters #### Request Body - **getTree** (object) - Enables tree traversal with specific configurations. - **limitLevel** (number) - Optional - The maximum depth of the tree to query (excluding the current level). Defaults to 10. Valid range is 1-15. - **startWith** (string) - Optional - A condition to specify the starting nodes for the query. If omitted, defaults to querying from root nodes (`parent_code=='' || parent_code==null`). ### Request Example ```javascript db.collection("department").get({ getTree: { limitLevel: 10, // Maximum query depth (excluding current level), defaults to 10, max 15, min 1 startWith: "parent_code=='' || parent_code==null" // Initial condition for the first level, can be omitted } }) ``` ### Response #### Success Response (200) - **data** (array) - An array of objects representing the nodes within the specified `limitLevel` and starting from the `startWith` condition. #### Response Example ```json { "data": [ { "_id": "5fe77207974b6900018c6c9c", "name": "总部", "parent_id": "", "status": 0, "children": [ { "_id": "5fe77232974b6900018c6cb1", "name": "一级部门A", "parent_id": "5fe77207974b6900018c6c9c", "status": 0, "children": [] } ] } ] } ``` ``` -------------------------------- ### Usage Example Source: https://doc.dcloud.net.cn/uniCloud/unicloud-city-select.html This example demonstrates how to integrate and use the unicloud-city-select component in a uni-app application. ```APIDOC ## Usage Example This example demonstrates how to integrate and use the unicloud-city-select component in a uni-app application. ```vue ``` ``` -------------------------------- ### Install Element UI in uni-admin Source: https://doc.dcloud.net.cn/uniCloud/admin?id=mutiladmin Install the Element UI library as a dependency for your uni-admin project using npm. ```bash npm i element-ui -S ``` -------------------------------- ### uni-id-permissions Table Example Source: https://doc.dcloud.net.cn/uniCloud/uni-id/summary Example data for the uni-id-permissions table, showing permission IDs and names. ```json { { "_id":"5f8428181c229600010389f6", "permission_id":"USER_EDIT", "permission_name":"修改用户", "created_date":1602495783272 }, { "_id":"5f842836d8daea0001906785", "permission_id":"USER_DEL", "permission_name":"删除用户", "created_date":1602495784372 } } ``` -------------------------------- ### uni-id-users Table Example Source: https://doc.dcloud.net.cn/uniCloud/uni-id/summary Example structure of the uni-id-users table, showing user information and their associated role IDs. ```json { { "_id":"5f8428181c229600010389f6", "username":"张三", "email":"zhangsan@dcloud.io", "role":[ "USER_ADMIN", "NOTICE_ADMIN" ], "created_date":1602495783272 } } ``` -------------------------------- ### uni-id-roles Table Example Source: https://doc.dcloud.net.cn/uniCloud/uni-id/summary Example data for the uni-id-roles table, illustrating role IDs, names, and associated permissions. ```json { { "_id":"5f8428181c229600010389f6", "role_id":"USER_ADMIN", "role_name":"人事管理", "permission":[ "USER_ADD", "USER_EDIT", "USER_DEL" ], "created_date":1602495783272 }, { "_id":"5f842836d8daea0001906785", "role_id":"NOTICE_ADMIN", "role_name":"公告管理", "permission":[ "NOTICE_ADD", "NOTICE_EDIT", "NOTICE_DEL" ], "created_date":1602495784372 } } ``` -------------------------------- ### Conditional Database Query with Get Method Source: https://doc.dcloud.net.cn/uniCloud/schema?id=autocode Illustrates how to use the `get` method for conditional database queries. The first example shows a valid query where `doc.shop_id` is a single, known value. The second example highlights an invalid use case where multiple possible values for `doc.shop_id` would cause the `get` method to return false without validation. ```javascript // This condition requires doc.shop_id to be '123123'. // get(`database.shop.${doc.shop_id}`) fetches the record from the shop table with ID 123123 to verify its owner matches the current user's UID. db.collection('street').where("shop_id=='123123'").get() ``` ```javascript // This condition allows doc.shop_id to be '123123' or '456456'. // ` ``` ```javascript // The `get(`database.shop.${doc.shop_id}`).owner == auth.uid` will directly return false without fetching shop table data for validation. db.collection('street').where("shop_id=='123123 || shop_id=='456456'").get() ``` -------------------------------- ### Verify Shop Owner with Get Method in Permissions Source: https://doc.dcloud.net.cn/uniCloud/schema?id=autocode This example demonstrates using the `get` method to verify if the owner of a shop matches the current user's UID. The `doc.shop_id` must be a unique identifier for the `get` method to work correctly. ```javascript "get(`database.shop.${doc.shop_id}`).owner == auth.uid" ``` -------------------------------- ### Aliyun Storage Configuration Example Source: https://doc.dcloud.net.cn/uniCloud/software/deploy.html Configuration for using Aliyun OSS as the file storage provider. Requires bucket, region, and access key details. ```json { "storage": { "provider": "aliyun", "bucket": "your-bucket-name", "region": "oss-cn-hangzhou", "accessKeyId": "your-access-key-id", "accessKeySecret": "your-access-key-secret", "cdnProtocol": "https://", "cdnDomain": "your-cdn-domain.com", "cdnRootPath": "/" } } ``` -------------------------------- ### Example GET Request with Fixed IP Source: https://doc.dcloud.net.cn/uniCloud/cf-functions?id=intro An example demonstrating how to use `uniCloud.httpProxyForEip.get` to fetch data, such as an access token from the WeChat API, ensuring the request originates from a fixed IP. ```javascript await uniCloud.httpProxyForEip.get( 'https://api.weixin.qq.com/cgi-bin/token', { grant_type: 'client_credential', appid: 'xxxx', secret: 'xxxx' } ) ``` -------------------------------- ### GET Request Event Structure Source: https://doc.dcloud.net.cn/uniCloud/cloud-obj.html Example of the event object received by a cloud object when accessed via a GET request with query parameters. Demonstrates how query parameters are parsed. ```json { path: '/${cloud object method name}', httpMethod: 'GET', headers: {HTTP request headers}, queryStringParameters: {a: "1", b: "2"}, isBase64Encoded: false } ``` -------------------------------- ### Local Storage Configuration Example Source: https://doc.dcloud.net.cn/uniCloud/software/deploy.html Configuration for using local storage as the file storage provider. Ensure the 'dir' path is correctly set. ```json { "storage": { "provider": "local", "dir": "file/upload", "cdnProtocol": "http://", "cdnDomain": "127.0.0.1:7001", "cdnRootPath": "/storage/file/", "storageSecret": "xxxxxxxxxx" } } ``` -------------------------------- ### Sample Department Data for startWith Explanation Source: https://doc.dcloud.net.cn/uniCloud/jql?id=lookup-with-temp This sample data illustrates the structure of department records, including `_id`, `name`, and `parent_id`, which is relevant for understanding the `startWith` parameter. ```json { "_id": "1", "name": "总部", "parent_id": "", "status": 0 } { "_id": "11", "name": "一级部门A", "parent_id": "1", "status": 0 } { "_id": "12", "name": "一级部门B", "parent_id": "1", "status": 1 } ``` -------------------------------- ### Get Invited User List Cloud Function Example Source: https://doc.dcloud.net.cn/uniCloud/uni-id/old.html Example of using uniID.getInvitedUser within a cloud function after checking the user's token. It retrieves up to 10 invited users and the total count. ```javascript // 云函数代码 const uniID = require('uni-id') exports.main = async function(event,context) { const payload = await uniID.checkToken(event.uniIdToken) if (payload.code) { return payload } const res = await uniID.getInvitedUser({ uid: payload.uid, limit: 10, offset: 0, needTotal: true }) return res } ``` -------------------------------- ### Add Record with Options Source: https://doc.dcloud.net.cn/uniCloud/unicloud-db?id=props This example shows how to add a record with additional options. These include customizing the success toast message and defining success, fail, and complete callbacks. ```javascript this.$refs.udb.add(value, { toastTitle: '新增成功', // toast提示语 success: (res) => { // 新增成功后的回调 const { code, message } = res }, fail: (err) => { // 新增失败后的回调 const { message } = err }, complete: () => { } }) ``` -------------------------------- ### Get Temporary File URL Source: https://doc.dcloud.net.cn/uniCloud/storage/dev Example of obtaining temporary download URLs for files stored in UniCloud. ```APIDOC ## Get Temporary File URL ### Description Retrieves temporary download URLs for specified files in UniCloud storage. This API is available on all major cloud platforms supported by UniCloud. ### Method `uniCloud.getTempFileURL(getTempFileURLOptions)` ### Parameters #### getTempFileURLOptions - **fileList** (Array) - Required - An array of file IDs for which to get download URLs. ### Response #### Success Response - **fileList** (Array) - Optional - An array containing file ID and its corresponding temporary URL. - **fileID** (string) - Required - The file ID. - **tempFileURL** (string) - Required - The temporary URL for accessing the file. - **requestId** (string) - Optional - The request ID for error tracing. ### Request Example ```javascript let result = await uniCloud.getTempFileURL({ fileList: ['cloud://test-28farb/a.png'] }); ``` ``` -------------------------------- ### Resume Schema Example Source: https://doc.dcloud.net.cn/uniCloud/schema?id=trim This example demonstrates how to define a schema for a 'resume' table, including field types, validation rules like min/max length, format, patterns, and trim settings. ```json { "bsonType": "object", "required": ["name", "birth_year", "tel", "email"], "permission": { "read": true, "create": true, "update": true, "delete": true }, "properties": { "_id": { "description": "ID,系统自动生成" }, "name": { "bsonType": "string", "title": "姓名", "trim": "both", "minLength": 2, "maxLength": 17 }, "birth_year": { "bsonType": "int", "title": "出生年份", "minimum": 1950, "maximum": 2020 }, "tel": { "bsonType": "string", "title": "手机号码", "pattern": "^\\+?[0-9-]{3,20}$", "trim": "both" }, "email": { "bsonType": "string", "title": "email", "format": "email", "trim": "both" }, "address": { "bsonType": "object", "title": "地址", "required": ["city"], "properties": { "city": { "bsonType": "string", "title": "城市" }, "street": { "bsonType": "string", "trim": "both" } } }, "intro":{ "bsonType": "string", "title": "简介", "trim": "both" } } } ``` -------------------------------- ### Uni-Pay Full Payment Configuration Example Source: https://doc.dcloud.net.cn/uniCloud/uni-pay/uni-app.html This example demonstrates the complete configuration for WeChat and Alipay payments across all platforms. It includes settings for notification URLs, communication keys, and detailed parameters for various WeChat payment types (MP, App, Native, JSAPI, Mweb), including API keys, certificates, and version selection. Ensure to replace placeholder values with your actual credentials and adjust paths for certificates. ```javascript const fs = require('fs'); const path = require('path'); module.exports = { // 统一 - 支付回调地址,格式为 "服务空间ID":"URL化地址" notifyUrl: { // 测试环境服务空间-支付回调地址 'mp-b267e273-19a7-4288-99c7-f6f27f9c5b77': 'https://fc-mp-b267e273-19a7-4288-99c7-f6f27f9c5b77.next.bspapp.com/uni-pay-co', // 线上环境服务空间-支付回调地址(如果只有一个服务空间,则只需要配置线上环境服务空间即可) 'mp-499e2a37-0c77-418a-82aa-3e5820ecb057': 'https://fc-mp-499e2a37-0c77-418a-82aa-3e5820ecb057.next.bspapp.com/uni-pay-co', }, notifyKey: '5FB2CD73C7B53918728417C50762E6D45FB2CD73C7B53918728417C50762E6D4', // 跨云函数通信时的加密密钥,建议手动改下,不要使用默认的密钥,长度保持在64位以上即可 // 微信支付相关 wxpay: { enable: true, // 是否启用微信支付 // 微信 - 小程序支付 mp: { appId: '', // 小程序的appid secret: '', // 小程序的secret mchId: '', // 商户id key: '', // v2的api key pfx: fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 v3Key: '', // v3的api key appCertPath: path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 appPrivateKeyPath: path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 wxpayPublicKeyPath: path.join(__dirname, 'wxpay/pub_key.pem'), // v3需要用到的证书 - 微信支付公钥证书(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数) wxpayPublicKeyId: '', // v3需要用到的微信支付公钥ID,值为以PUB_KEY_ID_开头的一串字符串(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数或注释掉此参数) version: 3, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - APP支付 app: { appId: '', // app开放平台下的应用的appid secret: '', // app开放平台下的应用的secret mchId: '', // 商户id key: '', // v2的api key pfx: fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 v3Key: '', // v3的api key appCertPath: path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 appPrivateKeyPath: path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 wxpayPublicKeyPath: path.join(__dirname, 'wxpay/pub_key.pem'), // v3需要用到的证书 - 微信支付公钥证书(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数) wxpayPublicKeyId: '', // v3需要用到的微信支付公钥ID,值为以PUB_KEY_ID_开头的一串字符串(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数或注释掉此参数) version: 3, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - 扫码支付 native: { appId: '', // 可以是小程序或公众号或app开放平台下的应用的任意一个appid secret: '', // secret mchId: '', // 商户id key: '', // v2的api key pfx: fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 v3Key: '', // v3的api key appCertPath: path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 appPrivateKeyPath: path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 wxpayPublicKeyPath: path.join(__dirname, 'wxpay/pub_key.pem'), // v3需要用到的证书 - 微信支付公钥证书(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数) wxpayPublicKeyId: '', // v3需要用到的微信支付公钥ID,值为以PUB_KEY_ID_开头的一串字符串(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数或注释掉此参数) version: 3, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - 公众号支付 jsapi: { appId: '', // 公众号的appid secret: '', // 公众号的secret mchId: '', // 商户id key: '', // v2的api key pfx: fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 v3Key: '', // v3的api key appCertPath: path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 appPrivateKeyPath: path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 wxpayPublicKeyPath: path.join(__dirname, 'wxpay/pub_key.pem'), // v3需要用到的证书 - 微信支付公钥证书(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数) wxpayPublicKeyId: '', // v3需要用到的微信支付公钥ID,值为以PUB_KEY_ID_开头的一串字符串(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数或注释掉此参数) version: 3, // 启用支付的版本 2代表v2版本 3 代表v3版本 }, // 微信 - 手机外部浏览器H5支付 mweb: { appId: '', // 可以是小程序或公众号或app开放平台下的应用的任意一个appid secret: '', // secret mchId: '', // 商户id key: '', // v2的api key pfx: fs.readFileSync(__dirname + '/wxpay/apiclient_cert.p12'), // v2需要用到的证书 v3Key: '', // v3的api key appCertPath: path.join(__dirname, 'wxpay/apiclient_cert.pem'), // v3需要用到的证书 appPrivateKeyPath: path.join(__dirname, 'wxpay/apiclient_key.pem'), // v3需要用到的证书 wxpayPublicKeyPath: path.join(__dirname, 'wxpay/pub_key.pem'), // v3需要用到的证书 - 微信支付公钥证书(仅限开启了微信支付公钥的商户,若已开通微信支付平台证书的商户可无视此参数) ``` -------------------------------- ### UniCloud get() Method with Single vs. Multiple Conditions Source: https://doc.dcloud.net.cn/uniCloud/schema?id=enum These examples illustrate how the get() method behaves with single and multiple conditions in a query. When a single condition is met, get() fetches and validates data. With multiple conditions (using '||'), get() may return false directly without fetching data if the conditions are not precisely matched. ```javascript // This condition ensures that doc.shop_id is '123123', and get(`database.shop.${doc.shop_id}`) fetches the record to verify its owner matches the current user's UID. db.collection('street').where("shop_id=='123123'").get() ``` ```javascript // This condition allows doc.shop_id to be '123123' or '456456'. The expression `"get(`database.shop.${doc.shop_id}`).owner == auth.uid"` will directly return false without fetching shop data for validation. db.collection('street').where("shop_id=='123123 || shop_id=='456456'").get() ``` -------------------------------- ### Validating Single Shop ID with Get Method Source: https://doc.dcloud.net.cn/uniCloud/schema?id=col-permission This example demonstrates how to use the `get` method to validate a single, specific `shop_id` against the shop owner's UID. The `doc.shop_id` must be a unique, known value for this to work correctly. ```javascript // This condition ensures that doc.shop_id is '123123', and then uses get(`database.shop.${doc.shop_id}`) to verify if the owner of the record with _id '123123' in the shop table matches the current user's UID. db.collection('street').where("shop_id=='123123'").get() ``` -------------------------------- ### Using $env variables for default values Source: https://doc.dcloud.net.cn/uniCloud/schema?id=enum Provides examples of using predefined environment variables like 'now', 'clientIP', and 'uid' for default values. ```json // Specify default value as true "defaultValue": true // Specify forced default value as current server timestamp "forceDefaultValue": { "$env": "now" } // Specify forced default value as current client IP "forceDefaultValue": { "$env": "clientIP" } // Specify forced default value as current customer ID "forceDefaultValue": { "$env": "uid" } ``` -------------------------------- ### Remove Session Key with uni-open-bridge Source: https://doc.dcloud.net.cn/uniCloud/uni-open-bridge.html Demonstrates removing a session key using the `removeSessionKey` function. Ensure the `uni-open-bridge-common` module is imported. The example shows setting, getting, removing, and then verifying the removal by attempting to get the key again, which should return null. ```javascript 'use strict'; const { getSessionKey, setSessionKey, removeSessionKey } = require('uni-open-bridge-common') exports.main = async (event, context) => { const key = { dcloudAppid: '__UNI__xxx', platform: 'weixin-mp', openid: '' } const value = { 'session_key': '' } const expiresIn = 7200 // 写入 (redis / 数据库) await setSessionKey(key, value, expiresIn) // 读取 (redis / 数据库) let result1 = await getSessionKey(key) // 删除 await removeSessionKey(key) // 删除后读取, 返回 null let result2 = await getSessionKey(key) console.log(result2) // null return null }; ``` -------------------------------- ### Two-Account Transfer Example Source: https://doc.dcloud.net.cn/uniCloud/cf-database?id=limit This example demonstrates a simple bank transfer between two accounts using `startTransaction`. It includes checks for account existence, updates amounts, and performs a rollback if the source account balance drops below zero. Note that `transaction.doc().get()` returns data that is not in an array format. ```javascript const db = uniCloud.database(); const dbCmd = db.command; exports.main = async (event) => { const transaction = await db.startTransaction(); try { const aaaRes = await transaction.collection('account').doc('aaa').get(); const bbbRes = await transaction.collection('account').doc('bbb').get(); if (aaaRes.data && bbbRes.data) { const updateAAARes = await transaction .collection('account') .doc('aaa') .update({ amount: dbCmd.inc(-10), }); const updateBBBRes = await transaction .collection('account') .doc('bbb') .update({ amount: dbCmd.inc(10), }); const aaaEndRes = await transaction.collection('account').doc('aaa').get(); if (aaaEndRes.data.amount < 0) { // 请注意transaction.doc().get()返回的data不是数组形式 await transaction.rollback(-100); return { success: false, error: `rollback`, rollbackCode: -100, }; } else { await transaction.commit(); console.log(`transaction succeeded`); return { success: true, aaaAccount: aaaRes.data.amount - 10, }; } } else { return { success: false, error: `rollback`, rollbackCode: -100, }; } } catch (e) { await transaction.rollback(); console.error(`transaction error`, e); return { success: false, error: e, }; } }; ``` -------------------------------- ### Get a substring from a Redis string Source: https://doc.dcloud.net.cn/uniCloud/redis Use this to retrieve a portion of a string value stored at a key, specified by start and end indices. ```javascript await redis.getrange('string-key', 0, 10) ``` -------------------------------- ### Configuring Default Values with Preset Variables Source: https://doc.dcloud.net.cn/uniCloud/schema Provides examples of setting default values for schema fields using preset variables. It shows how to set a simple boolean default, and how to use `$env` for server time, client IP, and user ID, ensuring data integrity and security. ```json // Specify default value as true "defaultValue": true ``` ```json // Specify forced default value as current server timestamp "forceDefaultValue": { "$env": "now" } ``` ```json // Specify forced default value as current client IP "forceDefaultValue": { "$env": "clientIP" } ``` ```json // Specify forced default value as current customer id "forceDefaultValue": { "$env": "uid" } ``` -------------------------------- ### Basic NoSQL Query Example Source: https://doc.dcloud.net.cn/uniCloud/jql?id=lookup-with-temp Demonstrates a basic NoSQL query using uniCloud.databaseForJQL() to fetch records from a collection. ```javascript // 注意,此处的db是通过 uniCloud.databaseForJQL() 得到,而不是 uniCloud.database() const db = uniCloud.databaseForJQL() let res = await db.collection('table').where({ field1: 'value1' }).get() ``` -------------------------------- ### Verify Signature in Univerify Cloud Function Source: https://doc.dcloud.net.cn/uniCloud/univerify Verify the incoming request signature in your Univerify cloud function when accessed from a self-hosted server. This example demonstrates verification for GET requests. ```javascript // 云函数验证签名,此示例中以接受GET请求为例作演示 const crypto = require('crypto') exports.main = async function (event){ const secret = 'your-secret-string' // 自己的密钥不要直接使用示例值,且注意不要泄露 const hmac = crypto.createHmac('sha256', secret); let params = event.queryStringParameters const sign = params.sign delete params.sign const signStr = Object.keys(params).sort().map(key => { return `${key}=${params[key]}` }).join('&') hmac.update(signStr); if(sign!==hmac.digest('hex')){ throw new Error('非法访问') } const { access_token, openid } = params const res = await uniCloud.getPhoneNumber({ provider: 'univerify', appid: 'xxx', // DCloud appid access_token: access_token, openid: openid }) // 返回手机号给自己服务器 return res } ``` -------------------------------- ### Query with Regular Expression Source: https://doc.dcloud.net.cn/uniCloud/cf-database?id=start-transaction Use a JavaScript `RegExp` object to perform pattern matching on string fields. This example finds users whose 'name' field starts with 'ABC'. ```javascript db.collection('user').where({ name: new RegExp('^ABC'), }); ``` -------------------------------- ### Example of Document Update Before and After Source: https://doc.dcloud.net.cn/uniCloud/jql Illustrates the state of a document before and after an update operation, showing how fields are modified. ```json // 更新前的数据 { "_id": "doc-id", "name": "Hello", "count": { "fav": 0, "follow": 0 } } // 更新后的数据 { "_id": "doc-id", "name": "Hey", "count": { "fav": 1, "follow": 0 } } ``` -------------------------------- ### Full getTree Query Example Source: https://doc.dcloud.net.cn/uniCloud/jql?id=lookup-with-temp This example demonstrates a complete JQL query using `getTree: {}` to fetch department data, including error handling and logging the results. ```javascript db.collection("department").get({ getTree: {} }) .then((res) => { const resdata = res.result.data console.log("resdata", resdata); }).catch((err) => { uni.showModal({ content: err.message || '请求服务失败', showCancel: false }) }).finally(() => { }) ``` -------------------------------- ### Get Daily Push Report - JavaScript Example Source: https://doc.dcloud.net.cn/uniCloud/uni-cloud-push/api.html This JavaScript snippet demonstrates how to call the `getReportByDate` method to retrieve daily push statistics for a specific application. It requires a date string in 'yyyy-MM-dd' format. ```javascript await uniPush.getReportByDate(date) ``` -------------------------------- ### JSON Data Import Example (Correct) Source: https://doc.dcloud.net.cn/uniCloud/hellodb?id=dbindex This example shows the correct format for JSON data when importing, especially for related fields like _id. Each line should be a standard JSON object. ```json // 每一行插入一个标准的 json 数据,不要用逗号分隔 {"title":"日常寒暄与社交","type":"main","parent_id":"","level":0} {"title":"购物与消费","type":"main","parent_id":"","level":0} {"title":"餐饮与美食","type":"main","parent_id":"","level":0} {"title":"休闲娱乐活动","type":"main","parent_id":"","level":0} ``` -------------------------------- ### Filter Nested JSON Fields Source: https://doc.dcloud.net.cn/uniCloud/jql?id=lookup-with-temp Filter specific fields within nested JSON structures using dot notation in the field() method. For example, to get only the 'vip' price from a nested 'price' object. ```json { "_id": "1", "title": "西游记", "author": "吴承恩", "price":{ "normal":10, "vip":8 } } ``` ```javascript db.collection('book').field("price.vip").get() ``` ```json { "_id": "1", "price":{ "vip":8 } } ```