Documentation for LLMs

Taddy API & SDK Integration Guide for LLMs

# Taddy API & SDK Integration Guide for LLMs

This document provides a comprehensive technical guide for integrating the Taddy monetization and traffic exchange platform into Telegram-based projects.

---

## 1. Overview

### What is Taddy?
Taddy is a platform designed for the Telegram ecosystem. It allows developers of **Telegram Mini Apps (TMAs)** and **Telegram Bots** to monetize their user base and exchange traffic with other applications in the network.

### Key Features
*   **Monetization:** Display advertisements to users. Taddy integrates with multiple ad networks (Playmatic, TeleAds, Monetag, Nygma) in addition to its own.
*   **Traffic Exchange:** Promote other Telegram apps and bots to your users by showing them "tasks." This can be a source of revenue.
*   **Analytics:** Track key user events like application launches (`/start`), ad impressions, and task completions.

### Target Platforms
1.  **Telegram Mini Apps (TMAs):** Web-based applications that run within Telegram. Integration is done via a **JavaScript SDK**.
2.  **Telegram Bots:** Server-based bots. Integration can be done via a **PHP SDK** or directly using the **REST API**.

---

## 2. IMPORTANT: Onboarding and Authentication

**This is the most critical information for any new integration.**

Taddy is **NOT a self-service platform**. You cannot simply sign up on a website and get API keys.

*   **`pubId` (Public Resource ID):** This is a unique identifier for your bot or application and is **required for every single API request**.
*   **Webhook Private Key:** This key is used to verify the authenticity of incoming webhooks from Taddy's servers.

**To get your `pubId` and private key, you MUST contact the Taddy team directly.** The documentation does not provide a public contact method, so you would need to find this through other channels. Without these credentials, no integration is possible.

---

## 3. Path A: Telegram Mini App (TMA) Integration

This path is for web-based applications running inside Telegram.

### Step 1: Include the SDK
Add the following script tag to your HTML file. The `data-pub-id` attribute is where you place your unique ID from the Taddy team.

```html
<script src="https://sdk.taddy.pro/web/taddy.min.js?1315" data-pub-id="YOUR_PUB_ID_HERE"></script>
```

### Step 2: Initialization & Readiness
The SDK initializes automatically. To signal that your app is ready and to send the initial `start` event, you must call `taddy.ready()`.

```javascript
// Get the Taddy object from the window
const taddy = window.Taddy;

// Initialize with your publisher ID
taddy.init('YOUR_PUB_ID_HERE');

// Signal that the app is ready. This sends the initial "start" event.
taddy.ready();
```

### Step 3: Displaying an Ad
The primary ad format for TMAs is the interstitial (full-screen) ad.

```javascript
// Get the ads module
const ads = taddy.ads();

// Display an interstitial ad
ads.interstitial({
  payload: { my: "data" }, // Optional payload
  onClosed: () => console.log('Ad was closed.'),
  onViewThrough: (id) => console.log('Ad was viewed completely.', id)
});
```

### Step 4: Using the Traffic Exchange
You can fetch and display tasks from the exchange.

```javascript
// Get the exchange module
const exchange = taddy.exchange();

async function showExchangeTasks() {
  // Fetch a list of tasks
  const items = await exchange.feed({
    limit: 8,
    imageFormat: 'png',
    autoImpressions: true, // Automatically track when tasks are shown
    showCompleted: true
  });

  // To open a task and automatically check if the user completed it
  if (items.length > 0) {
    const firstItem = items[0];
    exchange.open(firstItem).then(() => {
      console.log('Task completed! Reward the user.');
    }).catch(() => {
      console.log('Task was not completed.');
    });
  }
}
```

---

## 4. Path B: Telegram Bot Integration

This path is for server-side bots. The **PHP SDK is highly recommended**.

### 4.1. Using the PHP SDK (Recommended)

#### Step 1: Installation
```bash
composer require taddy/taddy-sdk
```

#### Step 2: Initialization
```php
use Taddy\Sdk\Taddy;
use Taddy\Sdk\Utils\TaddyOptions;

$taddy = new Taddy(
    'bot-your-pub-id', // Your Publisher ID
    new TaddyOptions(
        token: 'YOUR_TELEGRAM_BOT_TOKEN'
    )
);
```

#### Step 3: Handling the `/start` Command
This is crucial for analytics. You must create a `TaddyUser` object and send the `start` event.

