> ## Documentation Index
> Fetch the complete documentation index at: https://docs.billbuddyhq.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 向 By agreement DDR 推送扣费计划

> ### 按扣费计划类型填写

必须提供 `merchant_id`、`plan_id`、`type`、`amount` 和 `start_date`。目标 DDR 须已激活并绑定支付方式，且允许添加新的扣费计划。

| type | 计划类型 | 额外必填参数 |
| --- | --- | --- |
| 1 | 按成功期数 | `day_of_debit`、`end_terms` |
| 2 | 按累计金额 | `day_of_debit`、`total_amount` |
| 3 | 持续至取消 | `day_of_debit` |
| 4 | 按结束日期 | `day_of_debit`、`end_date`，结束日不得早于 `start_date` |
| 6 | 一次性 | 不要求 `day_of_debit` |

季度、半年、年度频率须提供 `day_of_debit_dtstart`。自定义频率须提供 `process_type=12`、`custom_cycle_type` 和 `custom_cycle`，并与 RRULE 一致。起算日期、首次扣费日期及完整取值限制见字段说明。

仅可向已激活且已绑定支付方式的 By agreement DDR 添加扣费计划，使用该 DDR 的支付方式。若存在任何 Paused 扣费计划（包括 Deposit 押金），须先恢复或取消；若存在 Active 的非 Deposit 扣费计划，须待其结束或取消后再添加。非标准 RRULE 须提供 process_type=12、custom_cycle_type 及 custom_cycle。start_date 不得早于 DDR 起算日；实际首次扣费日期不得早于服务业务时区的明天，并须符合 DDR 的起算日及频率规则。请同时保留响应的 plan_id 和 schedule_no。

所有示例均为格式示例，客户、订单、卡及账户数据须替换为测试环境获准使用的数据。BASE_URL 为服务根域名，不附加 /api/v2；ACCESS_TOKEN 为 /oauth/token 返回的 access_token。日期示例为 2030 年，执行时请改为满足当前日期限制的实际日期。



## OpenAPI

````yaml /openapi/billbuddy-v2-openapi.yaml post /api/v2/subscription/createSchedule
openapi: 3.0.3
info:
  title: BillBuddy API 接入文档
  version: 2.0.0
  description: >
    BillBuddy API
    接入文档，本文收录第三方服务端主动调用的认证、交易和订阅接口。请求与响应示例均使用完整但虚构的业务数据及离线生成的演示令牌，不能用于实际认证或交易。


    ## 接入步骤

    1. 向 BillBuddy 获取 Client ID、Client Secret、商户标识及业务标识。如启用 IP 白名单，请使用已获准的固定出口
    IP 调用。

    2. 通过 POST /oauth/token 获取 access_token。业务请求携带 Authorization: Bearer
    {access_token} 和 Accept: application/json。JSON 请求使用 Content-Type:
    application/json；获取令牌使用表单。

    3. 按需调用支付或订阅接口。客户通过 activation_url 打开托管激活页；Client Secret 仅可保存在商户服务端。


    ## 标识及金额

    商户身份由 OAuth 凭据确定，无需在请求中传 business_id。需要指定业务的接口使用 merchant_id；单笔交易查询和批次结果查询的
    merchant_id 可选，省略或为空时在当前商户全部业务范围内查询；交易列表使用可选的
    Mid（区分大小写），省略时查询当前商户的全部业务。业务标识必须属于凭据所属商户。响应中的标识请按各接口字段说明读取。

    除 TXT 批量上传文件及其 amount_cents/declared_total_amount_cents
    使用分外，金额使用主货币单位，最多两位小数，例如 10.50 表示 AUD 10.50。银行账号、卡号、月份、年份和邮编建议使用字符串，以保留前导零。


    ## 成功和失败

    业务 JSON 成功 code=0，常规失败 code=1。交易及订阅业务接口参数校验失败通常为 code=400、data={}，HTTP 状态仍为
    200。V2 业务接口认证失败为 code=1，plan/list 标识业务校验失败为 code=1。HTTP 429 表示请求超过频率限制。OAuth
    端点采用标准 OAuth 响应（HTTP 200/400/401/429）。

    code=0 表示接口处理成功，扣款结果须另行判断：批量 accepted 仅表示请求已受理，将异步处理；银行 Pending、预约 Pending 和
    3DS 待验证均不代表支付成功。交易、DDR 订阅和扣费计划各自使用不同的 status 枚举，请参阅对应字段说明。


    ## 日期及频率

    请求日期建议使用 YYYY-MM-DD。今天及明天均按服务业务时区 Australia/Sydney 计算（适用夏令时）；预约取消时间以
    Australia/Sydney 为准（适用夏令时），仅允许在处理日 08:15 之前取消，到达该时刻即不可取消。支付 complete_date
    与收银台 expires_at 使用 DD/MM/YYYY HH:mm:ss，其他时间格式见字段说明。

    RRULE 标准示例：Daily FREQ=DAILY;INTERVAL=1；Weekly
    FREQ=WEEKLY;INTERVAL=1;BYDAY=MO；Fortnightly
    FREQ=WEEKLY;INTERVAL=2;BYDAY=MO；Monthly
    FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15；Quarterly
    FREQ=MONTHLY;INTERVAL=3;BYMONTHDAY=15；Half Yearly
    FREQ=MONTHLY;INTERVAL=6;BYMONTHDAY=15；Yearly
    FREQ=YEARLY;INTERVAL=1;BYMONTH=2;BYMONTHDAY=15。星期缩写为
    MO/TU/WE/TH/FR/SA/SU。Weekly/Monthly 省略具体扣费日时按起算日确定；单一 BYDAY=SA 或 SU
    按周一处理，未指定具体日期且起算日在周末时也按周一处理。单值 BYMONTHDAY=29/30/31 在短月按月末处理；BYMONTHDAY=-1
    表示月底。所有规则须符合有效 RRULE 格式。

    非标准频率（如每 10 天）须同时传 process_type=12、custom_cycle_type=1、custom_cycle=10，且
    day_of_debit=FREQ=DAILY;INTERVAL=10。单位 1/2/3/4 对应
    DAILY/WEEKLY/MONTHLY/YEARLY，以天为单位时间隔最小为 5，其余单位最小为 1，INTERVAL 须等于
    custom_cycle。季度、半年及年度还须提供 day_of_debit_dtstart；完整日期须严格晚于同段
    start_date，并在其后一个计费周期内。createSchedule 的实际首次扣费日期由 DDR 起算日、扣费频率及最早明天的限制共同确定。


    ## 使用示例

    参数类型、可空、长度、枚举及数值范围见 Schema；条件必填、日期及业务限制见字段 description。请结合两者使用。curl 示例中的
    BASE_URL、ACCESS_TOKEN、CLIENT_ID 和 CLIENT_SECRET 需由调用方设置；实际测试或生产域名由 BillBuddy
    提供。示例中的客户、订单、卡号、账户及日期须替换为测试环境允许使用且满足日期限制的数据。


    ## 托管订阅接入

    调用 POST /api/v2/subscription/create 创建订阅，取得 activation_url 后原样用于浏览器跳转或
    iframe 的 src；也可将 activation_html 用作 iframe 的 srcdoc。客户在 BillBuddy
    提供的页面填写支付信息并完成授权和激活。请使用返回的完整链接，无需自行拼接地址或解析链接中的凭证。Client Secret 和
    access_token 仅保存在商户服务端，不得放入 iframe 地址或页面内容。


    周期订阅及 By agreement 须在 start_date 当天之前激活；纯一次性订阅须在创建后 30
    天内提交激活。页面可以打开不保证仍可提交，以激活接口结果为准。


    ## 示例数据约定

    示例中的商户、客户、订单、支付 Token、会话链接和 OAuth 凭据均为虚构，不能用于真实调用。银行卡使用标准测试卡号；银行账户为虚构账户；邮箱使用
    example.com 保留域名，电话号码使用澳大利亚保留的演示号码。请求中的 BASE_URL、ACCESS_TOKEN、CLIENT_ID 和
    CLIENT_SECRET 仍需替换为获准测试环境的实际值。示例中必要的空字符串、null、空数组、0 和 false
    表示实际接口状态，不能统一替换为非空值。

    支付响应的 sign 按各支付场景的签名规则，使用公开演示密钥 bb_docs_demo_signing_key_2030 离线计算。3DS
    待验证响应的 html 不参与签名计算。该密钥仅用于文档，不能用于实际签名或认证。


    ## TXT 批量交易

    使用 multipart/form-data 上传固定宽度 TXT 文件。文件金额及
    amount_cents、declared_total_amount_cents 均以分计，不含附加费；文件格式和示例文件见“上传 TXT
    批量交易文件”。上传成功仅表示已接收，请保存 batch_id 和 file_identifier，并使用批次结果接口查询逐笔状态。批次
    completed 不代表所有支付成功。查询结果须使用同一商户的 OAuth 凭据；merchant_id
    可省略，如传入则须与原上传请求的业务标识一致。响应字段含义以对应接口说明为准。


    ## 开发语言请求示例

    请求示例提供 cURL、Python、JavaScript、PHP、Go、Java 和 Ruby，同一语言下可切换各业务场景。各语言使用与 cURL
    对应场景相同的请求参数和类型。


    运行环境：cURL；Python 3.9+（标准库）；JavaScript 使用 Node.js 18+，保存为 .mjs 后运行；PHP 8+ 并启用
    cURL 扩展；Go 1.20+；Java 11+（示例类名为 Example，保存为 Example.java）；Ruby 3+（标准库）。


    运行前设置 BASE_URL；业务接口还需设置 ACCESS_TOKEN，获取令牌需设置 CLIENT_ID 和
    CLIENT_SECRET。BASE_URL 使用 API 根地址，不附加 /api/v2。TXT 上传示例从当前目录读取
    payments.txt。请先替换为获准测试数据，并结合响应 code 和业务状态判断结果。
