# Billyou API - Webhooks

## Overview

The Billyou webhook system delivers real-time event notifications to your application via HTTP POST requests. When events occur (invoices issued, payments received, E-Factura status changes), Billyou sends a signed JSON payload to your registered endpoint URLs.

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

## How Webhooks Work

1. **Register an endpoint** with a URL and the events you want to receive
2. **Store the signing secret** returned during creation (shown only once)
3. **Receive events** as HTTP POST requests to your URL
4. **Verify the signature** using HMAC-SHA256 to ensure authenticity
5. **Respond with 2xx** to acknowledge delivery (or Billyou will retry)

## Event Types

### Invoice Events

| Event Type | Description | Trigger |
|---|---|---|
| `invoice.issued` | Invoice finalized and sent to client | Invoice status changes to "sent" |
| `invoice.paid` | Invoice fully paid | Total payments >= invoice total |
| `invoice.canceled` | Invoice cancelled | Invoice cancellation processed |

### E-Factura Events

| Event Type | Description | Trigger |
|---|---|---|
| `invoice.efactura_sent` | Submitted to ANAF | E-Factura submission initiated |
| `invoice.efactura_accepted` | Accepted by ANAF | ANAF returns "ok" status |
| `invoice.efactura_rejected` | Rejected by ANAF | ANAF returns "nok" status |

### Customer Events

| Event Type | Description | Trigger |
|---|---|---|
| `customer.created` | New client created | Client added to organization |
| `customer.updated` | Client information updated | Client record modified |
| `customer.deleted` | Client deleted | Client removed from organization |

### E-Transport Events

| Event Type | Description | Trigger |
|---|---|---|
| `etransport.declaration.processed` | ANAF returned OK and the UIT code was extracted | Declaration polling returns a processed status |
| `etransport.declaration.rejected` | ANAF rejected the declaration | Declaration polling returns a rejected status |

#### etransport.declaration.processed payload

```json
{
  "type": "etransport.declaration.processed",
  "organizationId": "org_xxx",
  "resourceId": "decl_yyy",
  "environment": "production",
  "timestamp": "2026-01-15T10:30:00Z",
  "data": {
    "id": "decl_yyy",
    "declarationType": "NOTIFICATION",
    "status": "processed",
    "uitCode": "UIT-ABCDEF",
    "uploadIndex": "UP-001"
  }
}
```

#### etransport.declaration.rejected payload

```json
{
  "type": "etransport.declaration.rejected",
  "organizationId": "org_xxx",
  "resourceId": "decl_yyy",
  "environment": "production",
  "timestamp": "2026-01-15T10:30:00Z",
  "data": {
    "id": "decl_yyy",
    "declarationType": "NOTIFICATION",
    "status": "rejected",
    "uploadIndex": "UP-001"
  }
}
```

`declarationType` is one of `NOTIFICATION`, `CONFIRMATION`, or `DELETION`.
`environment` is `production` or `sandbox`.

### Account Events

These events are delivered to a **partner's** webhook endpoints and track the
lifecycle of accounts the partner provisioned via the Partner API. See the
[Partners reference](/llm-context/billyou-partners.md) for the full provisioning
flow.

| 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 at standard prices | The end-customer's paid subscription is created |

Account events are delivered in the standard event envelope: the top level is
`{ id, type, api_version, created, data: { object } }`, and the event-specific
fields live under `data.object`. In every account event, `data.object.organizationId`
is the **child** (end-customer) org id and `data.object.partnerOrgId` is the
partner org id.

#### account.provisioned payload

```json
{
  "id": "evt_lq7x2k_3f9a1b2c4d5e",
  "type": "account.provisioned",
  "api_version": "2026-03-01",
  "created": "2026-01-15T10:30:00.000Z",
  "data": {
    "object": {
      "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 payload

```json
{
  "id": "evt_lq8y3m_7a1b2c3d4e5f",
  "type": "account.activated",
  "api_version": "2026-03-01",
  "created": "2026-01-16T09:00:00.000Z",
  "data": {
    "object": {
      "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
      "partnerOrgId": "60a1b2c3d4e5f60718293a4b",
      "activatedAt": "2026-01-16T09:00:00.000Z"
    }
  }
}
```

#### account.subscribed payload

```json
{
  "id": "evt_lqa05p_9c2d3e4f5a6b",
  "type": "account.subscribed",
  "api_version": "2026-03-01",
  "created": "2026-01-30T12:00:00.000Z",
  "data": {
    "object": {
      "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
      "partnerOrgId": "60a1b2c3d4e5f60718293a4b",
      "plan": "prod_DEF456",
      "priceId": "price_DEF456",
      "subscribedAt": "2026-01-30T12:00:00.000Z"
    }
  }
}
```

`plan` is the Stripe **product** id (matches `/api/plans` and your
`partner_config.allowedPlans`); `priceId` is the underlying Stripe price id the
end-customer actually subscribed to.

## Endpoints

### POST /api/webhooks/endpoints - Create Endpoint

Create a new webhook endpoint. The **signing secret is returned only once** during creation. Store it securely.

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string | Yes | HTTPS URL to receive webhook POST requests |
| `description` | string | No | Human-readable description (max 500 chars) |
| `events` | string[] | Yes | Event types to subscribe to (min 1, unique items) |

**Example Request**:
```bash
curl -X POST https://app.billyou.ro/api/webhooks/endpoints \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/billyou",
    "description": "Production invoice notifications",
    "events": [
      "invoice.issued",
      "invoice.paid",
      "invoice.canceled",
      "invoice.efactura_accepted",
      "invoice.efactura_rejected"
    ]
  }'
