# Billyou API - Partners

## Overview

The Partner API lets an approved Billyou partner provision Billyou accounts on
behalf of their own end-customers — a B2B2C ("Business-to-Business-to-Consumer")
model. A typical partner is an accounting platform, an ERP, a vertical SaaS, or
a marketplace that wants to onboard its users onto Billyou without making them
sign up manually.

The flow is:

1. The partner calls `POST /api/partner/accounts` with the end-customer's
   company details. Billyou creates a **trial** organization for that
   end-customer and returns a **production API key** scoped to the new
   organization.
2. Billyou emails the end-customer a **partner-branded invite** to log in and
   complete their registration.
3. The end-customer activates the account and, after the trial, **self-subscribes
   at standard Billyou prices**. The partner does not pay for the end-customer
   and does not set the price — they only curate which plans are offered.

The partner keeps using the production API key it received to operate the
end-customer's account (create invoices, manage clients, etc.) just like any
other `bk_user_*` key.

**Base URL**: `https://app.billyou.ro/api`
**Authentication**: `X-API-Key` header required on all requests.

## Authentication & Partner Enablement

There is **no special partner key type**. The Partner API is unlocked by using an
ordinary `bk_user_*` API key whose organization has been configured as a partner
(it has a `partner_config`). When a partner key is used:

- The 4 Partner endpoints below become available.
- `GET /api/plans` is filtered to the partner's allowed plans.

If the calling key's organization has no partner configuration, the Partner
endpoints return `403 PARTNER_NOT_ENABLED`. If the organization is a partner but
has been suspended, they return `403 PARTNER_SUSPENDED`. Contact Billyou to have
your organization enabled as a partner.

```
X-API-Key: bk_user_your_partner_key_here
```

## Account Lifecycle

A provisioned account moves through three milestones. The partner is notified of
each transition via webhooks (see below).

```
provisioned -> activated -> subscribed
```

- **provisioned**: The trial organization was created. The end-customer has been
  emailed the partner-branded invite but has not logged in yet. The returned
  production API key already works. Billyou emits `account.provisioned`.
- **activated**: The end-customer logged in and completed registration. Billyou
  emits `account.activated`.
- **subscribed**: After the trial, the end-customer self-subscribed to a paid
  plan at standard prices. Billyou emits `account.subscribed`.

Track these milestones via the webhook events below — they are the source of
truth for a child account's progress. The `activationStatus` field in the
**provisioning response** is not a lifecycle cursor: it is always returned as
`"invite_sent"`, signalling only that the invite has been dispatched.

## Endpoints

### POST /api/partner/accounts - Provision Account

Provision a new **trial** account for one of your end-customers. Billyou creates
the organization, emails a partner-branded invite, and returns a production API
key for the new organization.

**Idempotency**: Pass an `Idempotency-Key` header to make retries safe. Repeating
a request with the same key returns the original result instead of creating a
second account.

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `email` | string | Yes | End-customer contact email (receives the invite) |
| `firstName` | string | Yes | End-customer first name |
| `lastName` | string | Yes | End-customer last name |
| `cui` | string | Conditional | Romanian company tax id (CUI). Provide **either** `cui` **or** `cnp`, not both |
| `cnp` | string | Conditional | Romanian personal numeric code (CNP) for individuals. Mutually exclusive with `cui` |
| `companyName` | string | Conditional | Legal/company name. Required for company (`cui`) accounts |
| `tradeRegistryNumber` | string | No | Trade registry (J) number for companies |
| `address` | object | No | Structured postal address (see fields below) |
| `address.street` | string | No | Street name |
| `address.number` | string | No | Street number |
| `address.city` | string | No | City |
| `address.county` | string | No | County / judet |
| `address.postalCode` | string | No | Postal code |
| `address.completeAddress` | string | No | Free-form full address (used when the structured fields are unavailable) |
| `phone` | string | No | End-customer phone number |
| `locale` | string | No | Invite/UI language: `"ro"` (default) or `"en"` |

**Example Request**:
```bash
curl -X POST https://app.billyou.ro/api/partner/accounts \
  -H "X-API-Key: bk_user_your_partner_key" \
  -H "Idempotency-Key: 7d8f2c1a-9b3e-4a6f-8c2d-1e5f4a7b9c0d" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "ion.popescu@example.ro",
    "firstName": "Ion",
    "lastName": "Popescu",
    "cui": "RO12345678",
    "companyName": "SC Example Client SRL",
    "address": {
      "street": "Strada Exemplu",
      "number": "123",
      "city": "Bucuresti",
      "county": "Bucuresti",
      "postalCode": "010101"
    },
    "locale": "ro"
  }'
```

