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

# Webhooks

> Receive real-time event notifications

# Webhooks

Receive real-time notifications when events occur in usmewe.

## Overview

Webhooks allow your application to receive HTTP POST requests when specific events happen, enabling real-time integrations.

```
┌─────────────────────────────────────────────────────────────────┐
│  usmewe                          Your Server                    │
│     │                                 │                         │
│     │  Event occurs                   │                         │
│     │  (loan.funded)                  │                         │
│     │                                 │                         │
│     │  ───────POST /webhook───────►   │                         │
│     │                                 │  Process event          │
│     │  ◄─────── 200 OK ───────────    │                         │
│     │                                 │                         │
└─────────────────────────────────────────────────────────────────┘
```

## Register Webhook

Create a new webhook endpoint.

<CodeGroup>
  ```bash Request theme={null}
  curl -X POST "https://api.usmewe.com/v1/webhooks" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "url": "https://yourapp.com/webhooks/usmewe",
      "events": ["loan.funded", "loan.repaid", "loan.overdue"],
      "secret": "your_webhook_secret"
    }'
  ```

  ```json Response theme={null}
  {
    "success": true,
    "data": {
      "id": "wh_abc123",
      "url": "https://yourapp.com/webhooks/usmewe",
      "events": ["loan.funded", "loan.repaid", "loan.overdue"],
      "status": "active",
      "createdAt": "2024-01-15T12:00:00Z"
    }
  }
  ```
</CodeGroup>

### Parameters

| Parameter | Type   | Required | Description                    |
| --------- | ------ | -------- | ------------------------------ |
| `url`     | string | Yes      | HTTPS endpoint URL             |
| `events`  | array  | Yes      | Events to subscribe to         |
| `secret`  | string | Yes      | Shared secret for verification |

## List Webhooks

Get all registered webhooks.

<CodeGroup>
  ```bash Request theme={null}
  curl -X GET "https://api.usmewe.com/v1/webhooks" \
    -H "Authorization: Bearer YOUR_TOKEN"
  ```

  ```json Response theme={null}
  {
    "success": true,
    "data": [
      {
        "id": "wh_abc123",
        "url": "https://yourapp.com/webhooks/usmewe",
        "events": ["loan.funded", "loan.repaid"],
        "status": "active",
        "lastDelivery": {
          "timestamp": "2024-01-15T10:00:00Z",
          "status": "success"
        }
      }
    ]
  }
  ```
</CodeGroup>

## Update Webhook

Update webhook configuration.

<CodeGroup>
  ```bash Request theme={null}
  curl -X PATCH "https://api.usmewe.com/v1/webhooks/{webhookId}" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "events": ["loan.funded", "loan.repaid", "vault.deposit"],
      "status": "active"
    }'
  ```

  ```json Response theme={null}
  {
    "success": true,
    "data": {
      "id": "wh_abc123",
      "url": "https://yourapp.com/webhooks/usmewe",
      "events": ["loan.funded", "loan.repaid", "vault.deposit"],
      "status": "active"
    }
  }
  ```
</CodeGroup>

## Delete Webhook

Remove a webhook.

<CodeGroup>
  ```bash Request theme={null}
  curl -X DELETE "https://api.usmewe.com/v1/webhooks/{webhookId}" \
    -H "Authorization: Bearer YOUR_TOKEN"
  ```

  ```json Response theme={null}
  {
    "success": true,
    "message": "Webhook deleted"
  }
  ```
</CodeGroup>

## Webhook Payload

All webhooks receive payloads in this format:

```json theme={null}
{
  "id": "evt_xyz789",
  "event": "loan.funded",
  "timestamp": "2024-01-15T12:00:00Z",
  "data": {
    "loanId": "loan_abc123",
    "userId": "user_def456",
    "amount": "50.00"
  }
}
```

## Verifying Webhooks

Verify webhook authenticity using the signature header:

```typescript theme={null}
import crypto from 'crypto';

function verifyWebhook(payload: string, signature: string, secret: string): boolean {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}

// In your webhook handler
app.post('/webhooks/usmewe', (req, res) => {
  const signature = req.headers['x-usmewe-signature'];
  const payload = JSON.stringify(req.body);

  if (!verifyWebhook(payload, signature, WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  // Process webhook
  const { event, data } = req.body;
  // ...

  res.status(200).send('OK');
});
```

