# Generación de Access Token

### Autenticación

Antes de usar los endpoints de la API de Blerify, necesitas autenticarte usando un access token. Este token se obtiene de una Service Account creada previamente en el portal de Blerify.

### Creación de una Service Account

Para acceder a la API de Blerify, necesitas crear una Service Account. Sigue estos pasos:

1. **Accede al portal de Blerify:** Inicia sesión en el portal de Blerify con tus credenciales.

{% embed url="<https://portal.blerify.com/>" %}

<figure><picture><source srcset="/files/bcfd560ebbbf602894f4b7407007a4f384c54025" media="(prefers-color-scheme: dark)"><img src="/files/8e6e62ca17df214adde8ab531bb422210f4e88cd" alt=""></picture><figcaption></figcaption></figure>

1. **Ve a la sección "Service Accounts":** Ubica y selecciona la sección "Service Accounts" en el menú del portal.<br>

   <figure><picture><source srcset="/files/b3b19f6f0d2e19d8816501e649ddda273570009c" media="(prefers-color-scheme: dark)"><img src="/files/c1eb807240533825dac87b608563c1ffebe88584" alt=""></picture><figcaption></figcaption></figure>
2. **Crea una nueva Service Account:** Haz clic en el botón "Create Service Account".

   <figure><picture><source srcset="/files/b7229fd22d441d63e56e4e849befc653d06e8746" media="(prefers-color-scheme: dark)"><img src="/files/cb6891c7aea11d8fa185f627ba3a2ef2aef40a3d" alt=""></picture><figcaption></figcaption></figure>
3. **Completa la información de la Service Account:**
   * Ingresa un nombre descriptivo para identificar la cuenta (por ejemplo, "Payments Application", "CRM Integration").
   * Puedes agregar una descripción para detallar el uso de esta cuenta.
   * Selecciona el tipo de algoritmo de cifrado.
   * Selecciona uno o más roles que otorgarán permisos al Access Token que se generará.
4. **Finaliza y descarga el archivo JSON:** Blerify generará un archivo JSON con la información necesaria para generar el access token. **Guarda este archivo en un lugar seguro y no lo compartas con nadie.**<br>
5. **Formato de archivo:** JSON

{% code fullWidth="false" %}

```json
{
  "type": "service_account",
  "organization_id": "ID",
  "private_key_id": "ID",
  "client_email": "EMAIL",
  "client_id": "CLIENT_ID",
  "token_uri": "TOKEN_URL",
  "auth_provider_x509_cert_url": "X509_CERTIFICATE_URL",
  "iam_audience": "IAM_AUDIENCE",
  "universe_domain": "blerify.com",
  "private_key": "-----BEGIN PRIVATE KEY-----PRIVATE_KEY_PEM_FORMAT-----END PRIVATE KEY-----"
}

```

{% endcode %}

<figure><picture><source srcset="/files/85816db6d6a196871829e9222626b9a61763f20c" media="(prefers-color-scheme: dark)"><img src="/files/fcdaa7f4cf28c91d60fe4267a9efff464f276486" alt=""></picture><figcaption></figcaption></figure>

### Generación del Access Token

Una vez que hayas creado la Service Account y descargado el archivo JSON, puedes generar el access token usando tu lenguaje de programación preferido. Aquí tienes un ejemplo con una biblioteca cliente de Blerify desarrollada en PHP.

**Código de ejemplo (PHP):**

```php
<?php

namespace Blerify\Authentication;

use Exception;
use Firebase\JWT\JWT;
use Ramsey\Uuid\Uuid;

class JwtHandler
{
    private $clientId;
    private $privateKey;
    private $organizationId;
    private $tokenUri;

    private $cachedJwt;
    private $cachedExpiration;

    private $audience;

    public function __construct($clientId,$organizationId, $privateKey, $tokenUri, $audience)
    {
        $this->clientId = $clientId;
        $this->organizationId = $organizationId;
        $this->privateKey = $privateKey;
        $this->tokenUri = $tokenUri;
        $this->cachedJwt = null;
        $this->cachedExpiration = null;
        $this->audience = $audience;
    }

    public function createJwt($audience)
    {
        $now = time();
        $payload = [
            'iss' => $this->clientId,
            'sub' => $this->clientId,
            'aud' => $audience,
            'iat' => $now,
            'exp' => $now + 3600,
            'jti' => Uuid::uuid4()->toString(),
        ];

        return JWT::encode($payload, $this->privateKey, 'RS256');
    }

    public function getAccessToken()
    {
        if ($this->cachedJwt && $this->cachedExpiration > (time() + 60)) {
            return $this->cachedJwt;
        }
        $jwt = $this->createJwt($this->audience);

        $ch = curl_init($this->tokenUri);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'client_id' => $this->clientId,
            'organization_id' => $this->organizationId,
            'client_assertion' => $jwt,
        ]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
        ]);
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($statusCode !== 200) {
            throw new Exception("Failed to get access token. Status code: $statusCode");
        }
        $tokenResponse = json_decode($response, true);
        if (!isset($tokenResponse['access_token'])) {
            throw new Exception("Access token not found in response.");
        }
         // Cache the JWT and its expiration time
         $this->cachedJwt = $tokenResponse['access_token'];
         $this->cachedExpiration = $this->getJwtExp($jwt);

         return $this->cachedJwt;
    }

    public function getJwtExp($jwt) {
        $parts = explode(".", $jwt);

        if (count($parts) !== 3) {
            throw new Exception("Invalid JWT format");
        }

        $payload = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[1])), true);

        $exp = (int) $payload['exp'];
        if (!isset($exp)) {
            throw new Exception("Invalid JWT: 'exp' not valid");
        }

        return $exp;
    }
}
?>
```

\
**Respuesta (ejemplo de access token generado):**

```json
{
  "access_token": "…",
  "expires_in": 3600,
  "refresh_expires_in": 0,
  "refresh_token": "…",
  "token_type": "Bearer",
  "not-before-policy": 0,
  "session_state": "…",
  "scope": "offline_access email profile"
}
```

* **access\_token:** El access token generado.
* **expires\_in:** Tiempo de vida en segundos del access token. En este ejemplo, 3600 segundos (1 hora).
* **refresh\_token:** Un token que se puede usar para obtener un nuevo access token sin volver a autenticar al usuario.

**Importante:** El access token tiene un tiempo de vida limitado, especificado en el `expires_in` parámetro.

### **Recomendaciones:**

* **Verifica la expiración:** Antes de usar el access token, el desarrollador debe verificar si ya expiró. Para hacerlo, puede comparar la marca de tiempo actual con la suma de la marca de tiempo de generación del token y el `expires_in` valor.
* **Genera un nuevo token:** Si el access token ha expirado, el desarrollador debe generar uno nuevo usando la biblioteca cliente de Blerify.
* **Almacena el token de forma segura:** El access token debe almacenarse de forma segura para evitar su uso no autorizado.

### Uso del Access Token

Una vez que hayas obtenido el access token, puedes usarlo para acceder a los endpoints de la API de Blerify. Para hacerlo, debes incluir el access token en el `Authorization` encabezado de la request HTTP, usando el `Bearer` esquema.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.blerify.com/es/desarrolladores/api-documentation/access-token-generation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
