# Gerando um token de aplicação

O token de aplicação serve para acessos a API para integração com organizações, do qual é necessário para criar um [fluxo utilizando no página para montar o documento usando templates](/exemplos/criar-fluxo-com-a-pagina-de-integracao.md). Para isso, as credenciais utilizadas para gerar este token devem ser uma conta do tipo PJ.

## Verificando se a conta é PJ

Para saber se sua conta é PJ usando os endpoints da API, podemos fazer da seguinte maneira:

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET \
    -H "Authorization: Bearer 41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4" \
    "https://api-v1.assine.online/v1/user?filter[0][field]=id&filter[0][type]=eq&filter[0][value]=\$USER_ID"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

const params = 'filter[0][field]=id&filter[0][type]=eq&filter[0][value]=$USER_ID';

const response = await fetch(`https://api.assine.online/v1/user?${params}`, {
  method: 'GET',
  headers: {
    Authorization: `Bearer ${token}`
  }
});

const data = await response.json();
```

{% endtab %}

{% tab title="PHP" %}

```php
$token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

$query = [
    'filter[0][field]' => 'id',
    'filter[0][type]' => 'eq',
    'filter[0][value]' => '$USER_ID'
];

$client = new GuzzleHttp\Client();

$res = $client->request('GET', 'https://api.assine.online/v1/user', [
    'headers' => [
        'Authorization' => 'Bearer ' . $token
    ],
    'query' => $query
]);

echo $res->getBody();
```

{% endtab %}
{% endtabs %}

[`GET https://api.assine.online/v1/user`](/api/api/usuario.md#buscar-dados-do-usuario-logado)

Não altere o `$USER_ID` da url, este converte internamente para o id do usuário correspondente ao token de acesso informado no header `Authorization` .

Resposta:

```javascript
{
    "_links": {
        "self": {
            "href": "https://api-v1.assine.online/v1/user?filter%5B0%5D%5Bfield%5D=id&filter%5B0%5D%5Btype%5D=eq&filter%5B0%5D%5Bvalue%5D=$USER_ID&page=1"
        },
        "first": {
            "href": "https://api-v1.assine.online/v1/user?filter%5B0%5D%5Bfield%5D=id&filter%5B0%5D%5Btype%5D=eq&filter%5B0%5D%5Bvalue%5D=$USER_ID"
        },
        "last": {
            "href": "https://api-v1.assine.online/v1/user?filter%5B0%5D%5Bfield%5D=id&filter%5B0%5D%5Btype%5D=eq&filter%5B0%5D%5Bvalue%5D=$USER_ID&page=1"
        }
    },
    "_embedded": {
        "user": [
            {
                "id": 474,
                "username": "siletic225@xhyemail.com",
                "status": "1",
                "name": "Jhon Doe",
                "email": "siletic225@xhyemail.com",
                "cellphone": "+5562991838359",
                "document": "12312312312",
                "country": "Brazil",
                "state": "GO",
                "city": "Goiânia",
                "address": "Av 136, Ed. New York Square 19/20",
                "zipCode": "74000000",
                "dateCreated": {
                    "date": "2020-02-20 13:28:28.000000",
                    "timezone_type": 3,
                    "timezone": "UTC"
                },
                "dateLastUpdated": {
                    "date": "2020-02-20 13:29:10.000000",
                    "timezone_type": 3,
                    "timezone": "UTC"
                },
                "_embedded": {
                    "businessUnit": {
                        "id": 24,
                        "name": "Soluti Soluções em negocios inteligentes",
                        "document": "cnpj",
                        "status": null,
                        "country": "Brazil",
                        "state": "GO",
                        "city": "Goiânia",
                        "address": "Av 136, Ed. New York Square 19/20",
                        "zipCode": "74000000",
                        "_links": {
                            "self": {
                                "href": "https://api-v1.assine.online/v1/business-unit/24"
                            }
                        }
                    }
                },
                "_links": {
                    "self": {
                        "href": "https://api-v1.assine.online/v1/user/474"
                    }
                }
            }
        ]
    },
    "page_count": 1,
    "page_size": 25,
    "total_items": 1,
    "page": 1
}
```

{% hint style="warning" %}
Caso exista configurações da sua organização na chave `businessUnit` então esta conta está habilitada para gerar tokens de aplicação.
{% endhint %}

## Gerando token de aplicação

