# Access Token Generation

### Authentication

Before using the Blerify API endpoints, you need to authenticate using an access token. This token is obtained from a Service Account previously created in the Blerify portal.

### Creating a Service Account

To access the Blerify API, you need to create a Service Account. Follow these steps:

1. **Access the Blerify portal:** Log in to the Blerify portal using your credentials.

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

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

1. **Navigate to the "Service Accounts" section:** Locate and select the "Service Accounts" section in the portal menu.<br>

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

2. **Create a new Service Account:** Click the "Create Service Account" button.

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

3. **Complete the Service Account information:**

   * Enter a descriptive name to identify the account (e.g., "Payments Application", "CRM Integration").
   * You can add a description to detail the use of this account.
   * Select the type of encryption algorithm.
   * Select one or more roles that will grant permissions to the Access Token that will be generated.

4. **Finish and Download the JSON file:** Blerify will generate a JSON file containing the information needed to generate the access token. **Store this file in a secure location and do not share it with anyone.**<br>

5. **File format:** 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/kowjnVfIS63x9a3lVXZN" media="(prefers-color-scheme: dark)"><img src="/files/jOAAPXlKftZ4CONpwkKP" alt=""></picture><figcaption></figcaption></figure>

### Generating the Access Token

Once you have created the Service Account and downloaded the JSON file, you can generate the access token using your preferred programming language. Here is an example with a Blerify client library developed in PHP.

**Example code (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;
    }
}
?>
```

\
**Response (Example of Generated Access Token):**

```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:** The generated access token.
* **expires\_in:** Lifetime in seconds of the access token. In this example, 3600 seconds (1 hour).
* **refresh\_token:** A token that can be used to obtain a new access token without re-authenticating the user.

**Important:** The access token has a limited lifetime, specified in the `expires_in` parameter.

### **Recommendations:**

* **Check expiration:** Before using the access token, the developer should check if it has expired. To do this, they can compare the current timestamp with the sum of the token generation timestamp and the `expires_in` value.
* **Generate a new token:** If the access token has expired, the developer must generate a new one using the Blerify client library.
* **Store the token securely:** The access token should be stored securely to prevent unauthorized use.

### Using the Access Token

Once you have obtained the access token, you can use it to access the Blerify API endpoints. To do this, you must include the access token in the `Authorization` header of the HTTP request, using the `Bearer` scheme.


---

# Agent Instructions: 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/developers/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.