```

**Response** (`201 Created`):
```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "url": "https://your-app.com/webhooks/billyou",
    "description": "Production invoice notifications",
    "events": [
      "invoice.issued",
      "invoice.paid",
      "invoice.canceled",
      "invoice.efactura_accepted",
      "invoice.efactura_rejected"
    ],
    "is_active": true,
    "secret": "whsec_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0",
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-15T10:00:00Z"
  }
}
```

**IMPORTANT**: The `secret` field is only returned during creation. Save it immediately and securely. You cannot retrieve it later.

### GET /api/webhooks/endpoints - List Endpoints

Retrieve your webhook endpoints with cursor-based pagination.

**Query Parameters**:

| Parameter | Type | Description |
|---|---|---|
| `limit` | integer | Items per page (default: 10, max: 100) |
| `starting_after` | string | Cursor: return items after this ID |
| `ending_before` | string | Cursor: return items before this ID |
| `is_active` | boolean | Filter by active/inactive status |

**Example Request**:
```bash
curl -X GET "https://app.billyou.ro/api/webhooks/endpoints?limit=10&is_active=true" \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": [
    {
      "id": "60f7b1b9c9e7b4a1e8d1c2b3",
      "url": "https://your-app.com/webhooks/billyou",
      "description": "Production invoice notifications",
      "events": ["invoice.issued", "invoice.paid"],
      "is_active": true,
      "created_at": "2026-01-15T10:00:00Z",
      "updated_at": "2026-01-15T10:00:00Z"
    }
  ],
  "has_more": false,
  "total_count": 1
}
```

### GET /api/webhooks/endpoints/:id - Get Endpoint

Retrieve a specific webhook endpoint by ID.

```bash
curl -X GET https://app.billyou.ro/api/webhooks/endpoints/60f7b1b9c9e7b4a1e8d1c2b3 \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "url": "https://your-app.com/webhooks/billyou",
    "description": "Production invoice notifications",
    "events": ["invoice.issued", "invoice.paid"],
    "is_active": true,
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-15T10:00:00Z"
  }
}
```

### PUT /api/webhooks/endpoints/:id - Update Endpoint

Update an existing endpoint. All fields are optional.

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string | No | New endpoint URL |
| `description` | string | No | New description |
| `events` | string[] | No | New event subscriptions |
| `is_active` | boolean | No | Enable/disable the endpoint |

**Example - Disable an endpoint**:
```bash
curl -X PUT https://app.billyou.ro/api/webhooks/endpoints/60f7b1b9c9e7b4a1e8d1c2b3 \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "is_active": false
  }'
```

**Example - Add event subscriptions**:
```bash
curl -X PUT https://app.billyou.ro/api/webhooks/endpoints/60f7b1b9c9e7b4a1e8d1c2b3 \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      "invoice.issued",
      "invoice.paid",
      "invoice.canceled",
      "customer.created",
      "customer.updated"
    ]
  }'
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "url": "https://your-app.com/webhooks/billyou",
    "description": "Production invoice notifications",
    "events": ["invoice.issued", "invoice.paid", "invoice.canceled", "customer.created", "customer.updated"],
    "is_active": true,
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-16T14:00:00Z"
  }
}
```

### DELETE /api/webhooks/endpoints/:id - Delete Endpoint

Delete a webhook endpoint. All future event deliveries to this endpoint will stop.

```bash
curl -X DELETE https://app.billyou.ro/api/webhooks/endpoints/60f7b1b9c9e7b4a1e8d1c2b3 \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "deleted": true
  }
}
```

### POST /api/webhooks/endpoints/:id/test - Test Endpoint

Send a test event to verify endpoint connectivity.

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `event_type` | string | No | Event type to simulate (default: "invoice.issued") |

```bash
curl -X POST https://app.billyou.ro/api/webhooks/endpoints/60f7b1b9c9e7b4a1e8d1c2b3/test \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "event_type": "invoice.paid"
  }'
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "success": true,
    "status_code": 200,
    "response_time_ms": 145,
    "response_body": "{\"status\": \"ok\"}"
  }
}
```

**Response - Endpoint Failed** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "success": false,
    "status_code": 500,
    "response_time_ms": 3200,
    "response_body": "Internal Server Error"
  }
}
```