```php
use Taddy\Sdk\Dto\User as TaddyUser;

// Assuming $tgUser is the user object from the Telegram update
$user = TaddyUser::factory($tgUser->id)
    ->withUsername($tgUser->username ?? '')
    ->withFirstName($tgUser->first_name ?? '')
    ->withLanguage($tgUser->language_code ?? 'en');

// Send the start event
// $message->text would be "/start" or "/start some_param"
$taddy->start($user, $message->text);
```

#### Step 4: Showing an Ad
Ads can be fetched and shown to the user. The SDK can even handle sending the message and deleting it after a delay.

```php
// Get the ads module
$ads = $taddy->ads();

// Get an ad for the user
$ad = $ads->getAd($user);

if ($ad) {
    // Automatically show the ad and delete the message after 15 seconds
    $ads->show($ad, $user, deleteMessage: true, showTime: 15);
}
```

#### Step 5: Full Integration Example (PHP Bot)
This is a complete, practical example for a webhook-based PHP bot.

```php
<?php

require 'vendor/autoload.php';

use Taddy\Sdk\Taddy;
use Taddy\Sdk\Dto\User as TaddyUser;
use Taddy\Sdk\Dto\CustomEvent;
use Taddy\Sdk\Utils\TaddyOptions;

// 1. Initialization
$taddy = new Taddy('bot-your-pub-id', new TaddyOptions(token: 'YOUR_BOT_TOKEN'));

// 2. Webhook Handler
$update = json_decode(file_get_contents('php://input'));

// 3. Handle Incoming Message
if ($message = $update->message ?? null) {
    $tgUser = $message->from;
    $user = TaddyUser::factory($tgUser->id)
        ->withUsername($tgUser->username ?? '')
        ->withPremium($tgUser->is_premium ?? false);

    // Handle /start command
    if (str_starts_with($message->text, '/start')) {
        $taddy->start($user, $message->text);

        // Show an ad on start
        $ad = $taddy->ads()->getAd($user);
        if ($ad) {
            $taddy->ads()->show($ad, $user, deleteMessage: true, showTime: 15);
        }
        sendMessage($tgUser->id, "Welcome! Use /tasks to see available tasks.");
    }

    // Handle /tasks command
    if ($message->text === '/tasks') {
        $exchange = $taddy->exchange();
        $tasks = $exchange->getFeed($user, limit: 5);

        if (empty($tasks)) {
            sendMessage($tgUser->id, "No tasks available right now.");
        } else {
            foreach ($tasks as $task) {
                // Show task with a button
                $keyboard = [['text' => "Complete (+{$task->price})", 'callback_data' => "do_{$task->id}"]];
                sendPhotoWithButton(
                    $tgUser->id,
                    $task->image,
                    "{$task->title}\n\n{$task->description}",
                    $keyboard
                );
            }
            // Send impressions for all tasks shown
            $exchange->impressions($user, $tasks);
        }
    }
}

// 4. Handle Button Clicks (Callbacks)
if ($callback = $update->callback_query ?? null) {
    $tgUser = $callback->from;
    $user = TaddyUser::factory($tgUser->id)->withUsername($tgUser->username ?? '');

    if (str_starts_with($callback->data, 'do_')) {
        $taskId = str_replace('do_', '', $callback->data);

        // Open the task link for the user
        answerCallbackWithUrl($callback->id, "https://t.tadly.pro/e/{$taskId}");

        // Check for completion after 20 seconds
        sleep(20);
        $completed = $taddy->exchange()->check($user, $taskId);

        if ($completed) {
            sendMessage($tgUser->id, "✅ Task completed! Reward credited.");
            // Send a custom event for analytics
            $taddy->customEvent($user, CustomEvent::CUSTOM1);
        } else {
            sendMessage($tgUser->id, "❌ Task not completed. Please try again.");
        }
    }
}
```

### 4.2. Using the REST API Directly

For non-PHP backends or for custom implementations. All requests are `POST` with a JSON body.

*   **Production URL:** `https://api.taddy.pro/v1`
*   **Staging URL:** `https://api.taddy.tech/v1`

