> For the complete documentation index, see [llms.txt](https://wiki.tribute.top/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wiki.tribute.top/br-pt/para-criadores-de-conteudo/produtos-informativos-e-conteudo/api-integration.md).

# Integrando produtos digitais ao seu produto

### Benefícios da Integração de Produtos Digitais do Tribute

#### Para você, como proprietário do serviço:

* **Aceitação de pagamentos** - SBP e Telegram Stars
* **Integração simples** - crie um produto, obtenha um link, configure um webhook
* **Infraestrutura pronta** - não é necessário integrar provedores de pagamento por conta própria
* **Saques automáticos** - receba dinheiro em USDT

#### Para seus usuários:

* **Pagamento conveniente** - compra com um clique pelo Telegram
* **Métodos de pagamento disponíveis** - SBP, Telegram Stars

### Como funciona: esquema geral

#### 1. Você [cria um produto digital](https://wiki.tribute.tg/en/for-content-creators/digital-product/how-to-create-a-digital-product) no Tribute

Por exemplo, para um assistente de IA, poderia ser "Acesso ao Assistente de IA por 1 mês"

#### 2. Obtenha um link de pagamento exclusivo

Cada produto tem seu próprio link no formato:

* Para Telegram: `https://t.me/tribute/app?startapp=p123`
* Para navegador: `https://web.tribute.tg/p/123`

#### 3. Direcione os usuários para este link

No seu bot ou outro serviço, adicione um botão "Pagar" que leva ao link do produto

#### 4. O usuário paga

O comprador pode:

* Pagar diretamente com Telegram Stars (se estiver disponível no saldo)
* Comprar Stars via SBP e trocá-las imediatamente pelo produto

#### 5. Você recebe um webhook sobre o pagamento bem-sucedido

Após o pagamento, uma requisição POST com as informações da compra chega ao seu servidor. Mais sobre o formato do webhook na [documentação de webhooks](https://wiki.tribute.tg/for-content-creators/api-documentation/webhooks#newdigitalproduct)

#### 6. Forneça acesso ao usuário

Ative o serviço para o usuário usando o ID do Telegram do webhook

### Instruções de configuração passo a passo

#### Etapa 1: Registro no Tribute

1. Abra [@tribute](https://t.me/tribute) no Telegram
2. Clique em "Iniciar" e siga as instruções
3. Vá para a seção "Painel do autor"

#### Etapa 2: Criação de um produto digital

1. **No painel, selecione "Produtos digitais" → "Criar produto instantâneo"**
2. **Você será redirecionado para a conversa com o bot**

   Envie ao bot uma mensagem que se tornará seu produto digital. Isso pode ser qualquer mensagem - por exemplo, uma foto com descrição, vídeo, arquivo ou até mesmo uma nota de voz.

   **Exemplo de mensagem de texto para integração:**

   ```
   ✅ Obrigado por comprar acesso ao Assistente de IA por 1 mês!
   O acesso será fornecido automaticamente.
   Para ativar sua assinatura, volte para @YourAIBot
   ```

   > **Importante:** Esta é a mensagem exata que o comprador receberá após o pagamento. Adicione instruções para o usuário para que ele entenda o que fazer a seguir. Depois que o produto for criado, esta mensagem não poderá ser editada (mas você sempre pode criar um novo produto digital com uma mensagem diferente).
3. **Depois de enviar a mensagem, clique no botão "Create Product" na mensagem do bot**
4. **Preencha os campos obrigatórios:**
   * **Moeda** - escolha a moeda de pagamento
   * **Nome** - o que o comprador verá (por exemplo: "Assistente de IA por 1 mês")
   * **Descrição** - breve descrição do produto
   * **Preço** - custo na moeda selecionada
5. **Salve o produto**

   Após salvar, você receberá um link de pagamento exclusivo que poderá ser usado na sua integração

#### Etapa 3: Obtenção da chave de API

1. No painel, abra o menu (três pontos) → "Configurações"
2. Vá para a seção "Chaves de API"
3. Clique em "Gerar nova chave"
4. Salve a chave em um local seguro - você precisará dela para verificar os webhooks

#### Etapa 4: Configuração dos webhooks

1. Na seção "Chaves de API", encontre o campo "URL do webhook"
2. Informe o endereço do seu servidor para receber webhooks:

   ```
   https://your-server.com/webhook/tribute
   ```
3. Salve as configurações

#### Etapa 5: Processando webhooks no seu servidor

Após o pagamento bem-sucedido de um produto digital, o Tribute enviará uma requisição POST para sua URL:

<details>

<summary><strong>Formato do webhook</strong></summary>

```json
{
  "name": "new_digital_product",
  "created_at": "2025-03-20T01:15:58.332Z",
  "sent_at": "2025-03-20T01:15:58.542Z",
  "payload": {
    "product_id": 456,
    "amount": 500,
    "currency": "usd",
    "user_id": 31326,
    "telegram_user_id": 12321321
  }
}
```

</details>

**Verificação da assinatura do webhook**

Cada requisição contém um `trbt-signature` cabeçalho com a assinatura HMAC-SHA256 do corpo da requisição. Exemplos de verificação de assinatura e processamento de webhooks estão disponíveis na [documentação de webhooks](https://wiki.tribute.tg/for-content-creators/api-documentation/webhooks)

#### Etapa 6: Integração no seu bot

No seu bot do Telegram, adicione um botão de pagamento

<details>

<summary>Código em Python</summary>

```python
# Python + python-telegram-bot
from telegram import InlineKeyboardButton, InlineKeyboardMarkup

def send_payment_button(update, context):
    keyboard = [[
        InlineKeyboardButton(
            "💳 Pagar (US$ 9,99)",
            url="https://t.me/tribute/app?startapp=p456"
        )
    ]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    
    update.message.reply_text(
        "Assistente de IA por 1 mês - US$ 9,99",
        reply_markup=reply_markup
    )
```

</details>

### Trabalhando com a API

## Get Product by ID

> Returns a single product by its ID

```json
{"openapi":"3.1.0","info":{"title":"Tribute API","version":"1.0.0"},"tags":[{"name":"Products","description":"Product operations. Products exist in three types:\n\n- `digital` - [Digital product](https://wiki.tribute.tg/for-content-creators/digital-product). Any Telegram message with optional attachments\n- `custom` - [Custom product](https://wiki.tribute.tg/for-content-creators/digital-product/digital-custom-product). On-demand content, e.g., personalized video greetings\n- `physical` - [Physical product](https://wiki.tribute.tg/for-content-creators/fizicheskie-tovary). Merchandise with shipping, e.g., printed t-shirts\n\nAll amounts are in smallest currency units (cents/kopecks)\n"}],"servers":[{"url":"https://tribute.tg/api/v1","description":"Tribute API v1"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Api-Key","description":"API key for authentication."}},"schemas":{"Product":{"type":"object","required":["id","type","name","amount","currency","status","isCustom","acceptCards","acceptWalletPay","protectContent","created","updated","link","webLink"],"properties":{"id":{"type":"integer","description":"Product ID"},"type":{"type":"string","description":"Product type","enum":["digital","custom","physical"]},"name":{"type":"string","description":"Product name"},"description":{"type":"string","description":"Product description"},"amount":{"type":"integer","format":"int64","description":"Product price in smallest currency units (cents for USD/EUR, kopecks for RUB). For physical products this is the starting price, taken from the cheapest variant."},"currency":{"type":"string","description":"Currency code","enum":["USD","EUR","RUB"]},"starsAmount":{"type":"integer","description":"Price in Telegram Stars"},"starsAmountEnabled":{"type":"boolean","description":"Whether payment with Stars is enabled"},"status":{"type":"string","description":"Product status","enum":["pending","approved","rejected"]},"isCustom":{"type":"boolean","description":"Whether this is a custom product"},"acceptCards":{"type":"boolean","description":"Whether card payments are accepted"},"acceptWalletPay":{"type":"boolean","description":"Whether wallet payments are accepted"},"protectContent":{"type":"boolean","description":"Whether content protection is enabled"},"created":{"type":"string","format":"date-time","description":"Product creation date"},"updated":{"type":"string","format":"date-time","description":"Product last update date"},"pendingOrders":{"type":"integer","description":"Number of pending orders (for custom products)"},"imageUrl":{"type":"string","format":"uri","description":"Product image URL"},"link":{"type":"string","format":"uri","description":"Direct link to product in Telegram app"},"webLink":{"type":"string","format":"uri","description":"Web link to product"}}},"Error":{"type":"object","required":["error","message"],"properties":{"error":{"type":"string","description":"Error code","enum":["error_bad_request","error_not_found","error_not_permitted","no_access"]},"message":{"type":"string","description":"Error description"}}}}},"paths":{"/products/{id}":{"get":{"summary":"Get Product by ID","description":"Returns a single product by its ID","tags":["Products"],"parameters":[{"name":"id","in":"path","description":"Product ID","required":true,"schema":{"type":"integer"}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Product"}}}},"400":{"description":"Bad request (invalid product ID format)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Unauthorized (invalid API key)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"Access denied","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Product not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}}}
```

## Get Products List

> Returns a paginated list of products

```json
{"openapi":"3.1.0","info":{"title":"Tribute API","version":"1.0.0"},"tags":[{"name":"Products","description":"Product operations. Products exist in three types:\n\n- `digital` - [Digital product](https://wiki.tribute.tg/for-content-creators/digital-product). Any Telegram message with optional attachments\n- `custom` - [Custom product](https://wiki.tribute.tg/for-content-creators/digital-product/digital-custom-product). On-demand content, e.g., personalized video greetings\n- `physical` - [Physical product](https://wiki.tribute.tg/for-content-creators/fizicheskie-tovary). Merchandise with shipping, e.g., printed t-shirts\n\nAll amounts are in smallest currency units (cents/kopecks)\n"}],"servers":[{"url":"https://tribute.tg/api/v1","description":"Tribute API v1"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Api-Key","description":"API key for authentication."}},"schemas":{"Product":{"type":"object","required":["id","type","name","amount","currency","status","isCustom","acceptCards","acceptWalletPay","protectContent","created","updated","link","webLink"],"properties":{"id":{"type":"integer","description":"Product ID"},"type":{"type":"string","description":"Product type","enum":["digital","custom","physical"]},"name":{"type":"string","description":"Product name"},"description":{"type":"string","description":"Product description"},"amount":{"type":"integer","format":"int64","description":"Product price in smallest currency units (cents for USD/EUR, kopecks for RUB). For physical products this is the starting price, taken from the cheapest variant."},"currency":{"type":"string","description":"Currency code","enum":["USD","EUR","RUB"]},"starsAmount":{"type":"integer","description":"Price in Telegram Stars"},"starsAmountEnabled":{"type":"boolean","description":"Whether payment with Stars is enabled"},"status":{"type":"string","description":"Product status","enum":["pending","approved","rejected"]},"isCustom":{"type":"boolean","description":"Whether this is a custom product"},"acceptCards":{"type":"boolean","description":"Whether card payments are accepted"},"acceptWalletPay":{"type":"boolean","description":"Whether wallet payments are accepted"},"protectContent":{"type":"boolean","description":"Whether content protection is enabled"},"created":{"type":"string","format":"date-time","description":"Product creation date"},"updated":{"type":"string","format":"date-time","description":"Product last update date"},"pendingOrders":{"type":"integer","description":"Number of pending orders (for custom products)"},"imageUrl":{"type":"string","format":"uri","description":"Product image URL"},"link":{"type":"string","format":"uri","description":"Direct link to product in Telegram app"},"webLink":{"type":"string","format":"uri","description":"Web link to product"}}},"Error":{"type":"object","required":["error","message"],"properties":{"error":{"type":"string","description":"Error code","enum":["error_bad_request","error_not_found","error_not_permitted","no_access"]},"message":{"type":"string","description":"Error description"}}}}},"paths":{"/products":{"get":{"summary":"Get Products List","description":"Returns a paginated list of products","tags":["Products"],"parameters":[{"name":"page","in":"query","description":"Page number","required":false,"schema":{"type":"integer","minimum":1,"default":1}},{"name":"size","in":"query","description":"Items per page","required":false,"schema":{"type":"integer","minimum":1,"maximum":100,"default":20}},{"name":"type","in":"query","description":"Filter by product type","required":false,"schema":{"type":"string","enum":["digital","custom","physical"]}},{"name":"desc","in":"query","description":"Sort by ID descending","required":false,"schema":{"type":"boolean","default":false}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":{"rows":{"type":"array","items":{"$ref":"#/components/schemas/Product"}},"meta":{"type":"object","properties":{"total":{"type":"integer","format":"int64","description":"Total number of items"},"offset":{"type":"integer","format":"int64","description":"Current page number"},"limit":{"type":"integer","format":"int64","description":"Page size"}}}}}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Unauthorized (invalid API key)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}}}
```

## Cancel Digital Product Purchase

> Cancels a digital product purchase and refunds the payment.\
> \
> \*\*Important:\*\* This endpoint only supports refunds for purchases paid with Telegram Stars.\
> Purchases paid with other payment methods cannot be refunded via this endpoint.<br>

```json
{"openapi":"3.1.0","info":{"title":"Tribute API","version":"1.0.0"},"tags":[{"name":"Products","description":"Product operations. Products exist in three types:\n\n- `digital` - [Digital product](https://wiki.tribute.tg/for-content-creators/digital-product). Any Telegram message with optional attachments\n- `custom` - [Custom product](https://wiki.tribute.tg/for-content-creators/digital-product/digital-custom-product). On-demand content, e.g., personalized video greetings\n- `physical` - [Physical product](https://wiki.tribute.tg/for-content-creators/fizicheskie-tovary). Merchandise with shipping, e.g., printed t-shirts\n\nAll amounts are in smallest currency units (cents/kopecks)\n"}],"servers":[{"url":"https://tribute.tg/api/v1","description":"Tribute API v1"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Api-Key","description":"API key for authentication."}},"schemas":{"Error":{"type":"object","required":["error","message"],"properties":{"error":{"type":"string","description":"Error code","enum":["error_bad_request","error_not_found","error_not_permitted","no_access"]},"message":{"type":"string","description":"Error description"}}}}},"paths":{"/products/purchases/{purchaseId}/cancel":{"post":{"summary":"Cancel Digital Product Purchase","description":"Cancels a digital product purchase and refunds the payment.\n\n**Important:** This endpoint only supports refunds for purchases paid with Telegram Stars.\nPurchases paid with other payment methods cannot be refunded via this endpoint.\n","tags":["Products"],"parameters":[{"name":"purchaseId","in":"path","description":"Digital product purchase ID (ProductPurchase.ID)","required":true,"schema":{"type":"integer"}}],"responses":{"200":{"description":"Purchase successfully cancelled and payment refunded","content":{"application/json":{"schema":{"type":"object","required":["success","purchaseId","message"],"properties":{"success":{"type":"boolean","description":"Operation success status"},"purchaseId":{"type":"integer","description":"Cancelled purchase ID"},"message":{"type":"string","description":"Success message"}}}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Unauthorized (invalid API key)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"Access denied (not the product owner)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Purchase or user not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}}}
```

{% openapi-webhook spec="api-en" name="newDigitalProduct" method="post" %}
[api-en](https://tribute.tg/api/v1/openapi/en)
{% endopenapi-webhook %}

{% openapi-webhook spec="api-en" name="digitalProductRefund" method="post" %}
[api-en](https://tribute.tg/api/v1/openapi/en)
{% endopenapi-webhook %}

### Criando diferentes planos

Para diferentes níveis, crie vários produtos digitais:

1. **Assistente de IA - 1 mês** (ID: 456) - US$ 9,99
2. **Assistente de IA - 3 meses** (ID: 457) - US$ 24,99
3. **Assistente de IA - 1 ano** (ID: 458) - US$ 79,99

### Tratamento de tentativas de nova entrega

Quando a entrega do webhook falha, o Tribute tenta novamente após:

* 5 minutos
* 15 minutos
* 30 minutos
* 1 hora
* 10 horas

Certifique-se de que seu handler seja idempotente (o reprocessamento do mesmo pagamento não criará duplicatas).

### Saques

Você pode sacar os fundos ganhos em USDT (saques para cartão bancário serão adicionados no futuro). Configure saques automáticos na seção "Wallet".

### Perguntas frequentes

<details>

<summary>Com que rapidez os webhooks chegam?</summary>

Normalmente em 1-2 segundos após o pagamento bem-sucedido.

</details>

<details>

<summary>Posso cancelar um pagamento?</summary>

Produtos digitais podem ser cancelados pelo suporte do Tribute.

</details>

***