**Response** (`201 Created`):
```json
{
  "success": true,
  "data": {
    "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
    "apiKey": "bk_user_live_a1b2c3d4e5f6g7h8i9j0k1l2",
    "activationStatus": "invite_sent"
  }
}
```

**IMPORTANT**: The returned `apiKey` is a **production** `bk_user_*` key for the
newly created organization. It is shown **only once** in this response — store it
securely. Use it for all subsequent API calls on behalf of that end-customer.

**Error - Duplicate tax id** (`409 Conflict`):
```json
{
  "success": false,
  "errorCode": "ORG_EXISTS",
  "message": "A provisioned account already exists for this tax id"
}
```

**Error - Provisioning timed out** (`503 Service Unavailable`):
```json
{
  "success": false,
  "errorCode": "PROVISIONING_TIMEOUT",
  "message": "Provisioning timed out"
}
```

`PROVISIONING_TIMEOUT` is **retry-safe**: retry the same request with the same
`Idempotency-Key`. If the account was actually created, the retry returns the
original `201` result; otherwise provisioning is attempted again.

### GET /api/partner/accounts - List Provisioned Accounts

Retrieve a paginated list of the accounts you have provisioned.

**Query Parameters**:

| Parameter | Type | Description |
|---|---|---|
| `page` | integer | Page number (default: 1) |
| `limit` | integer | Items per page (default: 20, max: 100) |

**Example Request**:
```bash
curl -X GET "https://app.billyou.ro/api/partner/accounts?page=1&limit=20" \
  -H "X-API-Key: bk_user_your_partner_key"
```

The list is returned as a bare array under `data`, with pagination under `meta`.

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": [
    {
      "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
      "name": "SC Example Client SRL",
      "cui": "12345678",
      "cnp": null,
      "firstName": "Ion",
      "lastName": "Popescu",
      "accountType": "company",
      "provisionedByPartnerOrgId": "60a1b2c3d4e5f60718293a4b",
      "createdVia": "PARTNER_API",
      "createdAt": "2026-01-15T10:30:00.000Z"
    }
  ],
  "meta": {
    "total": 1,
    "page": 1,
    "limit": 20
  }
}
```

Each account is the safe partner-facing view of a child org. The company name is
in `name` (not `companyName`); for individual accounts `name`/`cui` are `null`
and `cnp` is populated. There is no `email` or `activationStatus` field on this
object.

### GET /api/partner/accounts/:id - Get Provisioned Account

Retrieve a single account you have provisioned, by its `organizationId`.

**Example Request**:
```bash
curl -X GET https://app.billyou.ro/api/partner/accounts/org_a1b2c3d4e5f6 \
  -H "X-API-Key: bk_user_your_partner_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
    "name": "SC Example Client SRL",
    "cui": "12345678",
    "cnp": null,
    "firstName": "Ion",
    "lastName": "Popescu",
    "accountType": "company",
    "provisionedByPartnerOrgId": "60a1b2c3d4e5f60718293a4b",
    "createdVia": "PARTNER_API",
    "createdAt": "2026-01-15T10:30:00.000Z"
  }
}
```

**Error - Not owned by the partner** (`404 Not Found`):
```json
{
  "success": false,
  "errorCode": "NOT_FOUND",
  "message": "Account not found"
}
```

A partner can only read accounts it provisioned. Requesting an account that
belongs to a different partner (or that does not exist) returns `404`.

### GET /api/plans - List Plans

Retrieve the plan catalog **filtered to the plans your partner configuration
allows** (`partner_config.allowedPlans`; if empty, the full catalog is returned).
This is curation only — the end-customer always pays the standard Billyou price
for whichever plan they pick. Use this to show your end-customers the subset of
plans you want to offer.

**Example Request**:
```bash
curl -X GET https://app.billyou.ro/api/plans \
  -H "X-API-Key: bk_user_your_partner_key"
```

The catalog is returned as a bare array under `data`. Each plan carries its Stripe
product `id`, a `name`, and a `prices` array of `{ id, currency, interval }`. The
catalog does **not** include numeric prices.

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": [
    {
      "id": "prod_ABC123",
      "name": "Starter",
      "prices": [
        { "id": "price_ABC123", "currency": "ron", "interval": "month" }
      ]
    },
    {
      "id": "prod_DEF456",
      "name": "Pro",
      "prices": [
        { "id": "price_DEF456", "currency": "ron", "interval": "month" },
        { "id": "price_GHI789", "currency": "ron", "interval": "year" }
      ]
    }
  ]
}
```

## Webhooks

Account lifecycle events are delivered to the **partner's** webhook endpoints (the
ones you register with `POST /api/webhooks/endpoints` using your partner key).
Subscribe to these event types to track each provisioned account's progress.

