---
title: Създаване на разрешение за достъп
description: Дайте на купувач, сервиз или рециклатор достъп до ограничени данни от паспорта. Токенът pa_ се връща веднъж и не се съхранява. Органите остават в таблото.
canonical: "https://www.tracepass.eu/bg/docs/create-access-grant"
locale: bg
source: "https://www.tracepass.eu/bg/docs/create-access-grant"
---

# Създаване на разрешение за достъп

> Дайте на купувач, сервиз или рециклатор достъп до ограничени данни от паспорта. Токенът pa_ се връща веднъж и не се съхранява. Органите остават в таблото.

```http
POST /api/v1/access-grants
```

Дайте на получател достъп до ограничената част от паспортите си по същите правила като в таблото: ролята определя кои точки от данните показва разрешението, разрешението за купувач назовава паспортите, които покрива, и приключва при смяна на собственика на батерията, а компания има най-много 50 активни разрешения.

**Токенът `pa_` се връща веднъж, в този `201`, и повече никога.** Съхранява се само хеш. Предайте го веднага на получателя и не го записвайте в логове. Идемпотентно повторение (същият `Idempotency-Key`, същото тяло) връща разрешението без токена и с `tokenDelivered: true`, така че хранилището за идемпотентност никога не съдържа удостоверение. Ако токенът е изгубен, отнемете разрешението и създайте ново. Полето `notice` казва същото в отговора.

**Ролите на органи остават в таблото.** `market_surveillance`, `notified_body`, `commission` и `customs`, както и нивото `authority` при ролята `other`, връщат `400 role_dashboard_only`. Дневникът на достъпа записва кой API ключ или приложение е създало разрешението.

**Кой може да го извика.** API ключ само когато собственикът му е включил „May manage access grants“ за този ключ на страницата Developer (по подразбиране изключено; иначе `403 access_grants_not_enabled`). OAuth токен изисква scope `access_grants:write` и потребител admin или owner. Изисква платен акаунт. Брои се като едно v1 записване.

## Parameters

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `Authorization` | header | string | yes | `Bearer <token>` — или `tp_` API ключ (Developer → API Keys; най-просто, за server-to-server), или OAuth 2.0 access token (Developer → OAuth Apps; за приложения, авторизирани от потребител, scoped и отзоваеми). Страницата Authentication съдържа пълния OAuth поток и списъка със scopes. |
| `Idempotency-Key` | header | string | no | UUID v4. |
| `role` | body | string | yes | Ролята на получателя: `repairer`, `remanufacturer`, `repurposer`, `recycler`, `waste_treatment`, `training_centre`, `purchaser`, `purchaser_agent`, `elv_treatment`, `weee_treatment` или `other`. Четирите роли на органи се отхвърлят. |
| `label` | body | string (1-120 chars) | yes | За кого е разрешението, както искате да го виждате. |
| `scope` | body | object | no | `{ "kind": "company" }`, `{ "kind": "products", "ids": \[...\] }` или `{ "kind": "passports", "ids": \[...\] }` (до 500 id, всички във вашата компания). Разрешението за купувач трябва да изброява паспорти. |
| `purpose` | body | string (max 500 chars) | no | Защо получателят получава достъп. |
| `evidence` | body | object | no | `{ type, reference, note? }`, където `type` е `register_entry`, `invoice`, `authority_letter`, `contract` или `other`. Записва се, не се проверява. |
| `expiresInDays` | body | integer \| null (1-1825) | no | Дни до изтичане. Пропуснете за стандарта на ролята (12 месеца; без за купувач, чието разрешение приключва при смяна на собственика). `null` = без изтичане. |

## Examples

```bash
curl -sS -X POST https://app.tracepass.eu/api/v1/access-grants \
  -H "Authorization: Bearer tp_REDACTED_xxxxxxxxxxxx" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
  "role": "purchaser",
  "label": "Buyer GmbH, order 4711",
  "scope": { "kind": "passports", "ids": ["6650a1b2c3d4e5f6a7b8c9d0"] }
}'
```

```typescript
const res = await fetch("https://app.tracepass.eu/api/v1/access-grants", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.TRACEPASS_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    role: "purchaser",
    label: "Buyer GmbH, order 4711",
    scope: { kind: "passports", ids: [passportId] },
  }),
});
const grant = await res.json();
// grant.token is shown once: pass it to the recipient, never log it.
```

```python
import os, uuid, requests
res = requests.post(
    "https://app.tracepass.eu/api/v1/access-grants",
    headers={
        "Authorization": f"Bearer {os.environ['TRACEPASS_API_KEY']}",
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "role": "purchaser",
        "label": "Buyer GmbH, order 4711",
        "scope": {"kind": "passports", "ids": [passport_id]},
    },
)
res.raise_for_status()
grant = res.json()  # grant["token"] is shown once
```

## Responses

### 201 — Създадено (токенът се показва веднъж)

```json
{
  "id": "6650c1d2e3f4a5b6c7d8e9f0",
  "accessLevel": "restricted",
  "label": "Buyer GmbH, order 4711",
  "role": "purchaser",
  "scope": { "kind": "passports", "ids": ["6650a1b2c3d4e5f6a7b8c9d0"] },
  "purpose": null,
  "evidence": null,
  "state": "active",
  "expiresAt": null,
  "useCount": 0,
  "createdAt": "2026-06-01T09:30:00.000Z",
  "token": "pa_REDACTED_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "notice": "Pass this token to the recipient now. It cannot be shown again: only a hash is stored, and neither the list nor an idempotent replay returns it."
}
```

### 201 — Идемпотентно повторение (без токен)

```json
{
  "id": "6650c1d2e3f4a5b6c7d8e9f0",
  "accessLevel": "restricted",
  "label": "Buyer GmbH, order 4711",
  "role": "purchaser",
  "scope": { "kind": "passports", "ids": ["6650a1b2c3d4e5f6a7b8c9d0"] },
  "purpose": null,
  "evidence": null,
  "state": "active",
  "expiresAt": null,
  "useCount": 0,
  "createdAt": "2026-06-01T09:30:00.000Z",
  "tokenDelivered": true,
  "notice": "The token was delivered in the first response to this request and cannot be shown again. Revoke this grant and create a new one if it was lost."
}
```

### 400 — Роля на орган

```json
{
  "error": "role_dashboard_only",
  "message": "Authority grants (market_surveillance, notified_body, commission, customs, or the authority tier) are created in the dashboard only."
}
```

### 403 — Изключено

```json
{
  "error": "access_grants_not_enabled",
  "message": "This API key may not manage access grants. Its owner can switch on 'May manage access grants' for the key on the Developer page."
}
```

## Related

- [Списък на разрешенията за достъп](https://www.tracepass.eu/bg/docs/list-access-grants.md)
- [Отнемане на разрешение за достъп](https://www.tracepass.eu/bg/docs/revoke-access-grant.md)