## Available Events

### Loan Events

| Event                  | Description              |
| ---------------------- | ------------------------ |
| `loan.created`         | Loan request created     |
| `loan.funded`          | Loan has been funded     |
| `loan.repaid`          | Loan fully repaid        |
| `loan.partial_payment` | Partial payment received |
| `loan.overdue`         | Loan is overdue          |
| `loan.defaulted`       | Loan marked as default   |

### Vault Events

| Event                     | Description                 |
| ------------------------- | --------------------------- |
| `vault.deposit`           | USDC deposited              |
| `vault.withdraw`          | USDC withdrawn              |
| `vault.yield_distributed` | Yield distribution occurred |

### Social Vault Events

| Event                               | Description                |
| ----------------------------------- | -------------------------- |
| `social_vault.withdrawal_requested` | Large withdrawal requested |
| `social_vault.withdrawal_approved`  | Withdrawal approved        |
| `social_vault.withdrawal_executed`  | Withdrawal completed       |
| `social_vault.locked`               | Vault locked (duress)      |

### User Events

| Event                      | Description                   |
| -------------------------- | ----------------------------- |
| `user.trust_score_updated` | Trust Score changed           |
| `user.level_up`            | User leveled up               |
| `user.guardian_added`      | Guardian relationship created |

## Retry Policy

Failed webhook deliveries are retried:

| Attempt | Delay      |
| ------- | ---------- |
| 1       | Immediate  |
| 2       | 1 minute   |
| 3       | 5 minutes  |
| 4       | 30 minutes |
| 5       | 2 hours    |
| 6       | 24 hours   |

After 6 failed attempts, the webhook is marked as `failing`.

## Get Delivery History

View webhook delivery attempts.

<CodeGroup>
  ```bash Request theme={null}
  curl -X GET "https://api.usmewe.com/v1/webhooks/{webhookId}/deliveries?limit=10" \
    -H "Authorization: Bearer YOUR_TOKEN"
  ```

  ```json Response theme={null}
  {
    "success": true,
    "data": [
      {
        "id": "del_1",
        "event": "loan.funded",
        "status": "success",
        "statusCode": 200,
        "timestamp": "2024-01-15T10:00:00Z",
        "duration": 150
      },
      {
        "id": "del_2",
        "event": "loan.repaid",
        "status": "failed",
        "statusCode": 500,
        "timestamp": "2024-01-15T09:00:00Z",
        "duration": 5000,
        "error": "Timeout"
      }
    ]
  }
  ```
</CodeGroup>

## Test Webhook

Send a test event to your webhook.

<CodeGroup>
  ```bash Request theme={null}
  curl -X POST "https://api.usmewe.com/v1/webhooks/{webhookId}/test" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "event": "loan.funded"
    }'
  ```

  ```json Response theme={null}
  {
    "success": true,
    "data": {
      "delivered": true,
      "statusCode": 200,
      "duration": 120
    }
  }
  ```
</CodeGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Respond quickly" icon="bolt">
    Return 200 OK within 5 seconds. Process asynchronously if needed.
  </Accordion>

  <Accordion title="Handle duplicates" icon="copy">
    Use the `id` field to deduplicate. We may retry successful deliveries.
  </Accordion>

  <Accordion title="Verify signatures" icon="shield">
    Always verify the `x-usmewe-signature` header.
  </Accordion>

  <Accordion title="Use HTTPS" icon="lock">
    Webhook URLs must use HTTPS with valid certificates.
  </Accordion>
</AccordionGroup>

## Error Responses

| Code | Error               | Description            |
| ---- | ------------------- | ---------------------- |
| 400  | `INVALID_URL`       | URL is not valid HTTPS |
| 400  | `INVALID_EVENTS`    | Unknown event types    |
| 404  | `WEBHOOK_NOT_FOUND` | Webhook doesn't exist  |
| 409  | `URL_EXISTS`        | URL already registered |