See the [Webhooks reference](/llm-context/billyou-webhooks.md) for signature
verification, retries, and delivery format.

| Event Type | Description | Trigger |
|---|---|---|
| `account.provisioned` | A trial account was created for an end-customer | `POST /api/partner/accounts` succeeds |
| `account.activated` | The end-customer logged in and completed registration | The end-customer finalizes onboarding |
| `account.subscribed` | The end-customer self-subscribed to a paid plan | The end-customer's paid subscription is created |

**Delivery envelope.** Every delivered webhook is wrapped in the standard event
envelope, and the event-specific fields live under `data.object`:

```json
{
  "id": "evt_lq7x2k_3f9a1b2c4d5e",
  "type": "account.provisioned",
  "api_version": "2026-03-01",
  "created": "2026-01-15T10:30:00.000Z",
  "data": {
    "object": { "...": "event-specific fields, shown below" }
  }
}
```

In all three events, `data.object.organizationId` is the **child** (end-customer)
org id, and `data.object.partnerOrgId` is your partner org id.

### account.provisioned — `data.object`

```json
{
  "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
  "partnerOrgId": "60a1b2c3d4e5f60718293a4b",
  "companyName": "SC Example Client SRL",
  "taxId": "12345678",
  "createdAt": "2026-01-15T10:30:00.000Z",
  "trialEndDate": "2026-02-14T10:30:00.000Z"
}
```

`trialEndDate` is the ISO timestamp when the 30-day trial lapses.

### account.activated — `data.object`

```json
{
  "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
  "partnerOrgId": "60a1b2c3d4e5f60718293a4b",
  "activatedAt": "2026-01-16T09:00:00.000Z"
}
```

### account.subscribed — `data.object`

```json
{
  "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
  "partnerOrgId": "60a1b2c3d4e5f60718293a4b",
  "plan": "prod_DEF456",
  "priceId": "price_DEF456",
  "subscribedAt": "2026-01-30T12:00:00.000Z"
}
```

`plan` is the Stripe **product** id — it matches the `id` values from
`/api/plans` and your `partner_config.allowedPlans`, so you can reconcile the
subscription against the plan catalog. `priceId` is the underlying Stripe price
the end-customer actually subscribed to.

## Common Workflow

### Provision an account and track it to subscription

```typescript
const PARTNER_KEY = "bk_user_your_partner_key";
const BASE_URL = "https://app.billyou.ro/api";

// 1. Register a webhook for the account lifecycle (once)
const endpoint = await fetch(`${BASE_URL}/webhooks/endpoints`, {
  method: "POST",
  headers: { "X-API-Key": PARTNER_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://your-app.com/webhooks/billyou",
    description: "Partner account lifecycle",
    events: ["account.provisioned", "account.activated", "account.subscribed"],
  }),
}).then((r) => r.json());

console.log("Save this signing secret:", endpoint.data.secret);

// 2. Provision a trial account for an end-customer (idempotent)
const provision = await fetch(`${BASE_URL}/partner/accounts`, {
  method: "POST",
  headers: {
    "X-API-Key": PARTNER_KEY,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    email: "ion.popescu@example.ro",
    firstName: "Ion",
    lastName: "Popescu",
    cui: "RO12345678",
    companyName: "SC Example Client SRL",
    address: { city: "Bucuresti", county: "Bucuresti" },
    locale: "ro",
  }),
}).then((r) => r.json());

// 3. Store the production key for the new org — shown only once.
//    activationStatus is "invite_sent" here.
await saveOrgKey(provision.data.organizationId, provision.data.apiKey);

// 4. account.activated then account.subscribed arrive at your webhook later.
//    Read the event-specific fields from the body's `data.object`:
//      const childOrgId = event.data.object.organizationId;
//      if (event.type === "account.subscribed") { /* event.data.object.plan */ }
```

## Error Codes

| Code | HTTP | Description |
|---|---|---|
| `VALIDATION_ERROR` | 400 | Invalid body — e.g. both `cui` and `cnp` given, or a required field missing |
| `UNAUTHORIZED` | 401 | API key is invalid or missing |
| `PARTNER_NOT_ENABLED` | 403 | The calling key's organization has no partner configuration |
| `PARTNER_SUSPENDED` | 403 | The partner organization is suspended |
| `NOT_FOUND` | 404 | The requested account was not provisioned by this partner |
| `ORG_EXISTS` | 409 | A provisioned account already exists for this tax id |
| `PROVISIONING_TIMEOUT` | 503 | Provisioning timed out; retry-safe with the same `Idempotency-Key` |
