> 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/es/para-creadores-de-contenido/infoproductos-y-contenido/api-integration.md).

# Integrar productos digitales en tu producto

### Beneficios de la integración de productos digitales de Tribute

#### Para ti, como propietario del servicio:

* **Aceptación de pagos** - SBP y Estrellas de Telegram
* **Integración sencilla** - crea un producto, obtén un enlace, configura un webhook
* **Infraestructura lista** - no necesitas integrar tú mismo a los proveedores de pago
* **Retiros automáticos** - recibe dinero en USDT

#### Para tus usuarios:

* **Pago cómodo** - compra con un clic a través de Telegram
* **Métodos de pago disponibles** - SBP, Estrellas de Telegram

### Cómo funciona: esquema general

#### 1. Tú [creas un producto digital](https://wiki.tribute.tg/en/for-content-creators/digital-product/how-to-create-a-digital-product) en Tribute

Por ejemplo, para un asistente de IA podría ser "Acceso al asistente de IA por 1 mes"

#### 2. Obtén un enlace de pago único

Cada producto tiene su propio enlace en el formato:

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

#### 3. Dirige a los usuarios a este enlace

En tu bot u otro servicio, añade un botón "Pagar" que lleve al enlace del producto

#### 4. El usuario paga

El comprador puede:

* Pagar directamente con Estrellas de Telegram (si están disponibles en el saldo)
* Comprar Estrellas mediante SBP e intercambiarlas inmediatamente por el producto

#### 5. Recibes un webhook sobre el pago exitoso

Después del pago, llega a tu servidor una solicitud POST con la información de la compra. Más sobre el formato del webhook en la [documentación de webhooks](https://wiki.tribute.tg/for-content-creators/api-documentation/webhooks#newdigitalproduct)

#### 6. Proporciona acceso al usuario

Activa el servicio para el usuario usando el ID de Telegram del webhook

### Instrucciones de configuración paso a paso

#### Paso 1: Registro en Tribute

1. Abre [@tribute](https://t.me/tribute) en Telegram
2. Haz clic en "Start" y sigue las instrucciones
3. Ve a la sección "Panel del autor"

#### Paso 2: Creación de un producto digital

1. **En el panel, selecciona "Productos digitales" → "Crear producto instantáneo"**
2. **Serás redirigido al chat con el bot**

   Envía al bot un mensaje que se convertirá en tu producto digital. Puede ser cualquier mensaje: por ejemplo, una foto con descripción, un video, un archivo o incluso una nota de voz.

   **Mensaje de ejemplo para la integración:**

   ```
   ✅ ¡Gracias por comprar acceso al asistente de IA por 1 mes!
   El acceso se proporcionará automáticamente.
   Para activar tu suscripción, vuelve a @YourAIBot
   ```

   > **Importante:** Este es el mensaje exacto que el comprador recibirá después del pago. Añade instrucciones para el usuario para que entienda qué hacer a continuación. Una vez creado el producto, este mensaje no se puede editar (pero siempre puedes crear un nuevo producto digital con un mensaje diferente).
3. **Después de enviar el mensaje, haz clic en el botón "Crear producto" del mensaje del bot**
4. **Completa los campos obligatorios:**
   * **Moneda** - elige la moneda de pago
   * **Nombre** - lo que verá el comprador (por ejemplo: "Asistente de IA por 1 mes")
   * **Descripción** - breve descripción del producto
   * **Precio** - costo en la moneda seleccionada
5. **Guarda el producto**

   Después de guardar, recibirás un enlace de pago único que se puede usar en tu integración

#### Paso 3: Obtención de la clave API

1. En el panel, abre el menú (tres puntos) → "Configuración"
2. Ve a la sección "Claves API"
3. Haz clic en "Generar nueva clave"
4. Guarda la clave en un lugar seguro: la necesitarás para verificar los webhooks

#### Paso 4: Configuración de webhooks

1. En la sección "Claves API", busca el campo "URL del webhook"
2. Especifica la dirección de tu servidor para recibir webhooks:

   ```
   https://your-server.com/webhook/tribute
   ```
3. Guardar configuración

#### Paso 5: Procesamiento de webhooks en tu servidor

Después del pago exitoso de un producto digital, Tribute enviará una solicitud POST a tu URL:

<details>

<summary><strong>Formato del 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>

**Verificación de la firma del webhook**

Cada solicitud contiene una `trbt-signature` cabecera con la firma HMAC-SHA256 del cuerpo de la solicitud. Los ejemplos de verificación de firmas y procesamiento de webhooks están disponibles en la [documentación de webhooks](https://wiki.tribute.tg/for-content-creators/api-documentation/webhooks)

#### Paso 6: Integración en tu bot

En tu bot de Telegram, añade un botón de pago

<details>

<summary>Código Python</summary>

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

def send_payment_button(update, context):
    keyboard = [[
        InlineKeyboardButton(
            "💳 Pagar ($9.99)",
            url="https://t.me/tribute/app?startapp=p456"
        )
    ]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    
    update.message.reply_text(
        "Asistente de IA por 1 mes - $9.99",
        reply_markup=reply_markup
    )
```

</details>

### Trabajando con la 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 %}

### Creación de diferentes tarifas

Para distintos niveles, crea varios productos digitales:

1. **Asistente de IA - 1 mes** (ID: 456) - $9.99
2. **Asistente de IA - 3 meses** (ID: 457) - $24.99
3. **Asistente de IA - 1 año** (ID: 458) - $79.99

### Gestión de reintentos

Cuando falla la entrega del webhook, Tribute reintenta después de:

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

Asegúrate de que tu controlador sea idempotente (reprocesar el mismo pago no creará duplicados).

### Retiros

Puedes retirar los fondos ganados en USDT (los retiros a tarjeta bancaria se añadirán en el futuro). Configura los retiros automáticos en la sección "Cartera".

### Preguntas frecuentes

<details>

<summary>¿Con qué rapidez llegan los webhooks?</summary>

Por lo general, en 1-2 segundos después de un pago exitoso.

</details>

<details>

<summary>¿Puedo cancelar un pago?</summary>

Los productos digitales se pueden cancelar a través del soporte de Tribute.

</details>

***
