Source: https://docs.debitura.com/referral-partners/getting-started/ai-integration-recipe

# Build a Full Integration with an AI agent

Build one working “Send to collection” flow against test: create a client, complete onboarding, preview an invoice, submit it and read the case back. This recipe follows the Full Integration in the [Ledgerline demo’s developer view](https://referral.debitura.com/demo-journey#full).

Want one API call with Debitura handling the next steps? Use the live [Starter Integration](https://docs.debitura.com/referral-partners/getting-started/starter-quickstart.md): `POST /collection-requests` returns a `solutionUrl`. This recipe uses the Full Integration’s separate onboarding and Customer API calls.

<a id="give-your-agent-the-right-context"></a>

## Give your agent the right context

Start at [llms.txt](https://docs.debitura.com/llms.txt). Every page has a Markdown version: append `.md` to its URL, or use `/index.md` for the home page. The API references include nested fields and all documented response statuses; the [OpenAPI schemas](https://docs.debitura.com/assets/files/apis-ae4b8396e058fd1e5d37994844a8a578.json) provide the complete machine-readable contracts.

Use this brief with your coding agent:

```text
Build a small server-side Debitura Full Integration using this recipe and
the linked documentation. Use only the test API hosts and fictional data.
Keep the API key and bearer tokens on the server, outside code and logs.
Implement one invoice, show its preview, open the returned onboarding or
signing URL in a new tab, then read the actual API state before reporting
completion. Record where the documentation leaves you stuck.
```

<a id="prepare-test-access"></a>

## Prepare test access

Obtain a test referral partner key and arrange an address that can receive **test verification codes** with [partnerships@debitura.com](mailto:partnerships@debitura.com). Test email delivery is restricted to allowlisted domains. Your agent needs access to that test inbox or the code you provide during the browser step.

| Setting | Value |
| --- | --- |
| Server secret | `DEBITURA_API_KEY` — your test referral partner key |
| Referral Partner API | `https://testreferral-api.debitura.com` |
| Customer API | `https://testcustomer-api.debitura.com` |
| Hosted onboarding | URLs returned by the test API on `testreferral.debitura.com` |

Check the key with `GET /me` on the Referral Partner API, using the `XApiKey` header. Keep keys out of browser bundles, URLs, source control and agent transcripts. Use unique fictional company/user identifiers for each test run; replace the email placeholders below with your agreed test addresses.

The fixed-code demo is a simulation

The [public test demo](https://testreferral.debitura.com/demo) accepts `123456` for its isolated fictional sessions. It does not sign an actual agreement or complete ordinary API onboarding. A partner’s demo flag alone does not enable that code for a client created through `POST /clients`. Use a real test verification code for this recipe.

<a id="1-create-a-client"></a>

## 1\. Create a client

Your `externalTenantId` identifies your customer’s company, not the debtor. Use one stable value per company. The `client` object and `users` array are nested:

```http
POST https://testreferral-api.debitura.com/clients
XApiKey: YOUR_TEST_API_KEY
Idempotency-Key: ledgerline-client-RUN_ID
Content-Type: application/json

{
  "externalTenantId": "ledgerline-RUN_ID",
  "client": {
    "name": "Ledgerline Recipe Test Ltd",
    "country": "GB",
    "supportEmail": "YOUR_TEST_SUPPORT_EMAIL"
  },
  "users": [{
    "name": "Recipe Test User",
    "email": "YOUR_TEST_ONBOARDING_EMAIL",
    "isOnboardingUser": true
  }]
}
```

| Response | Your integration does |
| --- | --- |
| `202` | Open `onboardingLinks.url` in a new tab; the client needs onboarding |
| `201` | Continue; the client’s SDCA-based onboarding check is complete |
| `409` | Inspect the conflict type; follow [existing-client handling](https://docs.debitura.com/referral-partners/integration-guides/client-onboarding-conflicts.md) rather than creating another identity |
| `400` / `422` | Show the returned validation/business errors; correct the request |

Keep one idempotency key for retries of the **same** client-creation payload. Use a new key for a changed payload. A repeated `POST /clients` for an existing active link creates no further cases. Later invoices use the Customer API, not another embedded client-creation batch.

<a id="2-complete-and-verify-onboarding"></a>

## 2\. Complete and verify onboarding

Follow the returned URL through company details, users and agreement signing. Enter the real test verification code, review the required documents and complete the fictional test signature. Browser automation can drive the same forms. If code delivery is unavailable, record that blocker; do not substitute `123456`, a fabricated webhook or a database update that marks the agreement signed.

Read `GET /clients/ledgerline-RUN_ID` on the Referral Partner API with `XApiKey`. Continue when `onboardingDone` is `true`. A browser return containing `completed=true` is navigation feedback; it is not your source of truth. Later cases can still require a partner-specific agreement or KYC.

The [client onboarding guide](https://docs.debitura.com/referral-partners/integration-guides/client-onboarding.md) covers return URLs, interrupted onboarding and the full response contract.

<a id="3-preview-one-invoice"></a>

## 3\. Preview one invoice

Send `POST /cases/preview` on the **Referral Partner API**, authenticated with `XApiKey`. Preview does not create a case or require a client, so you can also show it before onboarding, as Ledgerline does. Choose a currently covered jurisdiction and use the same amount, currency, due date and debtor type/country you will submit:

```json
{
  "amountToRecover": 1500.00,
  "currencyCode": "EUR",
  "dueDate": "2026-10-01",
  "debtor": { "type": "Company", "countryAlpha2": "DE" }
}
```

Proceed only with `isEligible: true` and a usable `pricingPreview`. Display `pricingPreview.totalSuccessFeePercentage`; do not invent a fee from the demo. Treat `amountCheckUnavailable: true` or missing pricing as provisional and retry. Inspect `requiresKycVerification` and `pendingActions`; preview’s `combinedSigningUrl` is always `null`. See [Preview pricing](https://docs.debitura.com/referral-partners/integration-guides/preview-case-pricing.md).

<a id="4-mint-a-token-and-submit"></a>

## 4\. Mint a token and submit

Call `POST /oauth/token` on the **Referral Partner API**, with `XApiKey` and `{ "externalTenantId": "ledgerline-RUN_ID" }`. Use the returned `accessToken` as `Authorization: Bearer` on the **Customer API**. Tokens last 30 minutes; cache them per tenant. An active link can mint a token before onboarding completes, so token issuance alone does not prove signing succeeded.

Submit one case for the one invoice:

```http
POST https://testcustomer-api.debitura.com/cases
Authorization: Bearer YOUR_CLIENT_ACCESS_TOKEN
Idempotency-Key: ledgerline-case-RUN_ID-001
Content-Type: application/json

{
  "isTest": true,
  "allowPendingContracts": true,
  "creditorReference": "RECIPE-RUN_ID-001",
  "currencyCode": "EUR",
  "amountToRecover": 1500.00,
  "date": "2026-09-01",
  "dueDate": "2026-10-01",
  "claimDescription": "Fictional recipe invoice",
  "debtor": {
    "type": "Company",
    "name": "Recipe Test Debtor GmbH",
    "address": "Example Street 1",
    "city": "Berlin",
    "zipCode": "10115",
    "countryAlpha2": "DE",
    "email": "debtor@example.invalid"
  }
}
```

-   **Dates:** use past invoice/due dates, with `date` on or before `dueDate`.
-   **Invoice identity:** keep a stable `creditorReference` unique within the client and test/live classification.
-   **Retries:** reuse one `Idempotency-Key` with the identical body within its 24-hour replay window. A changed body with the same key returns `422 IdempotencyConflict`.
-   **Without a key:** duplicate-reference prevention does not replay the original response. After an ambiguous timeout, look up the reference before retrying. See [Idempotency](https://docs.debitura.com/developer-concepts/idempotency.md).

| Response | Next step |
| --- | --- |
| `200`, with `signingHandoff.combinedSigningUrl` | Open the returned signing flow, then read the case again. Missing signatures can leave its lifecycle at `Pending contract signing`. |
| `200`, no signing handoff | Read the actual case lifecycle; a case ID alone does not mean collection is active. |
| `422`, agreement or KYC requirement | Follow the returned handoff/`solutionUrl` and the [case submission](https://docs.debitura.com/referral-partners/integration-guides/case-submission.md) and [KYC verification](https://docs.debitura.com/referral-partners/integration-guides/kyc-verification.md) guides before retrying. |

<a id="5-read-back-and-record-the-result"></a>

## 5\. Read back and record the result

Use the case `id` with `GET /cases/{id}` on the Customer API and the same client bearer token. Check its reference, amount, currency, lifecycle and `isTestCase: true` (the request field is `isTest`, the response field is `isTestCase`).

The Referral Partner API’s case list and detail exclude test/demo cases: an empty `GET /cases` list or a `404` from its `GET /cases/{id}` does not mean your test submission failed. Use the Customer API readback for this trial. Referral reporting is for production cases; do not switch this recipe to live case creation just to make a reporting row appear.

Record a short run log without keys, tokens, verification codes or personal payloads:

| Check | Record |
| --- | --- |
| Create/link client | HTTP status and conflict type, if any |
| Hosted onboarding | Completed with a real test code, or the exact point of friction |
| API state | Actual `onboardingDone`; never inferred from a redirect |
| Preview | Eligibility, pricing available, required next steps |
| Submit/read | Status, test classification, reference and actual lifecycle |
| Retry | Existing case found by reference; no second case |
| Failure handling | Invalid key/request, another partner’s tenant refused, unavailable dependency surfaced |

For ongoing updates, implement [webhooks](https://docs.debitura.com/referral-partners/integration-guides/webhooks.md) and [test delivery/signatures](https://docs.debitura.com/referral-partners/integration-guides/webhook-testing.md). A synthetic webhook does not change underlying onboarding or case state. When finished, use the [test reset endpoints](https://docs.debitura.com/referral-partners/getting-started/environments.md#reset-test-clients); first inspect blockers and close any active test cases before requesting deletion.