servers:
  - url: https://staging-api.billbuddyhq.com
    description: Staging 测试环境
security:
  - oauth2: []
tags:
  - name: 认证
    description: OAuth2 Client Credentials。
  - name: 交易
    description: 单笔、批量与预约取消。
  - name: 订阅
    description: 订阅模板、创建订阅、创建并激活 DDR 及推送扣费计划。
paths:
  /api/v2/subscription/createSchedule:
    post:
      tags:
        - 订阅
      summary: 向 By agreement DDR 推送扣费计划
      description: >-
        ### 按扣费计划类型填写


        必须提供 `merchant_id`、`plan_id`、`type`、`amount` 和 `start_date`。目标 DDR
        须已激活并绑定支付方式，且允许添加新的扣费计划。


        | type | 计划类型 | 额外必填参数 |

        | --- | --- | --- |

        | 1 | 按成功期数 | `day_of_debit`、`end_terms` |

        | 2 | 按累计金额 | `day_of_debit`、`total_amount` |

        | 3 | 持续至取消 | `day_of_debit` |

        | 4 | 按结束日期 | `day_of_debit`、`end_date`，结束日不得早于 `start_date` |

        | 6 | 一次性 | 不要求 `day_of_debit` |


        季度、半年、年度频率须提供 `day_of_debit_dtstart`。自定义频率须提供
        `process_type=12`、`custom_cycle_type` 和 `custom_cycle`，并与 RRULE
        一致。起算日期、首次扣费日期及完整取值限制见字段说明。


        仅可向已激活且已绑定支付方式的 By agreement DDR 添加扣费计划，使用该 DDR 的支付方式。若存在任何 Paused
        扣费计划（包括 Deposit 押金），须先恢复或取消；若存在 Active 的非 Deposit 扣费计划，须待其结束或取消后再添加。非标准
        RRULE 须提供 process_type=12、custom_cycle_type 及 custom_cycle。start_date
        不得早于 DDR 起算日；实际首次扣费日期不得早于服务业务时区的明天，并须符合 DDR 的起算日及频率规则。请同时保留响应的 plan_id 和
        schedule_no。


        所有示例均为格式示例，客户、订单、卡及账户数据须替换为测试环境获准使用的数据。BASE_URL 为服务根域名，不附加
        /api/v2；ACCESS_TOKEN 为 /oauth/token 返回的 access_token。日期示例为 2030
        年，执行时请改为满足当前日期限制的实际日期。
      operationId: v2CreateSchedule
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateScheduleRequest'
            examples:
              oneOff:
                summary: 一次性扣费计划
                value:
                  merchant_id: '48290713'
                  plan_id: DDR73019482
                  type: 6
                  schedule_name: Usage charge
                  amount: '10.00'
                  start_date: '2030-01-15'
              count:
                summary: 按成功期数结束
                value:
                  merchant_id: '48290713'
                  plan_id: DDR73019482
                  type: 1
                  amount: '10.00'
                  start_date: '2030-01-15'
                  end_terms: 12
                  day_of_debit: FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15
              amount:
                summary: 按累计金额结束
                value:
                  merchant_id: '48290713'
                  plan_id: DDR73019482
                  type: 2
                  amount: '10.00'
                  total_amount: '100.00'
                  start_date: '2030-01-15'
                  day_of_debit: FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15
              endDate:
                summary: 按结束日期结束
                value:
                  merchant_id: '48290713'
                  plan_id: DDR73019482
                  type: 4
                  amount: '10.00'
                  start_date: '2030-01-15'
                  end_date: '2030-12-31'
                  day_of_debit: FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15
              ongoing:
                summary: 持续至取消
                value:
                  merchant_id: '48290713'
                  plan_id: DDR73019482
                  type: 3
                  amount: '10.00'
                  start_date: '2030-01-15'
                  day_of_debit: FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15
      responses:
        '200':
          description: HTTP 200。成功、业务失败、参数校验失败或业务鉴权失败以响应体 code 区分。
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/CreateScheduleResponse'
                  - $ref: '#/components/schemas/BusinessError'
              examples:
                success:
                  summary: 创建成功
                  value:
                    code: 0
                    message: ok
                    data:
                      schedule_id: 947281
                      schedule_no: s1893452400000462
                      status: 2
                      plan_id: DDR73019482
                failure:
                  summary: DDR 未激活
                  value:
                    code: 1
                    message: DDR is not active
                    data: []
                activeExists:
                  summary: 已有执行中计划
                  value:
                    code: 1
                    message: >-
                      Plan has an active schedule; please wait for it to
                      complete or cancel before adding a new one
                    data: []
                validation:
                  summary: 缺少参数
                  value:
                    code: 400
                    message: The plan id field is required.
                    data: {}
        '429':
          description: >-
            请求超过频率限制。API 请求共享每分钟 120 次的限额，通常按请求来源 IP 计数，并非每个接口单独 120 次。请遵循
            Retry-After 指定的等待秒数。
          headers:
            Retry-After:
              description: 再次请求前应等待的秒数。
              schema:
                type: integer
          content:
            application/json:
              schema:
                type: object
                description: 请求频率超限响应。
                properties:
                  message:
                    type: string
                    description: 限流提示。
              example:
                message: Too Many Attempts.
      security:
        - oauth2: []
      x-codeSamples:
        - lang: Shell
          label: 一次性扣费计划
          source: |-
            curl -X POST "${BASE_URL}/api/v2/subscription/createSchedule" \
              -H "Authorization: Bearer ${ACCESS_TOKEN}" \
              -H "Accept: application/json" \
              -H "Content-Type: application/json" \
              --data-raw '{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 6,
              "schedule_name": "Usage charge",
              "amount": "10.00",
              "start_date": "2030-01-15"
            }'
        - lang: Shell
          label: 按成功期数结束
          source: |-
            curl -X POST "${BASE_URL}/api/v2/subscription/createSchedule" \
              -H "Authorization: Bearer ${ACCESS_TOKEN}" \
              -H "Accept: application/json" \
              -H "Content-Type: application/json" \
              --data-raw '{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 1,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_terms": 12,
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }'
        - lang: Shell
          label: 按累计金额结束
          source: |-
            curl -X POST "${BASE_URL}/api/v2/subscription/createSchedule" \
              -H "Authorization: Bearer ${ACCESS_TOKEN}" \
              -H "Accept: application/json" \
              -H "Content-Type: application/json" \
              --data-raw '{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 2,
              "amount": "10.00",
              "total_amount": "100.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }'
        - lang: Shell
          label: 按结束日期结束
          source: |-
            curl -X POST "${BASE_URL}/api/v2/subscription/createSchedule" \
              -H "Authorization: Bearer ${ACCESS_TOKEN}" \
              -H "Accept: application/json" \
              -H "Content-Type: application/json" \
              --data-raw '{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 4,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_date": "2030-12-31",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }'
        - lang: Shell
          label: 持续至取消
          source: |-
            curl -X POST "${BASE_URL}/api/v2/subscription/createSchedule" \
              -H "Authorization: Bearer ${ACCESS_TOKEN}" \
              -H "Accept: application/json" \
              -H "Content-Type: application/json" \
              --data-raw '{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 3,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }'
        - lang: Python
          label: 一次性扣费计划
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


            base_url = os.environ["BASE_URL"].rstrip("/")

            url = base_url + "/api/v2/subscription/createSchedule"

            headers = {"Accept": "application/json"}

            headers["Authorization"] = "Bearer " + os.environ["ACCESS_TOKEN"]

            payload = json.loads(r'''{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 6,
              "schedule_name": "Usage charge",
              "amount": "10.00",
              "start_date": "2030-01-15"
            }''')

            body = json.dumps(payload).encode("utf-8")

            headers["Content-Type"] = "application/json"


            request = urllib.request.Request(url, data=body, headers=headers,
            method="POST")

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: Python
          label: 按成功期数结束
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


            base_url = os.environ["BASE_URL"].rstrip("/")

            url = base_url + "/api/v2/subscription/createSchedule"

            headers = {"Accept": "application/json"}

            headers["Authorization"] = "Bearer " + os.environ["ACCESS_TOKEN"]

            payload = json.loads(r'''{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 1,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_terms": 12,
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }''')

            body = json.dumps(payload).encode("utf-8")

            headers["Content-Type"] = "application/json"


            request = urllib.request.Request(url, data=body, headers=headers,
            method="POST")

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: Python
          label: 按累计金额结束
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


            base_url = os.environ["BASE_URL"].rstrip("/")

            url = base_url + "/api/v2/subscription/createSchedule"

            headers = {"Accept": "application/json"}

            headers["Authorization"] = "Bearer " + os.environ["ACCESS_TOKEN"]

            payload = json.loads(r'''{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 2,
              "amount": "10.00",
              "total_amount": "100.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }''')

            body = json.dumps(payload).encode("utf-8")

            headers["Content-Type"] = "application/json"


            request = urllib.request.Request(url, data=body, headers=headers,
            method="POST")

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: Python
          label: 按结束日期结束
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


            base_url = os.environ["BASE_URL"].rstrip("/")

            url = base_url + "/api/v2/subscription/createSchedule"

            headers = {"Accept": "application/json"}

            headers["Authorization"] = "Bearer " + os.environ["ACCESS_TOKEN"]

            payload = json.loads(r'''{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 4,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_date": "2030-12-31",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }''')

            body = json.dumps(payload).encode("utf-8")

            headers["Content-Type"] = "application/json"


            request = urllib.request.Request(url, data=body, headers=headers,
            method="POST")

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: Python
          label: 持续至取消
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


            base_url = os.environ["BASE_URL"].rstrip("/")

            url = base_url + "/api/v2/subscription/createSchedule"

            headers = {"Accept": "application/json"}

            headers["Authorization"] = "Bearer " + os.environ["ACCESS_TOKEN"]

            payload = json.loads(r'''{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 3,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }''')

            body = json.dumps(payload).encode("utf-8")

            headers["Content-Type"] = "application/json"


            request = urllib.request.Request(url, data=body, headers=headers,
            method="POST")

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: JavaScript
          label: 一次性扣费计划
          source: >
            const env = (name) => {
              const value = process.env[name];
              if (!value) throw new Error(`Missing environment variable: ${name}`);
              return value;
            };

            const baseUrl = env("BASE_URL").replace(/\/+$/, "");

            const url = new URL(baseUrl +
            "/api/v2/subscription/createSchedule");

            const headers = { Accept: "application/json" };

            headers.Authorization = `Bearer ${env("ACCESS_TOKEN")}`;

            const payload = {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 6,
              "schedule_name": "Usage charge",
              "amount": "10.00",
              "start_date": "2030-01-15"
            };

            const body = JSON.stringify(payload);

            headers["Content-Type"] = "application/json";


            const response = await fetch(url, {
              method: "POST",
              headers,
              body,
              signal: AbortSignal.timeout(30_000),
            });

            console.log(await response.text());
        - lang: JavaScript
          label: 按成功期数结束
          source: >
            const env = (name) => {
              const value = process.env[name];
              if (!value) throw new Error(`Missing environment variable: ${name}`);
              return value;
            };

            const baseUrl = env("BASE_URL").replace(/\/+$/, "");

            const url = new URL(baseUrl +
            "/api/v2/subscription/createSchedule");

            const headers = { Accept: "application/json" };

            headers.Authorization = `Bearer ${env("ACCESS_TOKEN")}`;

            const payload = {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 1,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_terms": 12,
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            };

            const body = JSON.stringify(payload);

            headers["Content-Type"] = "application/json";


            const response = await fetch(url, {
              method: "POST",
              headers,
              body,
              signal: AbortSignal.timeout(30_000),
            });

            console.log(await response.text());
        - lang: JavaScript
          label: 按累计金额结束
          source: >
            const env = (name) => {
              const value = process.env[name];
              if (!value) throw new Error(`Missing environment variable: ${name}`);
              return value;
            };

            const baseUrl = env("BASE_URL").replace(/\/+$/, "");

            const url = new URL(baseUrl +
            "/api/v2/subscription/createSchedule");

            const headers = { Accept: "application/json" };

            headers.Authorization = `Bearer ${env("ACCESS_TOKEN")}`;

            const payload = {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 2,
              "amount": "10.00",
              "total_amount": "100.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            };

            const body = JSON.stringify(payload);

            headers["Content-Type"] = "application/json";


            const response = await fetch(url, {
              method: "POST",
              headers,
              body,
              signal: AbortSignal.timeout(30_000),
            });

            console.log(await response.text());
        - lang: JavaScript
          label: 按结束日期结束
          source: >
            const env = (name) => {
              const value = process.env[name];
              if (!value) throw new Error(`Missing environment variable: ${name}`);
              return value;
            };

            const baseUrl = env("BASE_URL").replace(/\/+$/, "");

            const url = new URL(baseUrl +
            "/api/v2/subscription/createSchedule");

            const headers = { Accept: "application/json" };

            headers.Authorization = `Bearer ${env("ACCESS_TOKEN")}`;

            const payload = {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 4,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_date": "2030-12-31",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            };

            const body = JSON.stringify(payload);

            headers["Content-Type"] = "application/json";


            const response = await fetch(url, {
              method: "POST",
              headers,
              body,
              signal: AbortSignal.timeout(30_000),
            });

            console.log(await response.text());
        - lang: JavaScript
          label: 持续至取消
          source: >
            const env = (name) => {
              const value = process.env[name];
              if (!value) throw new Error(`Missing environment variable: ${name}`);
              return value;
            };

            const baseUrl = env("BASE_URL").replace(/\/+$/, "");

            const url = new URL(baseUrl +
            "/api/v2/subscription/createSchedule");

            const headers = { Accept: "application/json" };

            headers.Authorization = `Bearer ${env("ACCESS_TOKEN")}`;

            const payload = {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 3,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            };

            const body = JSON.stringify(payload);

            headers["Content-Type"] = "application/json";


            const response = await fetch(url, {
              method: "POST",
              headers,
              body,
              signal: AbortSignal.timeout(30_000),
            });

            console.log(await response.text());
        - lang: PHP
          label: 一次性扣费计划
          source: |
            <?php
            $env = static function (string $name): string {
                $value = getenv($name);
                if ($value === false || $value === '') {
                    throw new RuntimeException("Missing environment variable: " . $name);
                }
                return $value;
            };
            $baseUrl = rtrim($env('BASE_URL'), '/');
            $url = $baseUrl . "/api/v2/subscription/createSchedule";
            $headers = ['Accept: application/json'];
            $headers[] = 'Authorization: Bearer ' . $env('ACCESS_TOKEN');
            $body = <<<'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 6,
              "schedule_name": "Usage charge",
              "amount": "10.00",
              "start_date": "2030-01-15"
            }
            JSON;
            $headers[] = 'Content-Type: application/json';

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_POSTFIELDS => $body,
            ]);
            $response = curl_exec($curl);
            if ($response === false) {
                $error = curl_error($curl);
                curl_close($curl);
                throw new RuntimeException($error);
            }
            curl_close($curl);
            echo $response, PHP_EOL;
        - lang: PHP
          label: 按成功期数结束
          source: |
            <?php
            $env = static function (string $name): string {
                $value = getenv($name);
                if ($value === false || $value === '') {
                    throw new RuntimeException("Missing environment variable: " . $name);
                }
                return $value;
            };
            $baseUrl = rtrim($env('BASE_URL'), '/');
            $url = $baseUrl . "/api/v2/subscription/createSchedule";
            $headers = ['Accept: application/json'];
            $headers[] = 'Authorization: Bearer ' . $env('ACCESS_TOKEN');
            $body = <<<'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 1,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_terms": 12,
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON;
            $headers[] = 'Content-Type: application/json';

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_POSTFIELDS => $body,
            ]);
            $response = curl_exec($curl);
            if ($response === false) {
                $error = curl_error($curl);
                curl_close($curl);
                throw new RuntimeException($error);
            }
            curl_close($curl);
            echo $response, PHP_EOL;
        - lang: PHP
          label: 按累计金额结束
          source: |
            <?php
            $env = static function (string $name): string {
                $value = getenv($name);
                if ($value === false || $value === '') {
                    throw new RuntimeException("Missing environment variable: " . $name);
                }
                return $value;
            };
            $baseUrl = rtrim($env('BASE_URL'), '/');
            $url = $baseUrl . "/api/v2/subscription/createSchedule";
            $headers = ['Accept: application/json'];
            $headers[] = 'Authorization: Bearer ' . $env('ACCESS_TOKEN');
            $body = <<<'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 2,
              "amount": "10.00",
              "total_amount": "100.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON;
            $headers[] = 'Content-Type: application/json';

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_POSTFIELDS => $body,
            ]);
            $response = curl_exec($curl);
            if ($response === false) {
                $error = curl_error($curl);
                curl_close($curl);
                throw new RuntimeException($error);
            }
            curl_close($curl);
            echo $response, PHP_EOL;
        - lang: PHP
          label: 按结束日期结束
          source: |
            <?php
            $env = static function (string $name): string {
                $value = getenv($name);
                if ($value === false || $value === '') {
                    throw new RuntimeException("Missing environment variable: " . $name);
                }
                return $value;
            };
            $baseUrl = rtrim($env('BASE_URL'), '/');
            $url = $baseUrl . "/api/v2/subscription/createSchedule";
            $headers = ['Accept: application/json'];
            $headers[] = 'Authorization: Bearer ' . $env('ACCESS_TOKEN');
            $body = <<<'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 4,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_date": "2030-12-31",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON;
            $headers[] = 'Content-Type: application/json';

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_POSTFIELDS => $body,
            ]);
            $response = curl_exec($curl);
            if ($response === false) {
                $error = curl_error($curl);
                curl_close($curl);
                throw new RuntimeException($error);
            }
            curl_close($curl);
            echo $response, PHP_EOL;
        - lang: PHP
          label: 持续至取消
          source: |
            <?php
            $env = static function (string $name): string {
                $value = getenv($name);
                if ($value === false || $value === '') {
                    throw new RuntimeException("Missing environment variable: " . $name);
                }
                return $value;
            };
            $baseUrl = rtrim($env('BASE_URL'), '/');
            $url = $baseUrl . "/api/v2/subscription/createSchedule";
            $headers = ['Accept: application/json'];
            $headers[] = 'Authorization: Bearer ' . $env('ACCESS_TOKEN');
            $body = <<<'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 3,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON;
            $headers[] = 'Content-Type: application/json';

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_POSTFIELDS => $body,
            ]);
            $response = curl_exec($curl);
            if ($response === false) {
                $error = curl_error($curl);
                curl_close($curl);
                throw new RuntimeException($error);
            }
            curl_close($curl);
            echo $response, PHP_EOL;
        - lang: Go
          label: 一次性扣费计划
          source: |
            package main

            import (
                "fmt"
                "io"
                "net/http"
                "os"
                "strings"
                "time"
            )

            func mustEnv(name string) string {
                value := os.Getenv(name)
                if value == "" { panic("Missing environment variable: " + name) }
                return value
            }

            func main() {
                baseURL := strings.TrimRight(mustEnv("BASE_URL"), "/")
                endpoint := baseURL + "/api/v2/subscription/createSchedule"
                payload := `{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 6,
              "schedule_name": "Usage charge",
              "amount": "10.00",
              "start_date": "2030-01-15"
            }`
                body := strings.NewReader(payload)
                req, err := http.NewRequest("POST", endpoint, body)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Authorization", "Bearer " + mustEnv("ACCESS_TOKEN"))
                req.Header.Set("Content-Type", "application/json")
                client := &http.Client{Timeout: 30 * time.Second}
                response, err := client.Do(req)
                if err != nil { panic(err) }
                defer response.Body.Close()
                result, err := io.ReadAll(response.Body)
                if err != nil { panic(err) }
                fmt.Println(string(result))
            }
        - lang: Go
          label: 按成功期数结束
          source: |
            package main

            import (
                "fmt"
                "io"
                "net/http"
                "os"
                "strings"
                "time"
            )

            func mustEnv(name string) string {
                value := os.Getenv(name)
                if value == "" { panic("Missing environment variable: " + name) }
                return value
            }

            func main() {
                baseURL := strings.TrimRight(mustEnv("BASE_URL"), "/")
                endpoint := baseURL + "/api/v2/subscription/createSchedule"
                payload := `{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 1,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_terms": 12,
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }`
                body := strings.NewReader(payload)
                req, err := http.NewRequest("POST", endpoint, body)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Authorization", "Bearer " + mustEnv("ACCESS_TOKEN"))
                req.Header.Set("Content-Type", "application/json")
                client := &http.Client{Timeout: 30 * time.Second}
                response, err := client.Do(req)
                if err != nil { panic(err) }
                defer response.Body.Close()
                result, err := io.ReadAll(response.Body)
                if err != nil { panic(err) }
                fmt.Println(string(result))
            }
        - lang: Go
          label: 按累计金额结束
          source: |
            package main

            import (
                "fmt"
                "io"
                "net/http"
                "os"
                "strings"
                "time"
            )

            func mustEnv(name string) string {
                value := os.Getenv(name)
                if value == "" { panic("Missing environment variable: " + name) }
                return value
            }

            func main() {
                baseURL := strings.TrimRight(mustEnv("BASE_URL"), "/")
                endpoint := baseURL + "/api/v2/subscription/createSchedule"
                payload := `{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 2,
              "amount": "10.00",
              "total_amount": "100.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }`
                body := strings.NewReader(payload)
                req, err := http.NewRequest("POST", endpoint, body)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Authorization", "Bearer " + mustEnv("ACCESS_TOKEN"))
                req.Header.Set("Content-Type", "application/json")
                client := &http.Client{Timeout: 30 * time.Second}
                response, err := client.Do(req)
                if err != nil { panic(err) }
                defer response.Body.Close()
                result, err := io.ReadAll(response.Body)
                if err != nil { panic(err) }
                fmt.Println(string(result))
            }
        - lang: Go
          label: 按结束日期结束
          source: |
            package main

            import (
                "fmt"
                "io"
                "net/http"
                "os"
                "strings"
                "time"
            )

            func mustEnv(name string) string {
                value := os.Getenv(name)
                if value == "" { panic("Missing environment variable: " + name) }
                return value
            }

            func main() {
                baseURL := strings.TrimRight(mustEnv("BASE_URL"), "/")
                endpoint := baseURL + "/api/v2/subscription/createSchedule"
                payload := `{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 4,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_date": "2030-12-31",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }`
                body := strings.NewReader(payload)
                req, err := http.NewRequest("POST", endpoint, body)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Authorization", "Bearer " + mustEnv("ACCESS_TOKEN"))
                req.Header.Set("Content-Type", "application/json")
                client := &http.Client{Timeout: 30 * time.Second}
                response, err := client.Do(req)
                if err != nil { panic(err) }
                defer response.Body.Close()
                result, err := io.ReadAll(response.Body)
                if err != nil { panic(err) }
                fmt.Println(string(result))
            }
        - lang: Go
          label: 持续至取消
          source: |
            package main

            import (
                "fmt"
                "io"
                "net/http"
                "os"
                "strings"
                "time"
            )

            func mustEnv(name string) string {
                value := os.Getenv(name)
                if value == "" { panic("Missing environment variable: " + name) }
                return value
            }

            func main() {
                baseURL := strings.TrimRight(mustEnv("BASE_URL"), "/")
                endpoint := baseURL + "/api/v2/subscription/createSchedule"
                payload := `{
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 3,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }`
                body := strings.NewReader(payload)
                req, err := http.NewRequest("POST", endpoint, body)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Authorization", "Bearer " + mustEnv("ACCESS_TOKEN"))
                req.Header.Set("Content-Type", "application/json")
                client := &http.Client{Timeout: 30 * time.Second}
                response, err := client.Do(req)
                if err != nil { panic(err) }
                defer response.Body.Close()
                result, err := io.ReadAll(response.Body)
                if err != nil { panic(err) }
                fmt.Println(string(result))
            }
        - lang: Java
          label: 一次性扣费计划
          source: |
            import java.io.ByteArrayOutputStream;
            import java.net.URI;
            import java.net.URLEncoder;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.nio.file.Files;
            import java.nio.file.Path;
            import java.time.Duration;
            import java.util.LinkedHashMap;
            import java.util.Map;
            import java.util.UUID;
            import java.util.stream.Collectors;

            public class Example {
                static String requireEnv(String name) {
                    String value = System.getenv(name);
                    if (value == null || value.isEmpty()) {
                        throw new IllegalArgumentException("Missing environment variable: " + name);
                    }
                    return value;
                }

                public static void main(String[] args) throws Exception {
                    String baseUrl = requireEnv("BASE_URL").replaceAll("/+$", "");
                    String endpoint = baseUrl + "/api/v2/subscription/createSchedule";
                    String payload =
                        "{\n" +
                        "  \"merchant_id\": \"48290713\",\n" +
                        "  \"plan_id\": \"DDR73019482\",\n" +
                        "  \"type\": 6,\n" +
                        "  \"schedule_name\": \"Usage charge\",\n" +
                        "  \"amount\": \"10.00\",\n" +
                        "  \"start_date\": \"2030-01-15\"\n" +
                        "}";
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Authorization", "Bearer " + requireEnv("ACCESS_TOKEN"));
                    builder.header("Content-Type", "application/json");
                    HttpRequest request = builder.method("POST", HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)).build();
                    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
                    HttpResponse<String> response = client.send(request,
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                    System.out.println(response.body());
                }
            }
        - lang: Java
          label: 按成功期数结束
          source: |
            import java.io.ByteArrayOutputStream;
            import java.net.URI;
            import java.net.URLEncoder;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.nio.file.Files;
            import java.nio.file.Path;
            import java.time.Duration;
            import java.util.LinkedHashMap;
            import java.util.Map;
            import java.util.UUID;
            import java.util.stream.Collectors;

            public class Example {
                static String requireEnv(String name) {
                    String value = System.getenv(name);
                    if (value == null || value.isEmpty()) {
                        throw new IllegalArgumentException("Missing environment variable: " + name);
                    }
                    return value;
                }

                public static void main(String[] args) throws Exception {
                    String baseUrl = requireEnv("BASE_URL").replaceAll("/+$", "");
                    String endpoint = baseUrl + "/api/v2/subscription/createSchedule";
                    String payload =
                        "{\n" +
                        "  \"merchant_id\": \"48290713\",\n" +
                        "  \"plan_id\": \"DDR73019482\",\n" +
                        "  \"type\": 1,\n" +
                        "  \"amount\": \"10.00\",\n" +
                        "  \"start_date\": \"2030-01-15\",\n" +
                        "  \"end_terms\": 12,\n" +
                        "  \"day_of_debit\": \"FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15\"\n" +
                        "}";
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Authorization", "Bearer " + requireEnv("ACCESS_TOKEN"));
                    builder.header("Content-Type", "application/json");
                    HttpRequest request = builder.method("POST", HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)).build();
                    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
                    HttpResponse<String> response = client.send(request,
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                    System.out.println(response.body());
                }
            }
        - lang: Java
          label: 按累计金额结束
          source: |
            import java.io.ByteArrayOutputStream;
            import java.net.URI;
            import java.net.URLEncoder;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.nio.file.Files;
            import java.nio.file.Path;
            import java.time.Duration;
            import java.util.LinkedHashMap;
            import java.util.Map;
            import java.util.UUID;
            import java.util.stream.Collectors;

            public class Example {
                static String requireEnv(String name) {
                    String value = System.getenv(name);
                    if (value == null || value.isEmpty()) {
                        throw new IllegalArgumentException("Missing environment variable: " + name);
                    }
                    return value;
                }

                public static void main(String[] args) throws Exception {
                    String baseUrl = requireEnv("BASE_URL").replaceAll("/+$", "");
                    String endpoint = baseUrl + "/api/v2/subscription/createSchedule";
                    String payload =
                        "{\n" +
                        "  \"merchant_id\": \"48290713\",\n" +
                        "  \"plan_id\": \"DDR73019482\",\n" +
                        "  \"type\": 2,\n" +
                        "  \"amount\": \"10.00\",\n" +
                        "  \"total_amount\": \"100.00\",\n" +
                        "  \"start_date\": \"2030-01-15\",\n" +
                        "  \"day_of_debit\": \"FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15\"\n" +
                        "}";
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Authorization", "Bearer " + requireEnv("ACCESS_TOKEN"));
                    builder.header("Content-Type", "application/json");
                    HttpRequest request = builder.method("POST", HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)).build();
                    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
                    HttpResponse<String> response = client.send(request,
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                    System.out.println(response.body());
                }
            }
        - lang: Java
          label: 按结束日期结束
          source: |
            import java.io.ByteArrayOutputStream;
            import java.net.URI;
            import java.net.URLEncoder;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.nio.file.Files;
            import java.nio.file.Path;
            import java.time.Duration;
            import java.util.LinkedHashMap;
            import java.util.Map;
            import java.util.UUID;
            import java.util.stream.Collectors;

            public class Example {
                static String requireEnv(String name) {
                    String value = System.getenv(name);
                    if (value == null || value.isEmpty()) {
                        throw new IllegalArgumentException("Missing environment variable: " + name);
                    }
                    return value;
                }

                public static void main(String[] args) throws Exception {
                    String baseUrl = requireEnv("BASE_URL").replaceAll("/+$", "");
                    String endpoint = baseUrl + "/api/v2/subscription/createSchedule";
                    String payload =
                        "{\n" +
                        "  \"merchant_id\": \"48290713\",\n" +
                        "  \"plan_id\": \"DDR73019482\",\n" +
                        "  \"type\": 4,\n" +
                        "  \"amount\": \"10.00\",\n" +
                        "  \"start_date\": \"2030-01-15\",\n" +
                        "  \"end_date\": \"2030-12-31\",\n" +
                        "  \"day_of_debit\": \"FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15\"\n" +
                        "}";
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Authorization", "Bearer " + requireEnv("ACCESS_TOKEN"));
                    builder.header("Content-Type", "application/json");
                    HttpRequest request = builder.method("POST", HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)).build();
                    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
                    HttpResponse<String> response = client.send(request,
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                    System.out.println(response.body());
                }
            }
        - lang: Java
          label: 持续至取消
          source: |
            import java.io.ByteArrayOutputStream;
            import java.net.URI;
            import java.net.URLEncoder;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.nio.file.Files;
            import java.nio.file.Path;
            import java.time.Duration;
            import java.util.LinkedHashMap;
            import java.util.Map;
            import java.util.UUID;
            import java.util.stream.Collectors;

            public class Example {
                static String requireEnv(String name) {
                    String value = System.getenv(name);
                    if (value == null || value.isEmpty()) {
                        throw new IllegalArgumentException("Missing environment variable: " + name);
                    }
                    return value;
                }

                public static void main(String[] args) throws Exception {
                    String baseUrl = requireEnv("BASE_URL").replaceAll("/+$", "");
                    String endpoint = baseUrl + "/api/v2/subscription/createSchedule";
                    String payload =
                        "{\n" +
                        "  \"merchant_id\": \"48290713\",\n" +
                        "  \"plan_id\": \"DDR73019482\",\n" +
                        "  \"type\": 3,\n" +
                        "  \"amount\": \"10.00\",\n" +
                        "  \"start_date\": \"2030-01-15\",\n" +
                        "  \"day_of_debit\": \"FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15\"\n" +
                        "}";
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Authorization", "Bearer " + requireEnv("ACCESS_TOKEN"));
                    builder.header("Content-Type", "application/json");
                    HttpRequest request = builder.method("POST", HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8)).build();
                    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
                    HttpResponse<String> response = client.send(request,
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                    System.out.println(response.body());
                }
            }
        - lang: Ruby
          label: 一次性扣费计划
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/api/v2/subscription/createSchedule")
            request = Net::HTTP::Post.new(uri)
            request["Accept"] = "application/json"
            request["Authorization"] = "Bearer " + ENV.fetch("ACCESS_TOKEN")
            request["Content-Type"] = "application/json"
            request.body = <<~'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 6,
              "schedule_name": "Usage charge",
              "amount": "10.00",
              "start_date": "2030-01-15"
            }
            JSON
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = uri.scheme == "https"
            http.open_timeout = 30
            http.read_timeout = 30
            puts http.request(request).body
        - lang: Ruby
          label: 按成功期数结束
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/api/v2/subscription/createSchedule")
            request = Net::HTTP::Post.new(uri)
            request["Accept"] = "application/json"
            request["Authorization"] = "Bearer " + ENV.fetch("ACCESS_TOKEN")
            request["Content-Type"] = "application/json"
            request.body = <<~'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 1,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_terms": 12,
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = uri.scheme == "https"
            http.open_timeout = 30
            http.read_timeout = 30
            puts http.request(request).body
        - lang: Ruby
          label: 按累计金额结束
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/api/v2/subscription/createSchedule")
            request = Net::HTTP::Post.new(uri)
            request["Accept"] = "application/json"
            request["Authorization"] = "Bearer " + ENV.fetch("ACCESS_TOKEN")
            request["Content-Type"] = "application/json"
            request.body = <<~'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 2,
              "amount": "10.00",
              "total_amount": "100.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = uri.scheme == "https"
            http.open_timeout = 30
            http.read_timeout = 30
            puts http.request(request).body
        - lang: Ruby
          label: 按结束日期结束
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/api/v2/subscription/createSchedule")
            request = Net::HTTP::Post.new(uri)
            request["Accept"] = "application/json"
            request["Authorization"] = "Bearer " + ENV.fetch("ACCESS_TOKEN")
            request["Content-Type"] = "application/json"
            request.body = <<~'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 4,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "end_date": "2030-12-31",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = uri.scheme == "https"
            http.open_timeout = 30
            http.read_timeout = 30
            puts http.request(request).body
        - lang: Ruby
          label: 持续至取消
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/api/v2/subscription/createSchedule")
            request = Net::HTTP::Post.new(uri)
            request["Accept"] = "application/json"
            request["Authorization"] = "Bearer " + ENV.fetch("ACCESS_TOKEN")
            request["Content-Type"] = "application/json"
            request.body = <<~'JSON'
            {
              "merchant_id": "48290713",
              "plan_id": "DDR73019482",
              "type": 3,
              "amount": "10.00",
              "start_date": "2030-01-15",
              "day_of_debit": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
            }
            JSON
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = uri.scheme == "https"
            http.open_timeout = 30
            http.read_timeout = 30
            puts http.request(request).body
