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

# Autenticación

> Genera un Access Token para autenticar requests a la API de Pay-me.

Genera un **Access Token** usando tus credenciales `client_id` y `client_secret`.\
Todos los endpoints requieren este token para ser consumidos.

<ParamField path="POST /token" type="endpoint" />

<CardGroup cols={2}>
  <Card title="Pre-Producción" icon="flask">
    <code>[https://auth.preprod.alignet.io/token](https://auth.preprod.alignet.io/token)</code>
  </Card>

  <Card title="Producción" icon="rocket">
    <code>[https://auth.alignet.io/token](https://auth.alignet.io/token)</code>
  </Card>
</CardGroup>

<Note>
  Este endpoint sigue el flujo OAuth 2.0 `client_credentials`. Genera el token una vez y reutilízalo mientras siga vigente.
</Note>

***

## Scopes disponibles

Define los permisos asociados al token.

<CardGroup cols={2}>
  <Card title="create:token" icon="key">
    Obligatorio para generar tokens.
  </Card>

  <Card title="post:charges" icon="plus">
    Crear cargos y autorizaciones.
  </Card>

  <Card title="get:charges" icon="search">
    Consultar transacciones.
  </Card>

  <Card title="delete:charges" icon="trash">
    Cancelar transacciones.
  </Card>
</CardGroup>

***

## Request

### Headers

| Campo             | Descripción         | Valor              | Tipo   | Obligatorio |
| :---------------- | :------------------ | :----------------- | :----- | :---------- |
| `Content-Type`    | Formato del request | `application/json` | String | SI          |
| `ALG-API-VERSION` | Versión del API     | `1709847567`       | String | SI          |

```bash theme={"system"}
Content-Type: application/json
ALG-API-VERSION: 1709847567
```

***

### Body

| Campo           | Descripción               | Ejemplo                     | Tipo   | Obligatorio |
| :-------------- | :------------------------ | :-------------------------- | :----- | :---------- |
| `action`        | Acción a ejecutar         | `authorize`                 | String | SI          |
| `grant_type`    | Método de autorización    | `client_credentials`        | String | SI          |
| `audience`      | URL base del API          | `{{base_url}}`              | String | SI          |
| `client_id`     | Identificador del cliente | Credencial                  | String | SI          |
| `client_secret` | Secreto del cliente       | Credencial                  | String | SI          |
| `scope`         | Permisos solicitados      | `create:token post:charges` | String | SI          |

***

### Ejemplo (JSON)

```json theme={"system"}
{
  "action": "authorize",
  "grant_type": "client_credentials",
  "audience": "{{base_url_del_ambiente}}",
  "client_id": "your_client_id",
  "client_secret": "your_client_secret",
  "scope": "create:token post:charges get:charges delete:charges"
}
```

***

## Response

### Body

| Campo           | Descripción                     | Tipo    |
| :-------------- | :------------------------------ | :------ |
| `action`        | Acción ejecutada                | String  |
| `success`       | Resultado del proceso           | Boolean |
| `access_token`  | Token generado                  | String  |
| `scope`         | Permisos del token              | String  |
| `expires_in`    | Tiempo de expiración (segundos) | Integer |
| `token_type`    | Tipo de token (`Bearer`)        | String  |
| `authorization` | Metadata del flujo              | Object  |

***

### Ejemplo (JSON)

```json theme={"system"}
{
  "action": "authorize",
  "success": true,
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "scope": "create:token api-test:create:token",
  "expires_in": 8600,
  "token_type": "Bearer",
  "authorization": {
    "meta": {
      "status": {
        "code": "00",
        "message_ilgn": [
          {
            "locale": "es_PE",
            "value": "Access Token creado"
          }
        ]
      }
    }
  }
}
```

***

## Usar el token en requests

Incluye el token en el header `Authorization`:

```bash theme={"system"}
Authorization: Bearer {access_token}
Content-Type: application/json
ALG-API-VERSION: 1709847567
```

***

## Buenas prácticas

* Reutiliza el token mientras esté vigente.
* No generes un token por cada transacción.
* Renuévalo antes de su expiración.
* Centraliza su gestión en backend.
* Usa caché para optimizar rendimiento.
* Controla concurrencia para evitar múltiples generaciones simultáneas.

***

## Errores comunes

<CardGroup cols={2}>
  <Card title="401 Unauthorized" icon="triangle-exclamation">
    Token inválido, expirado o no enviado correctamente en el header.
  </Card>

  <Card title="403 Forbidden" icon="ban">
    El token no tiene los scopes necesarios para el endpoint.
  </Card>
</CardGroup>

<Warning>
  No expongas el Access Token en frontend, logs o herramientas sin enmascaramiento.
</Warning>

***

## Siguiente paso

<Card title="PayIn — Introducción" icon="arrow-right" href="/payin/introduccion">
  Aprende a crear tu primera transacción.
</Card>
