{
  "info": {
    "name": "DirecFunds Experience API (Test)",
    "description": "Recommended bundled disbursement-request flow against the DirecFunds Test environment (baseUrl defaults to https://testapi.direcfunds.com/v1). DirecFunds has no orderId: map each Order disbursement to one independent request. Fan out multi-Order selections as separate non-atomic calls; one Order may create multiple requests, but each needs a distinct clientReference and existing requests cannot be appended to.\n\nRun it in order with the Collection Runner. 0 gets a token. 1 discovers features. 2 prepares the Test sandbox and fills sourceAccountId and requesterUserId (it needs an onboarded Test company with an active branch, an active user and an existing source bank account). 3 validates the closing and stops the run if it is not valid. 4 creates one $100 Wire request. 5 approves and sends it. 6 tracks it, with Test-only simulations. 7 reports. Folders 8 and 9 are optional; folder 9 creates its own separate Test requests and never cancels or rejects the request sent in step 5. Folder 11 is destructive and runs only when allowDestructive is true.\n\nApprover: the sandbox prepares one user. When the closing allows self-approval, approverUserId defaults to requesterUserId; when $Validate reports requiresSeparateApprover=true, set approverUserId to a second user with approve permission. Canceling one recipient payment always needs an actor other than the requester, so that example is skipped until approverUserId is a second user.\n\nRetries: create and $VerifyAndSend keep their X-Idempotency-Key (and create keeps its clientReference) until a definitive response, so re-sending after a timeout, 5xx or in-progress 409 is a safe retry of the same operation; any other 4xx clears them because nothing was done. After an uncertain create, run '10. Additional reads > Find by clientReference' first. If same-key retries keep returning 502, the recorded outcome may be the failure itself: stop and email support@direcfunds.com with the X-Trace-Id.\n\nCredentials: select a Postman environment and keep clientSecret and accessToken there as secret-type variables. The token script writes accessToken to the selected environment; without one it falls back to a collection variable and warns you. Never commit or share real credentials with this file.\n\nBilling: if Capabilities reports billingReady=false, DirecFunds has not finished billing setup for the company and payout rails report active=false; contact DirecFunds. Separately, when the billing payment-method check is enforced, $VerifyAndSend returns 422 BILLING_PAYMENT_METHOD_REQUIRED until a company admin saves a card or US bank account on the Portal Billing page; billingReady does not report that check. Webhook requests run only when GET /Integration reports features.webhooks=true; webhooks are enabled per integration and depend on the current integration configuration.",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "variable": [
    {
      "key": "baseUrl",
      "value": "https://testapi.direcfunds.com/v1"
    },
    {
      "key": "tokenUrl",
      "value": "https://direcfundstest2.b2clogin.com/direcfundstest2.onmicrosoft.com/B2C_1A_CLIENT_CREDENTIALS/oauth2/v2.0/token"
    },
    {
      "key": "scope",
      "value": "https://direcfundstest2.onmicrosoft.com/public/.default"
    },
    {
      "key": "clientId",
      "value": ""
    },
    {
      "key": "clientSecret",
      "value": "",
      "description": "Keep the real value in a secret-type environment variable, not here."
    },
    {
      "key": "accessToken",
      "value": "",
      "description": "Written by 0. Get access token; prefer a secret-type environment variable."
    },
    {
      "key": "sourceAccountId",
      "value": "",
      "description": "Filled by 2. Prepare synthetic Test source when empty."
    },
    {
      "key": "requesterUserId",
      "value": "",
      "description": "Filled by 2. Prepare synthetic Test source when empty."
    },
    {
      "key": "approverUserId",
      "value": "",
      "description": "Defaults to requesterUserId when self-approval is allowed; otherwise set a second user with approve permission."
    },
    {
      "key": "disbursementRequestId",
      "value": ""
    },
    {
      "key": "payInId",
      "value": ""
    },
    {
      "key": "payOutId",
      "value": ""
    },
    {
      "key": "clientReference",
      "value": "",
      "description": "clientReference of the request created in step 4."
    },
    {
      "key": "createClientReference",
      "value": "",
      "description": "Pending create state: kept until create gets a definitive response."
    },
    {
      "key": "createIdempotencyKey",
      "value": "",
      "description": "Pending create state: kept until create gets a definitive response."
    },
    {
      "key": "sendIdempotencyKey",
      "value": "",
      "description": "Pending $VerifyAndSend state: kept until it gets a definitive response."
    },
    {
      "key": "supportsScheduling",
      "value": ""
    },
    {
      "key": "stagedRequestId",
      "value": ""
    },
    {
      "key": "stagedClientReference",
      "value": ""
    },
    {
      "key": "stagedIdempotencyKey",
      "value": ""
    },
    {
      "key": "scheduledRequestId",
      "value": ""
    },
    {
      "key": "scheduledClientReference",
      "value": ""
    },
    {
      "key": "scheduledIdempotencyKey",
      "value": ""
    },
    {
      "key": "scheduledFor",
      "value": "",
      "description": "Set to 24 hours ahead by the scheduled-request example when empty or past."
    },
    {
      "key": "cancelRequestId",
      "value": "",
      "description": "Defaults to stagedRequestId."
    },
    {
      "key": "cancelPaymentReference",
      "value": "seller-002"
    },
    {
      "key": "reportFrom",
      "value": "",
      "description": "Leave empty for a rolling 30-day window; set both to pin a half-open UTC range (at most 366 days)."
    },
    {
      "key": "reportTo",
      "value": ""
    },
    {
      "key": "webhooksEnabled",
      "value": "",
      "description": "Set from GET /Integration features.webhooks."
    },
    {
      "key": "webhookCallbackUrl",
      "value": "https://partner.example.com/direcfunds/webhooks"
    },
    {
      "key": "webhookCreateIdempotencyKey",
      "value": ""
    },
    {
      "key": "webhookSubscriptionId",
      "value": ""
    },
    {
      "key": "newWebhookSigningSecret",
      "value": "",
      "description": "32-512 characters from your secret-management workflow; rotation is skipped while empty."
    },
    {
      "key": "webhookDeliveryId",
      "value": ""
    },
    {
      "key": "allowDestructive",
      "value": "false",
      "description": "Set to true only to run folder 11."
    },
    {
      "key": "recipientAccountNumber",
      "value": "100200200",
      "type": "string"
    },
    {
      "key": "recipientRoutingNumber",
      "value": "100000000",
      "type": "string"
    },
    {
      "key": "recipientBankName",
      "value": "DirecFunds UAT Bank",
      "type": "string"
    },
    {
      "key": "recipientName",
      "value": "Test Recipient",
      "type": "string"
    },
    {
      "key": "secondRecipientName",
      "value": "Second Recipient",
      "type": "string"
    }
  ],
  "item": [
    {
      "name": "0. Get access token",
      "event": [
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "const body = pm.response.json();",
              "pm.test('token issued', () => pm.expect(body.access_token).to.be.a('string'));",
              "if (body.access_token) {",
              "  if (pm.environment.name) {",
              "    pm.environment.set('accessToken', body.access_token);",
              "  } else {",
              "    pm.collectionVariables.set('accessToken', body.access_token);",
              "    console.warn('No environment is selected, so accessToken was stored in a collection variable. Select an environment with secret-type clientSecret and accessToken variables before exporting or sharing this collection.');",
              "  }",
              "} else {",
              "  pm.execution.setNextRequest(null);",
              "}"
            ]
          }
        }
      ],
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/x-www-form-urlencoded"
          }
        ],
        "url": "{{tokenUrl}}",
        "body": {
          "mode": "urlencoded",
          "urlencoded": [
            {
              "key": "grant_type",
              "value": "client_credentials"
            },
            {
              "key": "client_id",
              "value": "{{clientId}}"
            },
            {
              "key": "client_secret",
              "value": "{{clientSecret}}"
            },
            {
              "key": "scope",
              "value": "{{scope}}"
            }
          ]
        }
      }
    },
    {
      "name": "1. Discovery",
      "item": [
        {
          "name": "GET Integration",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test('integration profile returned', () => pm.expect(pm.response.code).to.eql(200));",
                  "const features = pm.response.code === 200 ? (pm.response.json().features || {}) : {};",
                  "pm.collectionVariables.set('webhooksEnabled', String(features.webhooks === true));",
                  "if (features.webhooks !== true) { console.log('features.webhooks=false: folder 8 and the webhook list will be skipped.'); }"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/Integration"
          }
        },
        {
          "name": "GET PaymentRails",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/PaymentRails"
          }
        },
        {
          "name": "GET DisbursementRequests Capabilities",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test('capabilities returned', () => pm.expect(pm.response.code).to.eql(200));",
                  "if (pm.response.code === 200) {",
                  "  const capabilities = pm.response.json();",
                  "  pm.collectionVariables.set('supportsScheduling', String(capabilities.supportsScheduling === true));",
                  "  if (capabilities.billingReady === false) {",
                  "    console.warn('billingReady=false (' + capabilities.billingUnavailableReason + '): DirecFunds billing setup is incomplete, so payout rails are inactive. Contact DirecFunds.');",
                  "  }",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/Capabilities"
          }
        },
        {
          "name": "GET Onboarding Readiness",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/Onboarding/Readiness"
          }
        }
      ]
    },
    {
      "name": "2. Prepare the Test sandbox",
      "description": "Test only. Run before the money steps so steps 3-5 have a source account and a requester.",
      "item": [
        {
          "name": "Scenarios",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/Sandbox/Scenarios"
          }
        },
        {
          "name": "Prepare synthetic Test source",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.response.code === 200) {",
                  "  const prepared = pm.response.json();",
                  "  if (!pm.collectionVariables.get('sourceAccountId') && prepared.bankAccountId) { pm.collectionVariables.set('sourceAccountId', prepared.bankAccountId); }",
                  "  if (!pm.collectionVariables.get('requesterUserId') && prepared.userId) { pm.collectionVariables.set('requesterUserId', prepared.userId); }",
                  "  console.log('Sandbox prepared: readyForDisbursements=' + prepared.readyForDisbursements);",
                  "} else {",
                  "  console.warn('Sandbox preparation returned HTTP ' + pm.response.code + ': ' + pm.response.text());",
                  "}",
                  "pm.test('sourceAccountId and requesterUserId are set', () => {",
                  "  pm.expect(pm.variables.get('sourceAccountId')).to.be.a('string').and.not.empty;",
                  "  pm.expect(pm.variables.get('requesterUserId')).to.be.a('string').and.not.empty;",
                  "});",
                  "if (!pm.variables.get('sourceAccountId') || !pm.variables.get('requesterUserId')) { pm.execution.setNextRequest(null); }"
                ]
              }
            }
          ],
          "request": {
            "description": "Test only (404 in Production). Idempotently prepares the authenticated company's existing branch, one user's request and approve permissions, onboarding flags, and a synthetic source account. It needs an onboarded Test company with an active branch, an active user and an existing source bank account. Fills sourceAccountId and requesterUserId when they are empty.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/Sandbox/$Prepare",
            "body": {
              "mode": "raw",
              "raw": "{}"
            }
          }
        },
        {
          "name": "Readiness",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const readiness = pm.response.code === 200 ? pm.response.json() : {};",
                  "pm.test('disbursementsEnabled is true', () => pm.expect(readiness.disbursementsEnabled, JSON.stringify(readiness.findings || [])).to.eql(true));",
                  "if (readiness.disbursementsEnabled !== true) { pm.execution.setNextRequest(null); }"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/Onboarding/Readiness"
          }
        }
      ]
    },
    {
      "name": "3. Validate the closing (no writes)",
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "const missing = [\"sourceAccountId\", \"requesterUserId\"].filter(name => !pm.variables.get(name));",
              "if (missing.length) {",
              "  console.log('Skipping validation (run 2. Prepare the Test sandbox): set ' + missing.join(', ') + ' first.');",
              "  pm.execution.setNextRequest(null);",
              "  pm.execution.skipRequest();",
              "}",
              "if (!pm.collectionVariables.get('createClientReference')) { pm.collectionVariables.set('createClientReference', 'partner-' + Date.now()); }"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "const body = pm.response.code === 200 ? pm.response.json() : {};",
              "pm.test('validation call returned 200', () => pm.expect(pm.response.code).to.eql(200));",
              "pm.test('closing is valid', () => pm.expect(body.valid, JSON.stringify(body.issues || [])).to.eql(true));",
              "const preflight = body.preflight || {};",
              "if (body.preflight) { console.log('preflight ' + preflight.status + ': ' + JSON.stringify(preflight.findings || [])); }",
              "pm.test('preflight reports no blocker or missing input', () => pm.expect(['Blocked', 'InputRequired']).to.not.include(preflight.status));",
              "const requirements = body.approvalRequirements || {};",
              "if (!pm.variables.get('approverUserId') && requirements.requiresSeparateApprover === false) {",
              "  pm.collectionVariables.set('approverUserId', pm.variables.get('requesterUserId'));",
              "  console.log('Self-approval is allowed for this closing, so approverUserId defaults to requesterUserId.');",
              "}",
              "pm.test('approverUserId is set (a second approver is required when requiresSeparateApprover is true)', () => pm.expect(pm.variables.get('approverUserId'), requirements.reasonCode).to.be.a('string').and.not.empty);",
              "if (body.valid !== true || ['Blocked', 'InputRequired'].includes(preflight.status) || !pm.variables.get('approverUserId')) { pm.execution.setNextRequest(null); }"
            ]
          }
        }
      ],
      "request": {
        "description": "Validates the exact body step 4 will create, using the same pending clientReference. $Validate returns 200 even when valid is false, so the test checks valid, issues and the preflight assessment.",
        "method": "POST",
        "header": [
          {
            "key": "Authorization",
            "value": "Bearer {{accessToken}}"
          },
          {
            "key": "X-Api-Version",
            "value": "1.0"
          },
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/DisbursementRequests/$Validate",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"clientReference\": \"{{createClientReference}}\",\n  \"fundingInstruction\": {\n    \"sourceAccountReferenceId\": \"{{sourceAccountId}}\",\n    \"paymentRail\": \"Wire\"\n  },\n  \"expectedTotal\": 100.0,\n  \"currency\": \"USD\",\n  \"recipientPayments\": [\n    {\n      \"paymentReference\": \"seller-001\",\n      \"paymentRail\": \"Wire\",\n      \"amount\": 100.0,\n      \"transactionPurpose\": \"LoanPayoff\",\n      \"destination\": {\n        \"type\": \"BankAccount\",\n        \"bankAccount\": {\n          \"bankName\": \"{{recipientBankName}}\",\n          \"accountNumber\": \"{{recipientAccountNumber}}\",\n          \"routingNumber\": \"{{recipientRoutingNumber}}\",\n          \"accountBeneficiary\": \"{{recipientName}}\",\n          \"bankAddress1\": \"500 Walnut St\",\n          \"bankCity\": \"Cincinnati\",\n          \"bankState\": \"OH\",\n          \"bankPostalCode\": \"45202\",\n          \"depositAccountType\": \"Checking\"\n        }\n      },\n      \"recipient\": {\n        \"name\": \"{{recipientName}}\",\n        \"recipientType\": \"Person\",\n        \"dateOfBirth\": \"1992-10-10\",\n        \"address1\": \"50 Centennial Ave\",\n        \"city\": \"Cincinnati\",\n        \"state\": \"OH\",\n        \"postalCode\": \"45202\",\n        \"phone\": \"5134556770\"\n      },\n      \"transactionDetails\": {\n        \"memoLine\": \"Partner Test\"\n      }\n    }\n  ],\n  \"approvalContext\": {\n    \"requesterUserId\": \"{{requesterUserId}}\",\n    \"submitForApproval\": true\n  }\n}"
        }
      }
    },
    {
      "name": "4. Create the disbursement request",
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "const missing = [\"sourceAccountId\", \"requesterUserId\"].filter(name => !pm.variables.get(name));",
              "if (missing.length) {",
              "  console.log('Skipping create (run 2. Prepare the Test sandbox): set ' + missing.join(', ') + ' first.');",
              "  pm.execution.setNextRequest(null);",
              "  pm.execution.skipRequest();",
              "}",
              "if (!pm.collectionVariables.get('createClientReference')) { pm.collectionVariables.set('createClientReference', 'partner-' + Date.now()); }",
              "if (!pm.collectionVariables.get('createIdempotencyKey')) { pm.collectionVariables.set('createIdempotencyKey', pm.variables.replaceIn('{{$guid}}')); }"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "const code = pm.response.code;",
              "const text = pm.response.text();",
              "const inFlight = code === 409 && /IdempotencyKeyInFlight|REQUEST_IN_PROGRESS/.test(text);",
              "// 401 and 429 are refused before the operation runs; 5xx and in-flight outcomes are not final.",
              "const definitive = code < 500 && code !== 401 && code !== 429 && !inFlight;",
              "if (definitive) {",
              "  [\"createClientReference\", \"createIdempotencyKey\"].forEach(name => pm.collectionVariables.set(name, ''));",
              "} else {",
              "  console.warn('Outcome not final (HTTP ' + code + '). Run 10. Additional reads > Find by clientReference first to see whether the request exists. Re-send this request unchanged: it reuses the same X-Idempotency-Key and body, so DirecFunds returns the recorded outcome instead of repeating the operation. If same-key retries keep returning 502, stop and email support@direcfunds.com with X-Trace-Id ' + pm.response.headers.get('X-Trace-Id') + '.');",
              "}",
              "const succeeded = [201].includes(code);",
              "const body = succeeded ? pm.response.json() : {};",
              "if (succeeded) {",
              "  pm.collectionVariables.set('disbursementRequestId', body.id);",
              "  pm.collectionVariables.set('clientReference', body.clientReference);",
              "  pm.collectionVariables.set('payInId', (body.funding || {}).payInId || '');",
              "  pm.collectionVariables.set('payOutId', ((body.recipientPayments || [])[0] || {}).payOutId || '');",
              "  pm.collectionVariables.set('sendIdempotencyKey', '');",
              "} else if (definitive) {",
              "  console.error('Refused (HTTP ' + code + '): ' + text);",
              "}",
              "pm.test('created', () => pm.expect(code).to.eql(201));",
              "if (!succeeded) { pm.execution.setNextRequest(null); }"
            ]
          }
        }
      ],
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Authorization",
            "value": "Bearer {{accessToken}}"
          },
          {
            "key": "X-Api-Version",
            "value": "1.0"
          },
          {
            "key": "X-Idempotency-Key",
            "value": "{{createIdempotencyKey}}",
            "description": "Kept with createClientReference until a definitive response, so re-sending after a timeout or 5xx retries the same operation."
          },
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/DisbursementRequests",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"clientReference\": \"{{createClientReference}}\",\n  \"fundingInstruction\": {\n    \"sourceAccountReferenceId\": \"{{sourceAccountId}}\",\n    \"paymentRail\": \"Wire\"\n  },\n  \"expectedTotal\": 100.0,\n  \"currency\": \"USD\",\n  \"recipientPayments\": [\n    {\n      \"paymentReference\": \"seller-001\",\n      \"paymentRail\": \"Wire\",\n      \"amount\": 100.0,\n      \"transactionPurpose\": \"LoanPayoff\",\n      \"destination\": {\n        \"type\": \"BankAccount\",\n        \"bankAccount\": {\n          \"bankName\": \"{{recipientBankName}}\",\n          \"accountNumber\": \"{{recipientAccountNumber}}\",\n          \"routingNumber\": \"{{recipientRoutingNumber}}\",\n          \"accountBeneficiary\": \"{{recipientName}}\",\n          \"bankAddress1\": \"500 Walnut St\",\n          \"bankCity\": \"Cincinnati\",\n          \"bankState\": \"OH\",\n          \"bankPostalCode\": \"45202\",\n          \"depositAccountType\": \"Checking\"\n        }\n      },\n      \"recipient\": {\n        \"name\": \"{{recipientName}}\",\n        \"recipientType\": \"Person\",\n        \"dateOfBirth\": \"1992-10-10\",\n        \"address1\": \"50 Centennial Ave\",\n        \"city\": \"Cincinnati\",\n        \"state\": \"OH\",\n        \"postalCode\": \"45202\",\n        \"phone\": \"5134556770\"\n      },\n      \"transactionDetails\": {\n        \"memoLine\": \"Partner Test\"\n      }\n    }\n  ],\n  \"approvalContext\": {\n    \"requesterUserId\": \"{{requesterUserId}}\",\n    \"submitForApproval\": true\n  }\n}"
        }
      }
    },
    {
      "name": "5. Verify and send (approver)",
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "const missing = [\"disbursementRequestId\", \"approverUserId\"].filter(name => !pm.variables.get(name));",
              "if (missing.length) {",
              "  console.log('Skipping $VerifyAndSend: set ' + missing.join(', ') + ' first.');",
              "  pm.execution.setNextRequest(null);",
              "  pm.execution.skipRequest();",
              "}",
              "if (!pm.collectionVariables.get('sendIdempotencyKey')) { pm.collectionVariables.set('sendIdempotencyKey', pm.variables.replaceIn('{{$guid}}')); }"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "const code = pm.response.code;",
              "const text = pm.response.text();",
              "const inFlight = code === 409 && /IdempotencyKeyInFlight|REQUEST_IN_PROGRESS/.test(text);",
              "// 401 and 429 are refused before the operation runs; 5xx and in-flight outcomes are not final.",
              "const definitive = code < 500 && code !== 401 && code !== 429 && !inFlight;",
              "if (definitive) {",
              "  [\"sendIdempotencyKey\"].forEach(name => pm.collectionVariables.set(name, ''));",
              "} else {",
              "  console.warn('Outcome not final (HTTP ' + code + '). Read 6. Track the outcome > GET DisbursementRequest before retrying. Re-send this request unchanged: it reuses the same X-Idempotency-Key and body, so DirecFunds returns the recorded outcome instead of repeating the operation. If same-key retries keep returning 502, stop and email support@direcfunds.com with X-Trace-Id ' + pm.response.headers.get('X-Trace-Id') + '.');",
              "}",
              "const succeeded = [202].includes(code);",
              "const body = succeeded ? pm.response.json() : {};",
              "if (succeeded) {",
              "  const request = body.request || {};",
              "  console.log('Request status after $VerifyAndSend: ' + request.status);",
              "  if (!['Processing', 'Completed', 'PartiallyCompleted'].includes(request.status)) { console.error('attention: ' + JSON.stringify(request.attention)); }",
              "  pm.test('request is routing or settled', () => pm.expect(['Processing', 'Completed', 'PartiallyCompleted']).to.include(request.status));",
              "} else if (definitive) {",
              "  console.error('Refused (HTTP ' + code + '): ' + text);",
              "}",
              "pm.test('202 Accepted', () => pm.expect(code).to.eql(202));",
              "if (!succeeded || !['Processing', 'Completed', 'PartiallyCompleted'].includes((body.request || {}).status)) { pm.execution.setNextRequest(null); }"
            ]
          }
        }
      ],
      "request": {
        "description": "Approves, verifies and routes the request created in step 4. A 202 is not proof of routing: the test checks request.status. A 422 BILLING_PAYMENT_METHOD_REQUIRED means a company admin must save a card or US bank account on the Portal Billing page; if its detail says to try again later, billing could not be confirmed, so retry later with a new key.",
        "method": "POST",
        "header": [
          {
            "key": "Authorization",
            "value": "Bearer {{accessToken}}"
          },
          {
            "key": "X-Api-Version",
            "value": "1.0"
          },
          {
            "key": "X-Idempotency-Key",
            "value": "{{sendIdempotencyKey}}",
            "description": "Kept until a definitive response, so re-sending after a timeout or 5xx retries the same approval."
          },
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/DisbursementRequests/{{disbursementRequestId}}/$VerifyAndSend",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"approverUserId\": \"{{approverUserId}}\",\n  \"reviewConfirmed\": true\n}"
        }
      }
    },
    {
      "name": "6. Track the outcome",
      "item": [
        {
          "name": "GET DisbursementRequest",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.response.code === 200) {",
                  "  const request = pm.response.json();",
                  "  if (request.funding && request.funding.payInId) { pm.collectionVariables.set('payInId', request.funding.payInId); }",
                  "  const first = (request.recipientPayments || [])[0];",
                  "  if (first && first.payOutId) { pm.collectionVariables.set('payOutId', first.payOutId); }",
                  "  console.log('status=' + request.status + ' payments=' + JSON.stringify((request.recipientPayments || []).map(p => p.paymentReference + ':' + p.status)));",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{disbursementRequestId}}"
          }
        },
        {
          "name": "Simulate funding completed (Test only)",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!/testapi\\./.test(pm.variables.get('baseUrl'))) { console.log('Sandbox simulation is Test only; skipping.'); pm.execution.skipRequest(); }",
                  "const missing = [\"payInId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping funding simulation: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "description": "Test only. Applies the Completed scenario to the funding leg. Returns 409 when the leg is not in a state the scenario can follow; re-read the request first.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/Sandbox/PayIn/{{payInId}}/$Simulate",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"scenario\": \"Completed\"\n}"
            }
          }
        },
        {
          "name": "Simulate recipient payment completed (Test only)",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!/testapi\\./.test(pm.variables.get('baseUrl'))) { console.log('Sandbox simulation is Test only; skipping.'); pm.execution.skipRequest(); }",
                  "const missing = [\"payOutId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping payout simulation: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "description": "Test only. Applies the Completed scenario to the recipient payment so the request can reach a final state. Returns 409 when the leg is not in a state the scenario can follow; re-read the request first.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/Sandbox/PayOut/{{payOutId}}/$Simulate",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"scenario\": \"Completed\"\n}"
            }
          }
        },
        {
          "name": "GET Events (cursor poll)",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": {
              "raw": "{{baseUrl}}/DisbursementRequests/{{disbursementRequestId}}/Events?after=0&limit=100",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "DisbursementRequests",
                "{{disbursementRequestId}}",
                "Events"
              ],
              "query": [
                {
                  "key": "after",
                  "value": "0",
                  "description": "Persist the response's nextCursor and send it here on the next poll. Never use a webhook sequence value as this cursor."
                },
                {
                  "key": "limit",
                  "value": "100"
                }
              ]
            }
          }
        },
        {
          "name": "GET Reconciliation",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{disbursementRequestId}}/Reconciliation"
          }
        },
        {
          "name": "GET AuditLog (needs Audit.Read)",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": {
              "raw": "{{baseUrl}}/AuditLog?limit=100",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "AuditLog"
              ],
              "query": [
                {
                  "key": "limit",
                  "value": "100"
                }
              ]
            }
          }
        }
      ]
    },
    {
      "name": "7. Reporting and controlled catch-up",
      "description": "Search and Summary use the same required half-open UTC [from,to) range, which may span at most 366 days; the folder computes a rolling 30-day window unless reportFrom and reportTo are set. The Events feed is the authoritative record for recovery and reconciliation: persist its nextCursor as your checkpoint.",
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "// Rolling half-open UTC window [from, to): the last 30 days through the end of today.",
              "// Set reportFrom and reportTo yourself (at most 366 days apart) to pin a range.",
              "if (!pm.collectionVariables.get('reportFrom') || !pm.collectionVariables.get('reportTo')) {",
              "  const to = new Date();",
              "  to.setUTCHours(0, 0, 0, 0);",
              "  to.setUTCDate(to.getUTCDate() + 1);",
              "  const from = new Date(to.getTime() - 30 * 24 * 60 * 60 * 1000);",
              "  pm.variables.set('reportFrom', from.toISOString().replace('.000Z', 'Z'));",
              "  pm.variables.set('reportTo', to.toISOString().replace('.000Z', 'Z'));",
              "}"
            ]
          }
        }
      ],
      "item": [
        {
          "name": "GET DisbursementRequests Search",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": {
              "raw": "{{baseUrl}}/DisbursementRequests/Search?from={{reportFrom}}&to={{reportTo}}&limit=100",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "DisbursementRequests",
                "Search"
              ],
              "query": [
                {
                  "key": "from",
                  "value": "{{reportFrom}}"
                },
                {
                  "key": "to",
                  "value": "{{reportTo}}"
                },
                {
                  "key": "limit",
                  "value": "100"
                }
              ]
            }
          }
        },
        {
          "name": "GET DisbursementRequests Summary",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": {
              "raw": "{{baseUrl}}/DisbursementRequests/Summary?from={{reportFrom}}&to={{reportTo}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "DisbursementRequests",
                "Summary"
              ],
              "query": [
                {
                  "key": "from",
                  "value": "{{reportFrom}}"
                },
                {
                  "key": "to",
                  "value": "{{reportTo}}"
                }
              ]
            }
          }
        },
        {
          "name": "GET Company Events",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": {
              "raw": "{{baseUrl}}/DisbursementRequests/Events?after=0&limit=100",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "DisbursementRequests",
                "Events"
              ],
              "query": [
                {
                  "key": "after",
                  "value": "0",
                  "description": "Persist nextCursor as the company checkpoint and pass it as after on the next call; repeat until nextCursor is null. Keep limit unchanged."
                },
                {
                  "key": "limit",
                  "value": "100"
                }
              ]
            }
          }
        }
      ]
    },
    {
      "name": "8. Optional signed webhooks",
      "description": "Runs only when GET /Integration reports features.webhooks=true. The generated signing secret is returned once by create; copy it directly to an approved secret store and never save it in the collection.",
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "if (pm.collectionVariables.get('webhooksEnabled') !== 'true') {",
              "  console.log('Skipping webhooks: GET /Integration reports features.webhooks=false. Webhooks are enabled per integration and depend on the current integration configuration.');",
              "  pm.execution.skipRequest();",
              "}"
            ]
          }
        }
      ],
      "item": [
        {
          "name": "POST Create wildcard webhook subscription",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.collectionVariables.get('webhookSubscriptionId')) {",
                  "  console.log('Skipping create: webhookSubscriptionId is already set. Clear it to create another subscription.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "if (!pm.collectionVariables.get('webhookCreateIdempotencyKey')) { pm.collectionVariables.set('webhookCreateIdempotencyKey', pm.variables.replaceIn('{{$guid}}')); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const code = pm.response.code;",
                  "const text = pm.response.text();",
                  "const inFlight = code === 409 && /IdempotencyKeyInFlight|REQUEST_IN_PROGRESS/.test(text);",
                  "// 401 and 429 are refused before the operation runs; 5xx and in-flight outcomes are not final.",
                  "const definitive = code < 500 && code !== 401 && code !== 429 && !inFlight;",
                  "if (definitive) {",
                  "  [\"webhookCreateIdempotencyKey\"].forEach(name => pm.collectionVariables.set(name, ''));",
                  "} else {",
                  "  console.warn('Outcome not final (HTTP ' + code + ').  Re-send this request unchanged: it reuses the same X-Idempotency-Key and body, so DirecFunds returns the recorded outcome instead of repeating the operation. If same-key retries keep returning 502, stop and email support@direcfunds.com with X-Trace-Id ' + pm.response.headers.get('X-Trace-Id') + '.');",
                  "}",
                  "const succeeded = [201].includes(code);",
                  "const body = succeeded ? pm.response.json() : {};",
                  "if (succeeded) {",
                  "  pm.collectionVariables.set('webhookSubscriptionId', body.id);",
                  "  console.warn('Store signingSecret in an approved secret manager now; it is intentionally not saved by this collection.');",
                  "} else if (definitive) {",
                  "  console.error('Refused (HTTP ' + code + '): ' + text);",
                  "}",
                  "pm.test('subscription and one-time signing secret returned', () => { pm.expect(body.id).to.be.a('string'); pm.expect(body.signingSecret).to.be.a('string'); });"
                ]
              }
            }
          ],
          "request": {
            "description": "callbackUrl is the only required field. Omit signingSecret to receive a generated one in this create response only. Use [\"*\"] by itself for certification. Skipped when webhookSubscriptionId is already set.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{webhookCreateIdempotencyKey}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/WebhookSubscriptions",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"callbackUrl\": \"{{webhookCallbackUrl}}\",\n  \"eventTypes\": [\"*\"]\n}"
            }
          }
        },
        {
          "name": "POST Send signed diagnostic webhook",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"webhookSubscriptionId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping the diagnostic webhook: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/WebhookSubscriptions/{{webhookSubscriptionId}}/$Test"
          }
        },
        {
          "name": "PUT Rotate webhook signing secret in place",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"webhookSubscriptionId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping secret rotation: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "const secret = pm.variables.get('newWebhookSigningSecret') || '';",
                  "if (secret.length < 32 || secret.length > 512) {",
                  "  console.log('Skipping secret rotation: set newWebhookSigningSecret to 32-512 characters from your secret store.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test('secret rotated', () => pm.expect(pm.response.code).to.eql(200));",
                  "if (pm.response.code === 200) {",
                  "  pm.collectionVariables.set('newWebhookSigningSecret', '');",
                  "  console.log('Rotation succeeded: replace the stored secret in your secret store now. The value was cleared from the collection.');",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "description": "Set newWebhookSigningSecret to a new 32-512 character value from your secret-management workflow; this request is skipped while it is empty or the wrong length. Every delivery after success uses the new value. Omit signingSecret on unrelated updates to keep the current secret.",
            "method": "PUT",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/WebhookSubscriptions/{{webhookSubscriptionId}}",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"signingSecret\": \"{{newWebhookSigningSecret}}\"\n}"
            }
          }
        },
        {
          "name": "GET Dead-lettered webhook deliveries",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"webhookSubscriptionId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping the delivery list: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.response.code === 200) {",
                  "  const first = (pm.response.json().deliveries || [])[0];",
                  "  if (first) { pm.collectionVariables.set('webhookDeliveryId', String(first.id)); console.log('Dead-lettered delivery ' + first.id + ' for event ' + first.eventId); }",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/WebhookSubscriptions/{{webhookSubscriptionId}}/Deliveries?status=DeadLettered&limit=50"
          }
        },
        {
          "name": "POST Redeliver corrected dead-lettered delivery",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"webhookSubscriptionId\", \"webhookDeliveryId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping redelivery: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/WebhookSubscriptions/{{webhookSubscriptionId}}/Deliveries/{{webhookDeliveryId}}/$Redeliver"
          }
        }
      ]
    },
    {
      "name": "9. Optional lifecycle controls (separate Test requests)",
      "description": "Every example here uses its own separate Test request and ends Canceled or Rejected; none of them touches the request sent in step 5. The staged request shows submitForApproval=false, $SubmitForApproval, canceling one unsent recipient payment, and canceling the whole request. The scheduled request shows a future scheduledFor approved once with $VerifyAndSend (DirecFunds then releases it automatically when due), $CancelSchedule, and $Reject.",
      "item": [
        {
          "name": "Create staged two-payment request",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"sourceAccountId\", \"requesterUserId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping the staged request: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "if (pm.collectionVariables.get('stagedRequestId')) { console.log('Skipping: stagedRequestId is already set. Clear it to create another staged request.'); pm.execution.skipRequest(); }",
                  "if (!pm.collectionVariables.get('stagedClientReference')) { pm.collectionVariables.set('stagedClientReference', 'partner-staged-' + Date.now()); }",
                  "if (!pm.collectionVariables.get('stagedIdempotencyKey')) { pm.collectionVariables.set('stagedIdempotencyKey', pm.variables.replaceIn('{{$guid}}')); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const code = pm.response.code;",
                  "const text = pm.response.text();",
                  "const inFlight = code === 409 && /IdempotencyKeyInFlight|REQUEST_IN_PROGRESS/.test(text);",
                  "// 401 and 429 are refused before the operation runs; 5xx and in-flight outcomes are not final.",
                  "const definitive = code < 500 && code !== 401 && code !== 429 && !inFlight;",
                  "if (definitive) {",
                  "  [\"stagedClientReference\", \"stagedIdempotencyKey\"].forEach(name => pm.collectionVariables.set(name, ''));",
                  "} else {",
                  "  console.warn('Outcome not final (HTTP ' + code + ').  Re-send this request unchanged: it reuses the same X-Idempotency-Key and body, so DirecFunds returns the recorded outcome instead of repeating the operation. If same-key retries keep returning 502, stop and email support@direcfunds.com with X-Trace-Id ' + pm.response.headers.get('X-Trace-Id') + '.');",
                  "}",
                  "const succeeded = [201].includes(code);",
                  "const body = succeeded ? pm.response.json() : {};",
                  "if (succeeded) {",
                  "  pm.collectionVariables.set('stagedRequestId', body.id);",
                  "  if (!pm.collectionVariables.get('cancelRequestId')) { pm.collectionVariables.set('cancelRequestId', body.id); }",
                  "} else if (definitive) {",
                  "  console.error('Refused (HTTP ' + code + '): ' + text);",
                  "}",
                  "pm.test('staged request created', () => pm.expect(code).to.eql(201));"
                ]
              }
            }
          ],
          "request": {
            "description": "Creates a separate two-payment request with submitForApproval=false (Initialized). It is used only by the staged, recipient-cancel and cancel examples below. Skipped when stagedRequestId is already set.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{stagedIdempotencyKey}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"clientReference\": \"{{stagedClientReference}}\",\n  \"fundingInstruction\": {\n    \"sourceAccountReferenceId\": \"{{sourceAccountId}}\",\n    \"paymentRail\": \"Wire\"\n  },\n  \"expectedTotal\": 150.0,\n  \"currency\": \"USD\",\n  \"recipientPayments\": [\n    {\n      \"paymentReference\": \"seller-001\",\n      \"paymentRail\": \"Wire\",\n      \"amount\": 100.0,\n      \"transactionPurpose\": \"LoanPayoff\",\n      \"destination\": {\n        \"type\": \"BankAccount\",\n        \"bankAccount\": {\n          \"bankName\": \"{{recipientBankName}}\",\n          \"accountNumber\": \"{{recipientAccountNumber}}\",\n          \"routingNumber\": \"{{recipientRoutingNumber}}\",\n          \"accountBeneficiary\": \"{{recipientName}}\",\n          \"bankAddress1\": \"500 Walnut St\",\n          \"bankCity\": \"Cincinnati\",\n          \"bankState\": \"OH\",\n          \"bankPostalCode\": \"45202\",\n          \"depositAccountType\": \"Checking\"\n        }\n      },\n      \"recipient\": {\n        \"name\": \"{{recipientName}}\",\n        \"recipientType\": \"Person\",\n        \"dateOfBirth\": \"1992-10-10\",\n        \"address1\": \"50 Centennial Ave\",\n        \"city\": \"Cincinnati\",\n        \"state\": \"OH\",\n        \"postalCode\": \"45202\",\n        \"phone\": \"5134556770\"\n      },\n      \"transactionDetails\": {\n        \"memoLine\": \"Partner Test\"\n      }\n    },\n    {\n      \"paymentReference\": \"seller-002\",\n      \"paymentRail\": \"Wire\",\n      \"amount\": 50.0,\n      \"transactionPurpose\": \"LoanPayoff\",\n      \"destination\": {\n        \"type\": \"BankAccount\",\n        \"bankAccount\": {\n          \"bankName\": \"{{recipientBankName}}\",\n          \"accountNumber\": \"{{recipientAccountNumber}}\",\n          \"routingNumber\": \"{{recipientRoutingNumber}}\",\n          \"accountBeneficiary\": \"{{secondRecipientName}}\",\n          \"bankAddress1\": \"500 Walnut St\",\n          \"bankCity\": \"Cincinnati\",\n          \"bankState\": \"OH\",\n          \"bankPostalCode\": \"45202\",\n          \"depositAccountType\": \"Checking\"\n        }\n      },\n      \"recipient\": {\n        \"name\": \"{{secondRecipientName}}\",\n        \"recipientType\": \"Person\",\n        \"dateOfBirth\": \"1992-10-10\",\n        \"address1\": \"50 Centennial Ave\",\n        \"city\": \"Cincinnati\",\n        \"state\": \"OH\",\n        \"postalCode\": \"45202\",\n        \"phone\": \"5134556770\"\n      },\n      \"transactionDetails\": {\n        \"memoLine\": \"Partner Test\"\n      }\n    }\n  ],\n  \"approvalContext\": {\n    \"requesterUserId\": \"{{requesterUserId}}\",\n    \"submitForApproval\": false\n  }\n}"
            }
          }
        },
        {
          "name": "POST Submit staged request for approval",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"stagedRequestId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping POST Submit staged request for approval: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const response = pm.response.code === 202 ? pm.response.json() : {};",
                  "pm.test('202 Accepted', () => pm.expect(pm.response.code, pm.response.text()).to.eql(202));",
                  "pm.test('request is PendingApproval', () => pm.expect((response.request || {}).status).to.eql('PendingApproval'));"
                ]
              }
            }
          ],
          "request": {
            "description": "Moves a request created with submitForApproval=false from Initialized to PendingApproval.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{stagedRequestId}}/$SubmitForApproval"
          }
        },
        {
          "name": "Cancel unsent recipient as approver",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"stagedRequestId\", \"approverUserId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping recipient cancellation: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "if (pm.variables.get('approverUserId') === pm.variables.get('requesterUserId')) {",
                  "  console.log('Skipping recipient cancellation: the actor must be an approver other than the requester. Set approverUserId to a second user.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test('202 Accepted', () => pm.expect(pm.response.code, pm.response.text()).to.eql(202));"
                ]
              }
            }
          ],
          "request": {
            "description": "Cancels one recipient payment (seller-002) on the staged request while it is still awaiting approval; the funding amount drops to the remaining payment. The actor must be a branch approver other than the requester, so this is skipped until approverUserId is a second user. Never run it on a request that has been sent.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{stagedRequestId}}/RecipientPayments/{{cancelPaymentReference}}/$Cancel",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"actorUserId\": \"{{approverUserId}}\",\n  \"reason\": \"Partner Test cancellation after review\"\n}"
            }
          }
        },
        {
          "name": "POST Cancel entire undispatched request",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const missing = [\"cancelRequestId\", \"approverUserId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping POST Cancel entire undispatched request: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const response = pm.response.code === 202 ? pm.response.json() : {};",
                  "pm.test('202 Accepted', () => pm.expect(pm.response.code, pm.response.text()).to.eql(202));",
                  "pm.test('request is Canceled', () => pm.expect((response.request || {}).status).to.eql('Canceled'));"
                ]
              }
            }
          ],
          "request": {
            "description": "Cancels the request and every leg only while nothing has been dispatched. cancelRequestId defaults to the staged request. This is different from canceling one recipient payment.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{cancelRequestId}}/$Cancel",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"actorUserId\": \"{{approverUserId}}\",\n  \"reason\": \"Order disbursement withdrawn\"\n}"
            }
          }
        },
        {
          "name": "Create future scheduled request",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.collectionVariables.get('supportsScheduling') === 'false') {",
                  "  console.log('Skipping: Capabilities reports supportsScheduling=false.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "const missing = [\"sourceAccountId\", \"requesterUserId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping the scheduled request: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "if (pm.collectionVariables.get('scheduledRequestId')) { console.log('Skipping: scheduledRequestId is already set. Clear it to create another scheduled request.'); pm.execution.skipRequest(); }",
                  "const scheduledFor = pm.collectionVariables.get('scheduledFor');",
                  "if (!scheduledFor || new Date(scheduledFor).getTime() < Date.now() + 60 * 60 * 1000) {",
                  "  pm.collectionVariables.set('scheduledFor', new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().replace(/\\.\\d{3}Z$/, 'Z'));",
                  "}",
                  "if (!pm.collectionVariables.get('scheduledClientReference')) { pm.collectionVariables.set('scheduledClientReference', 'partner-scheduled-' + Date.now()); }",
                  "if (!pm.collectionVariables.get('scheduledIdempotencyKey')) { pm.collectionVariables.set('scheduledIdempotencyKey', pm.variables.replaceIn('{{$guid}}')); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const code = pm.response.code;",
                  "const text = pm.response.text();",
                  "const inFlight = code === 409 && /IdempotencyKeyInFlight|REQUEST_IN_PROGRESS/.test(text);",
                  "// 401 and 429 are refused before the operation runs; 5xx and in-flight outcomes are not final.",
                  "const definitive = code < 500 && code !== 401 && code !== 429 && !inFlight;",
                  "if (definitive) {",
                  "  [\"scheduledClientReference\", \"scheduledIdempotencyKey\"].forEach(name => pm.collectionVariables.set(name, ''));",
                  "} else {",
                  "  console.warn('Outcome not final (HTTP ' + code + ').  Re-send this request unchanged: it reuses the same X-Idempotency-Key and body, so DirecFunds returns the recorded outcome instead of repeating the operation. If same-key retries keep returning 502, stop and email support@direcfunds.com with X-Trace-Id ' + pm.response.headers.get('X-Trace-Id') + '.');",
                  "}",
                  "const succeeded = [201].includes(code);",
                  "const body = succeeded ? pm.response.json() : {};",
                  "if (succeeded) {",
                  "  pm.collectionVariables.set('scheduledRequestId', body.id);",
                  "} else if (definitive) {",
                  "  console.error('Refused (HTTP ' + code + '): ' + text);",
                  "}",
                  "pm.test('scheduled request created', () => pm.expect(code).to.eql(201));"
                ]
              }
            }
          ],
          "request": {
            "description": "Creates a separate request with scheduledFor 24 hours ahead (maximum 365 days). Skipped when supportsScheduling is false or scheduledRequestId is already set.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{scheduledIdempotencyKey}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"clientReference\": \"{{scheduledClientReference}}\",\n  \"fundingInstruction\": {\n    \"sourceAccountReferenceId\": \"{{sourceAccountId}}\",\n    \"paymentRail\": \"Wire\"\n  },\n  \"expectedTotal\": 100.0,\n  \"currency\": \"USD\",\n  \"scheduledFor\": \"{{scheduledFor}}\",\n  \"recipientPayments\": [\n    {\n      \"paymentReference\": \"seller-001\",\n      \"paymentRail\": \"Wire\",\n      \"amount\": 100.0,\n      \"transactionPurpose\": \"LoanPayoff\",\n      \"destination\": {\n        \"type\": \"BankAccount\",\n        \"bankAccount\": {\n          \"bankName\": \"{{recipientBankName}}\",\n          \"accountNumber\": \"{{recipientAccountNumber}}\",\n          \"routingNumber\": \"{{recipientRoutingNumber}}\",\n          \"accountBeneficiary\": \"{{recipientName}}\",\n          \"bankAddress1\": \"500 Walnut St\",\n          \"bankCity\": \"Cincinnati\",\n          \"bankState\": \"OH\",\n          \"bankPostalCode\": \"45202\",\n          \"depositAccountType\": \"Checking\"\n        }\n      },\n      \"recipient\": {\n        \"name\": \"{{recipientName}}\",\n        \"recipientType\": \"Person\",\n        \"dateOfBirth\": \"1992-10-10\",\n        \"address1\": \"50 Centennial Ave\",\n        \"city\": \"Cincinnati\",\n        \"state\": \"OH\",\n        \"postalCode\": \"45202\",\n        \"phone\": \"5134556770\"\n      },\n      \"transactionDetails\": {\n        \"memoLine\": \"Partner Test\"\n      }\n    }\n  ],\n  \"approvalContext\": {\n    \"requesterUserId\": \"{{requesterUserId}}\",\n    \"submitForApproval\": true\n  }\n}"
            }
          }
        },
        {
          "name": "POST Approve future scheduled request",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.collectionVariables.get('supportsScheduling') === 'false') {",
                  "  console.log('Skipping: Capabilities reports supportsScheduling=false.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "const missing = [\"scheduledRequestId\", \"approverUserId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping POST Approve future scheduled request: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const response = pm.response.code === 202 ? pm.response.json() : {};",
                  "pm.test('202 Accepted', () => pm.expect(pm.response.code, pm.response.text()).to.eql(202));",
                  "pm.test('request is Scheduled', () => pm.expect((response.request || {}).status).to.eql('Scheduled'));"
                ]
              }
            }
          ],
          "request": {
            "description": "Approves the future request once and holds it in Scheduled. DirecFunds automatically releases it at or after scheduledFor; no second partner call is required.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{scheduledRequestId}}/$VerifyAndSend",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"approverUserId\": \"{{approverUserId}}\",\n  \"reviewConfirmed\": true\n}"
            }
          }
        },
        {
          "name": "POST Cancel scheduled hold",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.collectionVariables.get('supportsScheduling') === 'false') {",
                  "  console.log('Skipping: Capabilities reports supportsScheduling=false.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "const missing = [\"scheduledRequestId\", \"approverUserId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping POST Cancel scheduled hold: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const response = pm.response.code === 202 ? pm.response.json() : {};",
                  "pm.test('202 Accepted', () => pm.expect(pm.response.code, pm.response.text()).to.eql(202));",
                  "pm.test('request is PendingApproval', () => pm.expect((response.request || {}).status).to.eql('PendingApproval'));"
                ]
              }
            }
          ],
          "request": {
            "description": "Clears scheduledFor and returns an undispatched Scheduled request to PendingApproval.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{scheduledRequestId}}/$CancelSchedule",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"actorUserId\": \"{{approverUserId}}\",\n  \"reason\": \"Funding date changed\"\n}"
            }
          }
        },
        {
          "name": "Reject as approver",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.collectionVariables.get('supportsScheduling') === 'false') {",
                  "  console.log('Skipping: Capabilities reports supportsScheduling=false.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "const missing = [\"scheduledRequestId\", \"approverUserId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping rejection: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const response = pm.response.code === 202 ? pm.response.json() : {};",
                  "pm.test('202 Accepted', () => pm.expect(pm.response.code, pm.response.text()).to.eql(202));",
                  "pm.test('request is Rejected', () => pm.expect((response.request || {}).status).to.eql('Rejected'));"
                ]
              }
            }
          ],
          "request": {
            "description": "Rejects the scheduled example after its hold was canceled, so it ends without moving money. Rejection is an approval decision and is allowed only before anything is dispatched; never run it on the request sent in step 5.",
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              },
              {
                "key": "X-Idempotency-Key",
                "value": "{{$guid}}"
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/{{scheduledRequestId}}/$Reject",
            "body": {
              "mode": "raw",
              "raw": "{\n  \"approverUserId\": \"{{approverUserId}}\",\n  \"reviewConfirmed\": true,\n  \"reason\": \"Partner Test rejection after review\"\n}"
            }
          }
        }
      ]
    },
    {
      "name": "10. Additional reads",
      "item": [
        {
          "name": "Find by clientReference",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.variables.set('lookupClientReference', pm.collectionVariables.get('createClientReference') || pm.collectionVariables.get('clientReference'));",
                  "const missing = [\"lookupClientReference\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping the lookup: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.response.code === 200) {",
                  "  const request = pm.response.json();",
                  "  pm.collectionVariables.set('disbursementRequestId', request.id);",
                  "  console.log('Found ' + request.clientReference + ' (' + request.id + ') in status ' + request.status + '. If this was an uncertain create, it exists: do not create it again.');",
                  "} else if (pm.response.code === 404) {",
                  "  console.log('No request has this clientReference.');",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "description": "Recovery read after an uncertain create: looks up the pending createClientReference when one is waiting, otherwise the last created clientReference. A 404 means the request was not created.",
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests?clientReference={{lookupClientReference}}"
          }
        },
        {
          "name": "List webhook subscriptions",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.collectionVariables.get('webhooksEnabled') !== 'true') {",
                  "  console.log('Skipping webhooks: GET /Integration reports features.webhooks=false. Webhooks are enabled per integration and depend on the current integration configuration.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/WebhookSubscriptions"
          }
        }
      ]
    },
    {
      "name": "11. Destructive (run manually)",
      "description": "Irreversible operations. Skipped unless allowDestructive is true.",
      "item": [
        {
          "name": "Disable webhook subscription",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.collectionVariables.get('allowDestructive') !== 'true') {",
                  "  console.log('Skipping irreversible webhook disable: set allowDestructive=true to run it.');",
                  "  pm.execution.skipRequest();",
                  "}",
                  "const missing = [\"webhookSubscriptionId\"].filter(name => !pm.variables.get(name));",
                  "if (missing.length) {",
                  "  console.log('Skipping webhook disable: set ' + missing.join(', ') + ' first.');",
                  "  pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (pm.response.code < 300) { pm.collectionVariables.set('webhookSubscriptionId', ''); }"
                ]
              }
            }
          ],
          "request": {
            "description": "Irreversible: a disabled subscription cannot be re-enabled or updated through the API, and its open deliveries are dead-lettered. Runs only when allowDestructive is true.",
            "method": "DELETE",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{accessToken}}"
              },
              {
                "key": "X-Api-Version",
                "value": "1.0"
              }
            ],
            "url": "{{baseUrl}}/DisbursementRequests/WebhookSubscriptions/{{webhookSubscriptionId}}"
          }
        }
      ]
    }
  ]
}