components:
  schemas:
    CreateScheduleRequest:
      type: object
      description: >-
        向已激活且已绑定支付方式的 By agreement DDR 添加扣费计划，使用该 DDR 的支付方式。存在任何 Paused 扣费计划（包括
        Deposit 押金）时须先恢复或取消；存在 Active 的非 Deposit 扣费计划时须待其结束或取消后再添加。非标准 RRULE
        须同时提供 process_type=12、custom_cycle_type 及 custom_cycle。
      properties:
        merchant_id:
          type: string
          description: 业务标识，由 BillBuddy 分配。
          maxLength: 20
          minLength: 1
        plan_id:
          type: string
          description: DDR 订阅 ID。
          maxLength: 50
          minLength: 1
        type:
          type: integer
          description: 扣费计划类型：1 按成功期数；2 按累计金额；3 持续至取消；4 按结束日期；6 One-off。不允许 5 或 7。
          enum:
            - 1
            - 2
            - 3
            - 4
            - 6
        amount:
          oneOf:
            - type: number
              multipleOf: 0.01
              minimum: 0.01
              maximum: 9999999.99
            - type: string
              pattern: ^\d+(\.\d{1,2})?$
              allOf:
                - pattern: ^0*(?:[1-9]\d{0,6}(?:\.\d{1,2})?|0\.(?:0[1-9]|[1-9]\d?))$
          description: >-
            单次或每期金额。 金额以主货币单位计，例如 10.50 表示 AUD 10.50，最多两位小数。接受数值或数字字符串，最小
            0.01、最大 9999999.99，两种类型遵守相同范围限制。
        start_date:
          type: string
          description: >-
            扣费计划起始日期 YYYY-MM-DD。不得早于 DDR 的起算日。可传过去日期；实际首次扣费不得早于服务业务时区的明天，并须符合
            DDR 起算日及 RRULE 日期规则。
          format: date
          minLength: 1
        schedule_name:
          type: string
          description: 扣费计划名称。 省略时使用 DDR 的 plan_name。
          nullable: true
          maxLength: 255
        total_amount:
          oneOf:
            - type: number
              multipleOf: 0.01
              minimum: 0.01
              nullable: true
            - type: string
              pattern: ^\d+(\.\d{1,2})?$
              allOf:
                - pattern: ^0*(?:[1-9]\d*(?:\.\d{1,2})?|0\.(?:0[1-9]|[1-9]\d?))$
          description: >-
            目标累计金额，以主货币单位计，最多两位小数，最小为 0.01，接受数值或数字字符串。type=2 时必填且不能为
            null。服务按目标金额推算期数。
          nullable: true
        day_of_debit:
          type: string
          description: >-
            RFC 5545 RRULE 扣费规则。type=1/2/3/4 时必填且不能为
            null；type=6（一次性）可省略。频率写法见接入说明。
          nullable: true
          maxLength: 255
        process_type:
          type: integer
          description: 仅自定义频率时传 12。其他频率由 RRULE 推断，请省略此字段。
          nullable: true
          enum:
            - 12
            - null
        custom_cycle_type:
          type: integer
          description: >-
            process_type=12 时必填。1 天、2 周、3 月、4 年；须与 RRULE 的 FREQ 对应。非 Custom
            模式不得填写非空的自定义周期参数。 当 process_type 为 12 时必填，且不能为 null。
          nullable: true
          enum:
            - 1
            - 2
            - 3
            - 4
            - null
        custom_cycle:
          type: integer
          description: >-
            process_type=12 时必填，正整数且必须等于 RRULE 的 INTERVAL。以天为单位时最小 5，其他单位最小 1。 当
            process_type 为 12 时必填，且不能为 null。
          nullable: true
          minimum: 1
        day_of_debit_dtstart:
          type: string
          description: >-
            首次扣费锚点。季度、半年、年度频率必填，推荐 YYYY-MM-DD；必须严格晚于对应
            start_date，且在其后一个计费周期内（3/6/12 个月，按月底截断）。也支持
            MM-DD，此时须为合法月日，不适用上述完整日期窗口限制。
          nullable: true
          pattern: ^(\d{4}-)?\d{2}-\d{2}$
        end_date:
          type: string
          description: 结束日期，建议使用 YYYY-MM-DD。type=4 时必填且不能为 null；提供时不得早于同一段的 start_date。
          nullable: true
          format: date
        end_terms:
          type: integer
          description: 成功扣费期数，正整数，最小为 1。type=1 时必填且不能为 null。
          nullable: true
          minimum: 1
      required:
        - merchant_id
        - plan_id
        - type
        - amount
        - start_date
      not:
        anyOf:
          - allOf:
              - required:
                  - type
                properties:
                  type:
                    enum:
                      - 1
              - not:
                  required:
                    - end_terms
                  properties:
                    end_terms:
                      not:
                        enum:
                          - null
          - allOf:
              - required:
                  - type
                properties:
                  type:
                    enum:
                      - 2
              - not:
                  required:
                    - total_amount
                  properties:
                    total_amount:
                      not:
                        enum:
                          - null
          - allOf:
              - required:
                  - type
                properties:
                  type:
                    enum:
                      - 4
              - not:
                  required:
                    - end_date
                  properties:
                    end_date:
                      not:
                        enum:
                          - null
                      minLength: 1
          - allOf:
              - required:
                  - type
                properties:
                  type:
                    enum:
                      - 1
                      - 2
                      - 3
                      - 4
              - not:
                  required:
                    - day_of_debit
                  properties:
                    day_of_debit:
                      not:
                        enum:
                          - null
                      minLength: 1
          - allOf:
              - required:
                  - process_type
                properties:
                  process_type:
                    enum:
                      - 12
              - not:
                  required:
                    - custom_cycle_type
                    - custom_cycle
                  properties:
                    custom_cycle_type:
                      not:
                        enum:
                          - null
                    custom_cycle:
                      not:
                        enum:
                          - null
          - allOf:
              - required:
                  - process_type
                  - custom_cycle_type
                properties:
                  process_type:
                    enum:
                      - 12
                  custom_cycle_type:
                    enum:
                      - 1
              - not:
                  required:
                    - custom_cycle
                  properties:
                    custom_cycle:
                      not:
                        enum:
                          - null
                      minimum: 5
          - allOf:
              - required:
                  - custom_cycle_type
                properties:
                  custom_cycle_type:
                    not:
                      enum:
                        - null
              - not:
                  required:
                    - process_type
                  properties:
                    process_type:
                      enum:
                        - 12
          - allOf:
              - required:
                  - custom_cycle
                properties:
                  custom_cycle:
                    not:
                      enum:
                        - null
              - not:
                  required:
                    - process_type
                  properties:
                    process_type:
                      enum:
                        - 12
    CreateScheduleResponse:
      type: object
      description: 成功响应。
      properties:
        code:
          type: integer
          description: 0 表示扣费计划创建成功，不表示已完成扣款。
          enum:
            - 0
        message:
          type: string
          description: 响应说明。
        data:
          type: object
          description: 新扣费计划。
          properties:
            schedule_id:
              type: integer
              description: 扣费计划标识。
            schedule_no:
              type: string
              description: 扣费计划编号。与 plan_id 一起保留，用于识别该订阅下的扣费计划。
            status:
              type: integer
              description: >-
                扣费计划状态：1 Pending、2 Active、3 Paused、4 Cancelled、5 Completed。新建通常为
                2。
              enum:
                - 1
                - 2
                - 3
                - 4
                - 5
            plan_id:
              type: string
              description: DDR 订阅 ID。
          required:
            - schedule_id
            - schedule_no
            - status
            - plan_id
      required:
        - code
        - message
        - data
    BusinessError:
      type: object
      description: 业务错误。HTTP 通常仍为 200。
      properties:
        code:
          type: integer
          description: 业务失败、认证失败为 1；Request 参数及文件属性校验失败为 400。
          enum:
            - 1
            - 400
        message:
          type: string
          description: 错误原因，具体文案会因失败原因不同而变化。
        data:
          oneOf:
            - type: object
              description: 空对象或错误上下文。
              properties:
                customer_id:
                  type: string
                  description: createDdr 后续步骤失败时，可能返回已创建并保留的客户 ID；重试可使用此 ID。
            - type: array
              items: {}
              description: 通常为空数组。
          description: 错误数据，可能为 []、{} 或包含 customer_id 的客户上下文。
      required:
        - code
        - message
        - data
  securitySchemes:
    oauth2:
      type: oauth2
      description: OAuth2 client_credentials 授权。access_token 到期后重新获取。
      flows:
        clientCredentials:
          tokenUrl: /oauth/token
          scopes: {}

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.