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

# Autenticacion

> Como autenticar llamadas a la API publica de SimplePay con bearer keys, scopes, tenant context y practicas seguras.

La API publica de SimplePay usa bearer API keys:

```http request theme={"theme":{"light":"github-light","dark":"github-dark"}}
Authorization: Bearer spk_sandbox_...
```

Las API keys pertenecen a un tenant y a un ambiente. SimplePay valida la key, resuelve el tenant y aplica scopes antes de ejecutar la solicitud.

<Danger>
  Usa solo la API publica documentada y no pongas API keys en frontend, repos,
  screenshots, logs o artefactos de evidencia.
</Danger>

## Ambientes

| Ambiente | Key               | Uso                                                                    |
| -------- | ----------------- | ---------------------------------------------------------------------- |
| Sandbox  | `spk_sandbox_...` | Desarrollo, QA, pruebas de webhooks y datos no reales.                 |
| Live     | `spk_live_...`    | Pagos reales despues de aprobacion, policy gates y webhooks validados. |

## Scopes

Algunos endpoints declaran scopes en la especificacion OpenAPI con `x-simplepay-required-scopes`.

| Scope                              | Permite                                                                                                                |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `products:read`                    | Leer productos, configuracion Bookable y preflight.                                                                    |
| `products:write`                   | Crear o actualizar productos y bundles.                                                                                |
| `catalog:read`                     | Leer catalogo publico CMS.                                                                                             |
| `customer_hub:read`                | Leer customers, timeline, imports y sync sources del Customer Hub.                                                     |
| `customer_hub:write`               | Crear o actualizar customers, addresses, relationships, external refs, links, imports y sync sources del Customer Hub. |
| `customer_hub.contacts:write`      | Agregar o actualizar contactos del Customer Hub.                                                                       |
| `customer_hub.notes:write`         | Agregar notas del Customer Hub.                                                                                        |
| `customer_hub.segments:read`       | Leer tags del Customer Hub.                                                                                            |
| `customer_hub.segments:write`      | Crear tags del Customer Hub.                                                                                           |
| `customer_hub.provider_sync:write` | Disparar la proyeccion al provider del Customer Hub.                                                                   |
| `availability:read`                | Leer slots, recursos, schedules y disponibilidad.                                                                      |
| `availability:write`               | Crear o modificar recursos, schedules, rules, overrides y event types.                                                 |
| `bookings:read`                    | Leer bookings.                                                                                                         |
| `bookings:write`                   | Crear holds, checkouts, cancelaciones, refunds y reschedules.                                                          |
| `webhooks:read`                    | Leer endpoints webhook.                                                                                                |
| `webhooks:write`                   | Crear, borrar y reintentar webhooks.                                                                                   |
| `policies:read`                    | Leer y evaluar politica efectiva de pagos.                                                                             |

<Info>
  Hosted Checkout, Payment Links, Bookable Payments y Refunds tambien pasan por
  autenticacion bearer y por politica interna de tenant, aunque algunas rutas no
  expongan un scope explicito en la spec.
</Info>

## Headers recomendados

```http request theme={"theme":{"light":"github-light","dark":"github-dark"}}
Authorization: Bearer spk_sandbox_...
Content-Type: application/json
Idempotency-Key: order_1001_checkout_v1
```

Usa `Idempotency-Key` para cualquier operacion que crea o muta estado.

## Manejo de secrets

<Steps>
  <Step title="Guarda keys en tu secret manager">
    Usa variables de entorno o el secret manager de tu plataforma. No las
    serialices en config publica.
  </Step>

  <Step title="Usa una key por ambiente">
    Mantener sandbox y live separados reduce accidentes y hace mas simple
    revocar acceso.
  </Step>

  <Step title="Aplica minimo privilegio">
    Para un integration test de Bookable no necesitas scopes de catalogo si solo
    creas holds y bookings.
  </Step>

  <Step title="Rota ante sospecha">
    Si una key aparece en logs o chat, revocala y emite una nueva.
  </Step>
</Steps>

## Ejemplo de backend

```ts server.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
export async function createCheckoutSession(order: {
  id: string;
  amount: number;
  email: string;
}) {
  const response = await fetch("https://api.simplepay.mx/v1/hosted-checkout/sessions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.SIMPLEPAY_API_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": `${order.id}_checkout_v1`,
    },
    body: JSON.stringify({
      currency: "mxn",
      customer_email: order.email,
      success_url: `https://example.com/orders/${order.id}/success`,
      cancel_url: `https://example.com/orders/${order.id}`,
      client_reference_id: order.id,
      line_items: [{ name: "Orden", amount: order.amount, quantity: 1 }],
      metadata: { order_id: order.id },
    }),
  });

  if (!response.ok) {
    throw new Error(await response.text());
  }

  return response.json();
}
```
