# Getting started

This guide explains how to integrate external systems with SX Digital Pay to generate **single-use** payment links and track their lifecycle through API calls and webhooks. The external system creates a link, redirects the customer, and checks the link details (or webhook) to know whether a payment was completed.

## Environments
| Environment | Base URL | Authentication / API Key Source |
|-------------|----------|----------------------------------|
| Production | `https://app.sxdigitalpay.com/api/v1` | Requires API key provided in `Integration` menu on Merchant's Dashboard. |
| Sandbox | `https://sandbox.sxdigitalpay.com/api/v1` | Requires the shared sandbox API key provided in [Authentication](https://developers.sxdigitalpay.com/authentication-1821094m0.md). |

Sandbox limitations:
- `GET /payment-links` is **disabled** in sandbox and returns `403`.
- You can create payment links in [Create single-use payment link](https://developers.sxdigitalpay.com/create-single-use-payment-link-25254364e0.md) and open the quote page (fields `paymentLink.url` or `paymentLink.shortUrl` on response) to simulate payments.
- Webhooks are not dispatched automatically in sandbox; use the Sandbox panel on the quote page to simulate events and review responses.

## Authentication
Send either header `x-api-key: <api-key>` or `Authorization: Bearer <api-key>`. See [Authentication](https://developers.sxdigitalpay.com/authentication-1821094m0.md) for full details.

## Rate limiting
- 60 requests per minute per API key.
- Responses include `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and return `429` + `Retry-After` when the limit is exceeded.

## Core Flow
1) **Create a payment link**
   - `POST /payment-links`
   - Required fields: `title`, `amount` (> 25).
   - Optional but recommended: `externalReference` (idempotency per merchant), `expiresAt`, `metadata` (JSON object), `webhookUrl`, `webhookSecret` (otherwise generated and returned only once), `callbackUrl` (redirect after successful payment).
2) **Redirect the customer to the link**
   - Use `url` or `shortUrl` from the response. The checkout and payment capture happen on SX Digital Pay.
   - If you set `callbackUrl`, the checkout automatically redirects the customer to that URL after the payment is completed.
3) **Track the link and payments**
   - Read `paymentStatus` (NOT_STARTED, PENDING, COMPLETED) and `payments[]` from `GET /payment-links/{id}`.
   - Or subscribe to the webhook `payment_link.payment_status_changed` to be notified when the link's paymentStatus changes.

Sandbox note: you can create links and open the quote page (fields `paymentLink.url` or `paymentLink.shortUrl` on [Create single-use payment link](https://developers.sxdigitalpay.com/create-single-use-payment-link-25254364e0.md) response). Use the Sandbox panel to simulate link status and payment status changes.

## Key Endpoints
- **Create link**: `POST /payment-links`
- **List links**: `GET /payment-links` (filters: `status`, `externalReference`, pagination) **Production only**
- **Get link details (payments + paymentStatus)**: `GET /payment-links/{id}`

Payments are embedded in the link details response; there is no separate payments endpoint.

## Link Status and Behavior
- `ACTIVE`: link is usable; `isActive` is true while not expired.
- `INACTIVE`: disabled by the platform or business logic.
- `EXPIRED`: past `expiresAt` or otherwise expired.
- Links are **single-use** (`isMultiUse` always false). After a payment is completed, expect the link to become inactive and receive a webhook if configured.
- `paymentStatus` (aggregated by link):
  - `NOT_STARTED`: no payments exist for the link.
  - `PENDING`: at least one payment exists but none completed.
  - `COMPLETED`: the payment has been completed; the payment balance has already been added to the merchant's account.

## Webhooks
Configure `webhookUrl` when creating the link to receive events:
- `payment_link.created`
- `payment_link.status_changed`
- `payment_link.payment_status_changed`

`payment_link.payment_status_changed` is the simplest way to know when a link starts receiving payments (NOT_STARTED -> PENDING) and when a payment is completed (PENDING -> COMPLETED). The payload also includes the latest payment summary and counts.

Headers:
- `x-sxpay-signature`: HMAC-SHA256 of `"{timestamp}.{rawBody}"` using the link's `webhookSecret`.
- `x-sxpay-timestamp`: Epoch milliseconds.

Verify the signature before processing. If verification fails, reject the webhook.

### Automatic Retries
SX Digital Pay automatically retries failed webhook deliveries with exponential backoff (1min, 5min, 15min, 1h, 4h, 12h). Return a `2xx` status to acknowledge successful receipt. For complete details, see [Webhook Delivery System](https://developers.sxdigitalpay.com/webhook-delivery-system-1955363m0.md).

Sandbox note: use the Sandbox panel on the quote page to simulate webhook events and inspect the webhook responses. Logs are stored in the browser (localStorage) for your session.

## Typical Integration Steps (Example)
1) Create link:
   ```http
   POST /payment-links
   Content-Type: application/json
   x-api-key: <api-key>

   {
     "title": "Order #9123",
     "amount": 129.90,
     "externalReference": "order-9123",
     "metadata": { "customerId": "cst_42" },
     "webhookUrl": "https://merchant.com/webhooks/sxpay",
     "callbackUrl": "https://merchant.com/orders/9123/paid"
   }
   ```
2) Redirect customer to the returned `url` (or `shortUrl`).
3) Receive webhook `payment_link.payment_status_changed` with `paymentStatus: COMPLETED` (and `latestPayment`) or poll `GET /payment-links/{id}` to reconcile.
4) When you receive a completed payment, mark the order as paid in your system.

## Polling vs. Webhooks
- Prefer **webhooks** for near real-time updates.
- Use **polling** as a backup (e.g., on webhook failures or for periodic reconciliation) against `GET /payment-links/{id}` to read `paymentStatus` and `payments[]`.

## Errors and Responses
- `401` Missing/invalid API key.
- `403` Merchant inactive or sandbox-only restriction (e.g., list endpoint or payment continuation in sandbox).
- `404` Resource not found (link or payment).
- `400` Validation issues (title, amount, dates, webhookUrl).
- `409` `externalReference` already exists for the merchant.

## Data Models (high level)
- **PaymentLink**: `id`, `title`, `amount`, `currency`, `status`, `paymentStatus`, `isMultiUse:false`, `isActive`, `isExpired`, `expiresAt`, `url`, `shortUrl`, `metadata`, optional `callbackUrl`, optional `webhookUrl`, optional `webhookSecret` (only at creation).
- **Payments embedded in link details**: `paymentsSummary` (counts by status) plus `payments[]` with `id`, `status`, timestamps, optional `customer`, optional `quote` (amount, currency, paymentMethod, installments, totalBRL).
- **Payment status (per payment)**: `PENDING | COMPLETED | DISPUTED | REFUNDED`.

## Recommendations
- Use `externalReference` for idempotency and reconciliation on your side.
- Store the `webhookSecret` securely; it is only returned at creation time.
- Validate HMAC signatures and check `x-sxpay-timestamp` freshness to prevent replay attacks.
- Implement idempotency on your webhook endpoint using the event `id` field, as SX Digital Pay may deliver the same event multiple times during retries.
- Return `2xx` responses quickly (< 20 seconds) to acknowledge receipt; process payloads asynchronously if needed.

## Support
If you have any questions, concerns, or wish to report a bug, please do not hesitate to contact us: `developers@sxdigitalpay.com`.