### GET /api/webhooks/deliveries - List Deliveries

Retrieve webhook delivery history with cursor-based pagination.

**Query Parameters**:

| Parameter | Type | Description |
|---|---|---|
| `limit` | integer | Items per page (default: 10, max: 100) |
| `starting_after` | string | Cursor for forward pagination |
| `ending_before` | string | Cursor for backward pagination |
| `status` | string | Filter: `pending`, `success`, `failed` |

```bash
curl -X GET "https://app.billyou.ro/api/webhooks/deliveries?status=failed&limit=20" \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": [
    {
      "id": "60f7b1b9c9e7b4a1e8d1c2b4",
      "endpoint_id": "60f7b1b9c9e7b4a1e8d1c2b3",
      "event_type": "invoice.issued",
      "status": "failed",
      "status_code": 500,
      "request_body": {
        "event": "invoice.issued",
        "data": {
          "invoiceId": "68dcc67261bb80850ae1299e",
          "serialNumber": "FACT-00123"
        }
      },
      "response_body": "Internal Server Error",
      "response_time_ms": 5000,
      "attempt_count": 3,
      "next_retry_at": "2026-01-16T10:00:00Z",
      "created_at": "2026-01-15T10:00:00Z",
      "updated_at": "2026-01-15T10:30:00Z"
    }
  ],
  "has_more": false,
  "total_count": 1
}
```

### POST /api/webhooks/deliveries/:id/retry - Retry Delivery

Manually retry a failed webhook delivery.

```bash
curl -X POST https://app.billyou.ro/api/webhooks/deliveries/60f7b1b9c9e7b4a1e8d1c2b4/retry \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b4",
    "endpoint_id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "event_type": "invoice.issued",
    "status": "pending",
    "attempt_count": 4,
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-16T14:00:00Z"
  }
}
```

### GET /api/webhooks/event-types - List Event Types

Retrieve all available webhook event types with descriptions and categories.

```bash
curl -X GET https://app.billyou.ro/api/webhooks/event-types \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": [
    {
      "type": "invoice.issued",
      "description": "Triggered when an invoice is issued and sent to the client.",
      "category": "Invoices"
    },
    {
      "type": "invoice.paid",
      "description": "Triggered when an invoice is fully paid.",
      "category": "Invoices"
    },
    {
      "type": "invoice.canceled",
      "description": "Triggered when an invoice is canceled.",
      "category": "Invoices"
    },
    {
      "type": "invoice.efactura_sent",
      "description": "Triggered when an invoice is submitted to the Romanian E-Factura system.",
      "category": "E-Factura"
    },
    {
      "type": "invoice.efactura_accepted",
      "description": "Triggered when an invoice is accepted by the Romanian E-Factura system.",
      "category": "E-Factura"
    },
    {
      "type": "invoice.efactura_rejected",
      "description": "Triggered when an invoice is rejected by the Romanian E-Factura system.",
      "category": "E-Factura"
    },
    {
      "type": "customer.created",
      "description": "Triggered when a new customer/client is created.",
      "category": "Customers"
    },
    {
      "type": "customer.updated",
      "description": "Triggered when a customer/client is updated.",
      "category": "Customers"
    },
    {
      "type": "customer.deleted",
      "description": "Triggered when a customer/client is deleted.",
      "category": "Customers"
    },
    {
      "type": "etransport.declaration.processed",
      "description": "Triggered when ANAF returns OK and the UIT code is extracted for an E-Transport declaration.",
      "category": "E-Transport"
    },
    {
      "type": "etransport.declaration.rejected",
      "description": "Triggered when ANAF rejects an E-Transport declaration.",
      "category": "E-Transport"
    },
    {
      "type": "account.provisioned",
      "description": "Triggered when a partner provisions a trial account for an end-customer.",
      "category": "Accounts"
    },
    {
      "type": "account.activated",
      "description": "Triggered when a provisioned end-customer logs in and completes registration.",
      "category": "Accounts"
    },
    {
      "type": "account.subscribed",
      "description": "Triggered when a provisioned end-customer self-subscribes to a paid plan.",
      "category": "Accounts"
    }
  ]
}
```