Para gerar o token de aplicação, é necessário informar a senha da conta para validar a requisição, bem como uma data de validade para este token, lembrando que é de suma importância que manipule este token de forma segura para que não corra o risco de pessoas não autorizadas terem acesso a ele. Caso tenha suspeitas de que o token possa ter sido comprometido, [revogue-o](/exemplos/gerando-um-token-de-aplicacao.md#revogando-tokens-de-aplicacao). Para gerar o token:

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST \
    -H "Authorization: Bearer 41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4" \
    -H "Content-Type: application/json" \
    https://api-v1.assine.online/v1/access-token -d '
{
    "password": "INFORME_SENHA",
    "expires": "2021-01-01 23:59:00"
}
'
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

const body = {
  password: 'INFORME_SENHA',
  expires: '2021-01-01 23:59:00' 
};

const response = await fetch('https://api.assine.online/v1/access-token', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${token}`
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(body)
});

const data = await response.json();
```

{% endtab %}

{% tab title="PHP" %}

```php
$token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

$client = new GuzzleHttp\Client();

$res = $client->request('POST', 'https://api.assine.online/v1/access-token', [
    'headers' => [
        'Authorization' => 'Bearer ' . $token
    ],
    'json' => [
        'password' => 'INFORME_SENHA',
        'expires' => '2021-01-01 23:59:00'
    ]
]);

echo $res->getBody();
```

{% endtab %}
{% endtabs %}

[`POST https://api-v1.assine.online/v1/access-token` ](/api/api/autenticacao.md#criar-token-de-sessao)

Resposta:

```javascript
{
    "accessToken": "5499d5cac5d19926adcbcda7987c01854065554f",
    "expires": {
        "date": "2021-01-01 23:59:00.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
    "id": "5347?q=verify&sessionIndex=a18443cb74060f334d1530c01fa21f12c92b19e5",
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Token created",
    "status": 201,
    "detail": "Access Token data"
}
```

Guarde este token pois este é o único momento que ele será exibido, caso perca este token, é necessário que gere outro.

## Listando token de aplicação

Para listar token de aplicação gerados:

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET \
    -H "Authorization: Bearer 41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4" \
    https://api-v1.assine.online/v1/access-token
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

const response = await fetch('https://api.assine.online/v1/access-token', {
  method: 'GET',
  headers: {
    Authorization: `Bearer ${token}`
  }
});

const data = await response.json();
```

{% endtab %}

{% tab title="PHP" %}

```php
$token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

$client = new GuzzleHttp\Client();

$res = $client->request('GET', 'https://api.assine.online/v1/access-token', [
    'headers' => [
        'Authorization' => 'Bearer ' . $token
    ]
]);

echo $res->getBody();
```

{% endtab %}
{% endtabs %}

[`GET https://api-v1.assine.online/v1/access-token` ](/api/api/autenticacao.md#listar-tokens-de-acesso)

Resposta:

```javascript
{
    "_links": {
        "self": {
            "href": "https://api-v1.assine.online/access-token?page=1"
        },
        "first": {
            "href": "https://api-v1.assine.online/access-token"
        },
        "last": {
            "href": "https://api-v1.assine.online/access-token?page=1"
        }
    },
    "_embedded": {
        "access_token": [
            {
                "accessToken": "***** HIDDEN *****",
                "expires": {
                    "date": "2020-02-21 13:29:31.000000",
                    "timezone_type": 3,
                    "timezone": "UTC"
                },
                "id": "5320",
                "scope": {},
                "_embedded": {
                    "user": {
                        "id": 474,
                        "name": "Jhon Doe",
                        "username": "siletic225@xhyemail.com",
                        "email": "siletic225@xhyemail.com",
                        "_links": {
                            "self": {
                                "href": "https://api-v1.assine.online/user/474"
                            }
                        }
                    }
                },
                "_links": {
                    "self": {
                        "href": "https://api-v1.assine.online/access-token/5320"
                    }
                }
            },
            
            {
                "accessToken": "***** HIDDEN *****",
                "expires": {
                    "date": "2021-01-01 23:59:00.000000",
                    "timezone_type": 3,
                    "timezone": "UTC"
                },
                "id": "5347",
                "scope": {},
                "_embedded": {
                    "user": {
                        "id": 474,
                        "name": "Jhon Doe",
                        "username": "siletic225@xhyemail.com",
                        "email": "siletic225@xhyemail.com",
                        "_links": {
                            "self": {
                                "href": "https://api-v1.assine.online/user/474"
                            }
                        }
                    }
                },
                "_links": {
                    "self": {
                        "href": "https://api-v1.assine.online/access-token/5347"
                    }
                }
            }
        ]
    },
    "page_count": 1,
    "page_size": 25,
    "total_items": 3,
    "page": 1
}
```

Veja que o primeiro token corresponde ao nosso próprio token de sessão do qual foi gerado quando fizemos login, e o segundo é o token de aplicação que pedimos para ser gerado.

## Revogando tokens de aplicação

Para revogar um token de aplicação, pegue o `id` do token do qual é exibido ao fazer a listagem dos tokens e execute:

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X DELETE \
    -H "Authorization: Bearer 41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4" \
    https://api-v1.assine.online/v1/access-token/5347
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

const tokenId = 5347;

const response = await fetch(`https://api.assine.online/v1/access-token/${tokenId}`, {
  method: 'DELETE',
  headers: {
    Authorization: `Bearer ${token}`
  }
});

const data = await response.json();
```

{% endtab %}

{% tab title="PHP" %}

```php
$token = '41f7ff53c1dc5cf4f3db1f33e026b2908cdf88b4';

$tokenId = 5347;

$client = new GuzzleHttp\Client();

$res = $client->request('DELETE', 'https://api.assine.online/v1/access-token/' . $tokenId, [
    'headers' => [
        'Authorization' => 'Bearer ' . $token
    ]
]);

echo $res->getBody();
```

{% endtab %}
{% endtabs %}

[`DELETE https://api-v1.assine.online/v1/access-token/:id` ](/api/api/autenticacao.md#remover-token-de-sessao)

Deve ser retornado status `204` da requisição simbolizando que o token foi revogado.


---

# 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.assine.online/exemplos/gerando-um-token-de-aplicacao.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.