#### Example: Sending a `start` event with `curl`
```bash
curl -X POST \
  https://api.taddy.pro/v1/events/start \
  -H 'Content-Type: application/json' \
  -d 
{
    "pubId": "YOUR_PUB_ID_HERE",
    "user": {
      "id": 123456789,
      "firstName": "John",
      "username": "john_doe",
      "language": "en"
    },
    "origin": "server",
    "start": "/start"
}
```

#### Example: Getting the Exchange Feed
```bash
curl -X POST \
  https://api.taddy.pro/v1/exchange/feed \
  -H 'Content-Type: application/json' \
  -d 
{
    "pubId": "YOUR_PUB_ID_HERE",
    "user": { "id": 123456789 },
    "origin": "server",
    "limit": 5,
    "autoImpressions": false
}
```

---

## 5. Core Data Structures (for REST API)

### The `user` Object
This object is required in almost every request.

```json
{
  "id": 1234567890,
  "firstName": "John",
  "lastName": "Doe",
  "username": "john_doe",
  "premium": true,
  "language": "en",
  "country": "DE",
  "gender": "male",
  "ip": "65.82.123.21",
  "userAgent": "Mozilla/5.0...",
  "birthDate": "2001-01-01"
}
```

### The `ExchangeFeedItem` Object (from `/exchange/feed`)
```json
{
  "id": "qwertyuio....asdfghjk",
  "uid": "11ddbaf3386aea1f2974eee984542152",
  "title": "This is demo",
  "description": "Please, click me!",
  "image": "https://cdn.google.com/images/123456.webp",
  "type": "app",
  "price": 0.15,
  "link": "https://t.tadly.pro/e/qwertyuio....asdfghjk",
  "status": "new",
  "createdAt": "2025-07-28T07:22:22+00:00",
  "expiresAt": "2025-07-28T09:22:43+00:00"
}
```

---

## 6. Webhooks

Taddy uses webhooks to send real-time event notifications to your server.

### Supported Events
*   `exchange.incoming`: A new user has arrived from a Taddy traffic exchange link.
*   `exchange.outgoing`: A user has left to a Taddy traffic exchange link.
*   `ads.impression`: An ad was shown.
*   `ads.view_through`: An ad was watched completely.
*   `custom_event`: A custom event occurred.

### Webhook Verification
This is essential for security. Taddy sends a signature in the `X-Taddy-Sign` header. You must verify it.

**Signature Formula:** `sha1(ID + URL + BODY + YOUR_PRIVATE_KEY)`

*   `ID`: From the `X-Taddy-Event-Id` header.
*   `URL`: The full URL of your webhook endpoint.
*   `BODY`: The raw JSON body of the POST request.
*   `YOUR_PRIVATE_KEY`: The secret key provided by the Taddy team.

#### PHP Verification Example:
```php
$id = $_SERVER['HTTP_X_TADDY_EVENT_ID'];
$sign = $_SERVER['HTTP_X_TADDY_SIGN'];
$body = file_get_contents('php://input');
$url = 'https://yourdomain.com' . $_SERVER['REQUEST_URI'];
$privateKey = 'YOUR_PRIVATE_KEY'; // From Taddy Team

$calculatedSign = sha1($id . $url . $body . $privateKey);

if ($sign === $calculatedSign) {
    // Webhook is valid
    $event = json_decode($body);
    // Process event...
} else {
    // Invalid webhook, ignore.
    http_response_code(403);
}
```

---

## 7. Summary & Appendix

### What Is Known
*   The full REST API structure is defined in the OpenAPI spec.
*   SDKs for Web (JS) and Bots (PHP) provide high-level abstractions.
*   The data models for users, ads, and tasks are clear.
*   The webhook verification mechanism is clearly defined.

### What Is Unknown (Requires contacting Taddy)
*   **Onboarding Process:** How to register and get a `pubId`.
*   **Monetization Details:** Specific payment rates, commission structures, and withdrawal methods.
*   **Contact Information:** No public email or contact form is available in the documentation.

### Useful Links
*   **Main Documentation:** `https://taddy.gitbook.io/docs`
*   **OpenAPI Spec:** `https://api.taddy.pro/openapi/v1.yaml`
*   **PHP SDK Repo:** `https://github.com/taddy-pro/taddy-sdk-php`
*   **Web SDK File:** `https://sdk.taddy.pro/web/taddy.min.js`
*   **API Server:** `https://api.taddy.pro/v1`
*   **General Telegram API:** `https://api.telegram.org`

Last updated