## HMAC Signature Verification

Every webhook delivery includes a `Billyou-Signature` header. Verify it to confirm the request is authentic and has not been tampered with.

### Signature Header Format

```
Billyou-Signature: t=<unix_timestamp>,v1=<hmac_sha256_hex>
```

`t` is the Unix timestamp (integer seconds) at which the delivery was sent. `v1` is the HMAC-SHA256 of `t + "." + raw_body` hex-encoded.

### Verification Algorithm

1. Read the raw request body **before** JSON parsing
2. Parse the `Billyou-Signature` header into its `t` and `v1` components (split on `,`, then on the first `=`)
3. Compute `HMAC-SHA256(webhook_secret, t + "." + raw_body)` and hex-encode the result
4. Compare the computed value against `v1` using a timing-safe comparison

### Node.js / TypeScript Example

```typescript
import crypto from "node:crypto";
import express from "express";

const app = express();

// IMPORTANT: Use raw body for signature verification
app.use("/webhooks/billyou", express.raw({ type: "application/json" }));

const WEBHOOK_SECRET = "whsec_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0";

function verifyWebhookSignature(
  rawBody: Buffer | string,
  signatureHeader: string,
  secret: string
): boolean {
  // Parse the header: "t=1234567890,v1=abc123..."
  const parts = Object.fromEntries(
    signatureHeader.split(",").map((p) => {
      const idx = p.indexOf("=");
      return [p.slice(0, idx), p.slice(idx + 1)];
    })
  );
  const timestamp = parts["t"];
  const receivedSig = parts["v1"];

  if (!timestamp || !receivedSig) return false;

  // Compute expected signature: HMAC-SHA256(secret, timestamp + "." + raw_body)
  const signedPayload = `${timestamp}.${rawBody}`;
  const expected = crypto
    .createHmac("sha256", secret)
    .update(signedPayload, "utf8")
    .digest("hex");

  if (receivedSig.length !== expected.length) return false;

  // Use timing-safe comparison to prevent timing attacks
  return crypto.timingSafeEqual(
    Buffer.from(receivedSig, "utf8"),
    Buffer.from(expected, "utf8")
  );
}

app.post("/webhooks/billyou", (req, res) => {
  const signature = req.headers["billyou-signature"] as string;

  if (!signature) {
    return res.status(401).json({ error: "Missing signature header" });
  }

  if (!verifyWebhookSignature(req.body, signature, WEBHOOK_SECRET)) {
    return res.status(401).json({ error: "Invalid signature" });
  }

  // Signature is valid - process the event
  const event = JSON.parse(req.body.toString());
  console.log(`Received event: ${event.type}`);

  switch (event.type) {
    case "invoice.issued":
      handleInvoiceIssued(event.data);
      break;
    case "invoice.paid":
      handleInvoicePaid(event.data);
      break;
    case "invoice.efactura_accepted":
      handleEfacturaAccepted(event.data);
      break;
    case "invoice.efactura_rejected":
      handleEfacturaRejected(event.data);
      break;
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }

  // Always respond with 2xx to acknowledge receipt
  res.status(200).json({ received: true });
});

app.listen(3000);
```

### Python Example

```python
import hmac
import hashlib
from flask import Flask, request, jsonify

app = Flask(__name__)

WEBHOOK_SECRET = "whsec_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0"

def verify_webhook_signature(raw_body: bytes, signature_header: str, secret: str) -> bool:
    # Parse the header: "t=1234567890,v1=abc123..."
    parts = {}
    for part in signature_header.split(","):
        idx = part.index("=")
        parts[part[:idx]] = part[idx + 1:]

    timestamp = parts.get("t")
    received_sig = parts.get("v1")

    if not timestamp or not received_sig:
        return False

    # Compute expected: HMAC-SHA256(secret, timestamp + "." + raw_body)
    signed_payload = f"{timestamp}.{raw_body.decode('utf-8')}"
    expected = hmac.new(
        secret.encode("utf-8"),
        signed_payload.encode("utf-8"),
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(expected, received_sig)

@app.route("/webhooks/billyou", methods=["POST"])
def handle_webhook():
    signature = request.headers.get("Billyou-Signature")

    if not signature:
        return jsonify({"error": "Missing signature"}), 401

    if not verify_webhook_signature(request.data, signature, WEBHOOK_SECRET):
        return jsonify({"error": "Invalid signature"}), 401

    event = request.get_json()
    print(f"Received: {event['type']}")

    return jsonify({"received": True}), 200
```

## Retry Policy

When a webhook delivery fails (non-2xx response or timeout), Billyou automatically retries with exponential backoff:

| Attempt | Delay After Failure |
|---|---|
| 1st retry | ~1 minute |
| 2nd retry | ~5 minutes |
| 3rd retry | ~30 minutes |
| 4th retry | ~2 hours |
| 5th retry | ~8 hours |

**Maximum retries**: 5 attempts total (including the original delivery)

**Timeout**: Your endpoint must respond within 30 seconds or the delivery is marked as failed.

**Success criteria**: Any HTTP 2xx status code (200, 201, 202, etc.) is considered successful.

After all retry attempts are exhausted, the delivery is permanently marked as `failed`. You can manually retry it via the `POST /webhooks/deliveries/:id/retry` endpoint.

## Delivery Payload Format

Webhook payloads are sent as JSON with the following structure:

```json
{
  "event": "invoice.issued",
  "data": {
    "invoiceId": "68dcc67261bb80850ae1299e",
    "serialNumber": "FACT-00123",
    "clientName": "SC Example SRL",
    "totalAmount": 1904.00,
    "currency": "RON",
    "issueDate": "2025-03-15"
  },
  "timestamp": "2026-01-15T10:00:00Z",
  "webhook_id": "60f7b1b9c9e7b4a1e8d1c2b4"
}
```

### Headers Sent With Each Delivery

| Header | Description |
|---|---|
| `Content-Type` | `application/json` |
| `Billyou-Signature` | HMAC-SHA256 signature (`t=<timestamp>,v1=<hmac-hex>`) |
| `Billyou-Event` | Event type (e.g., `invoice.issued`) |
| `Billyou-Delivery` | Unique delivery ID for idempotency |
| `User-Agent` | `Billyou-Webhooks/1.0` |

## Best Practices

### 1. Verify Signatures Always
Never skip signature verification, even in development. It protects against replay attacks and request forgery.

### 2. Respond Quickly
Process events asynchronously. Return `200 OK` immediately after receiving the webhook, then process the event in a background job. Long-running processing may cause timeouts and retries.

### 3. Handle Duplicate Deliveries
Use the `Billyou-Delivery` header for idempotency. Store processed delivery IDs and skip duplicates:

```typescript
const processedDeliveries = new Set<string>();

app.post("/webhooks/billyou", (req, res) => {
  const deliveryId = req.headers["billyou-delivery"] as string;

  if (processedDeliveries.has(deliveryId)) {
    // Already processed - return success to stop retries
    return res.status(200).json({ received: true, duplicate: true });
  }

  processedDeliveries.add(deliveryId);
  // Process event...

  res.status(200).json({ received: true });
});
```

### 4. Subscribe to Specific Events
Only subscribe to the events you need. This reduces unnecessary traffic and processing.

### 5. Use Test Endpoint
Before going live, use the test endpoint to verify your handler works correctly:

```bash
curl -X POST https://app.billyou.ro/api/webhooks/endpoints/<id>/test \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{"event_type": "invoice.issued"}'
```

### 6. Monitor Deliveries
Periodically check for failed deliveries and retry them:

```bash
curl -X GET "https://app.billyou.ro/api/webhooks/deliveries?status=failed" \
  -H "X-API-Key: bk_user_your_key"
```

## Complete Setup Example

```typescript
const API_KEY = "bk_user_your_api_key";
const BASE_URL = "https://app.billyou.ro/api";

async function setupWebhooks() {
  // 1. Create the endpoint
  const response = await fetch(`${BASE_URL}/webhooks/endpoints`, {
    method: "POST",
    headers: {
      "X-API-Key": API_KEY,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: "https://your-app.com/webhooks/billyou",
      description: "Production - all invoice events",
      events: [
        "invoice.issued",
        "invoice.paid",
        "invoice.canceled",
        "invoice.efactura_accepted",
        "invoice.efactura_rejected",
        "customer.created",
      ],
    }),
  });

  const result = await response.json();

  console.log("Endpoint ID:", result.data.id);
  console.log("Signing Secret:", result.data.secret);
  console.log("IMPORTANT: Save this secret securely!");

  // 2. Test the endpoint
  const testResponse = await fetch(
    `${BASE_URL}/webhooks/endpoints/${result.data.id}/test`,
    {
      method: "POST",
      headers: {
        "X-API-Key": API_KEY,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ event_type: "invoice.issued" }),
    }
  );

  const testResult = await testResponse.json();
  console.log("Test result:", testResult.data.success ? "PASS" : "FAIL");
  console.log("Response time:", testResult.data.response_time_ms, "ms");
}
```
