# Integrate Platformy into a Telegram Mini App or bot

You are a coding agent (Claude Code, Cursor, Codex, ...). The app owner pointed you at this file and gave you a **pubId**. This file is everything you need: read it completely, then follow the steps in order. Talk to the owner in the owner's language (the language of their messages), keep code, identifiers and commit messages in English, and avoid jargon: say "ad spots" and "tasks from other apps", not "SDK" and "placements", unless the owner uses those words.

Platformy = ads (rewarded, interstitial, banner), a free people exchange with other apps (a tasks wall in the app shows tasks of other apps), and product analytics. It is integrated with one script tag plus a few calls. Full function reference: <https://platfor.my/agent/sdk-reference.md>.

Hosts: SDK `https://platfor.my/sdk.js`; API `https://api.platfor.my`.

## Goal and rules

Goal: a working, verified integration that shows ads only where the owner agreed, reports analytics, and breaks nothing.

Hard rules:
1. **Never show a rewarded ad (`showReward`, `showTask`) without an explicit user action** (the user tapped a "get bonus / extra life / free spin" button). Never on load, never on a timer. Interstitials only at natural breaks (level end, screen transitions), never while the user is mid-action, and rate-limit them (for example at most once per 2-3 minutes).
2. **Never touch the owner's money, payment settings, bot tokens, wallets, prices, or Platformy panel settings.** You only edit code in this project. The single thing you may read from a bot token is its numeric id (the digits before the `:`), passed as `botId` (Step 2); the token itself is never copied, logged, printed or sent anywhere. Never ask the owner to paste secret keys into the chat; secrets go into environment variables or the project's existing secret mechanism, and you only reference them by name.
3. **Keep the existing UX.** Do not restyle, move or remove existing elements. New elements must fit the existing design (reuse its components and CSS variables).
4. **Ask before adding anything visible.** Nothing visible (banner, button, wall, ad call) is added before the owner answered the question in Step 3. Invisible analytics (script tag, goals, purchases) may be added right after Step 2.
5. Every ad call must be fail-safe: if the call resolves `false` or never fires its callback with `true`, the app must continue normally and must not grant rewards.
6. Do not commit, push, or deploy unless the owner asked you to. Leave the changes in the working tree and say what to run.

## Step 1: Detect the stack

Look at the repository (do not ask yet). Determine:
- Is there a Mini App front-end (HTML that loads `telegram-web-app.js`, or `@telegram-apps/sdk`, `@twa-dev/sdk`, `window.Telegram.WebApp` usage)? Which framework: plain HTML/JS, React (Vite/CRA), Next.js, Vue/Nuxt, Svelte, other?
- Is there a Telegram bot (grammY, Telegraf, node-telegram-bot-api, aiogram, python-telegram-bot, other) with or without a Mini App?
- Where is the HTML entry (`index.html`, `app/layout.tsx`, `pages/_document.tsx`, `nuxt.config`)? Where does the app create payments (`createInvoiceLink`, `openInvoice`, TON Connect `sendTransaction`)? Where are rewards granted (coins, lives, spins)? Where is the main navigation / screens list?
- Does a Platformy integration already exist (`grep -riE "platform[ay]"`)? If yes, extend it instead of duplicating.

Decide: **Mini App front-end present** -> use the browser SDK (Steps 2-6). **Bot only, no Mini App** -> use the inline bot API (end of Step 2) and skip front-end placements. Both present -> do both.

## Step 2: Install

### Mini App (browser SDK)

Add two script tags to the HTML entry, **immediately after** the Telegram script (the SDK reads `window.Telegram.WebApp` at init, so the Telegram script must load first):

```html
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<script src="https://platfor.my/sdk.js"></script>
<script>Platformy.init({ pubId: 'YOUR_PUB_ID' });</script>
```

Replace `YOUR_PUB_ID` with the pubId from the owner. Rules:
- If the project already loads `telegram-web-app.js`, put ours right after that tag; do not add a second Telegram script.
- **Bot id (`botId`).** If the project already has the Telegram bot token in its config or environment (for example `BOT_TOKEN`, `TELEGRAM_BOT_TOKEN`, `.env`, a settings file), read ONLY the numeric part before the `:` and pass it as `botId`: `Platformy.init({ pubId: 'YOUR_PUB_ID', botId: 1234567890 })` (a number or a numeric string). The bot id is public; it lets Platformy verify that users are real. **NEVER copy, log, print, commit or send the token itself, and never paste it into `init`, the chat, a file or a URL.** Take the number at build/run time from the existing variable, or, if the app has no server step, write only the digits as a literal (they are not a secret). If the project has no bot token available, omit `botId` (the owner can enter the bot id in the panel instead). Platformy stores the id only after it verifies the app's signed launch data for exactly that id, so a wrong id is simply ignored.
- Leave out `level`: the owner controls the analytics level in the panel. Do not pass `level: false`: it also turns off the invoice tracking that Stars purchases rely on.
- The pubId is public (it is visible to every user), so it is fine in source. Prefer an env var only if the project already uses one for similar public ids.

Framework notes:
- **Vite/CRA React, Vue, Svelte**: put the tags in `index.html` (`<head>` or end of `<body>`, after the Telegram script). No npm package. The global is `window.Platformy`; for TypeScript add `declare const Platformy: any;` (or `interface Window { Platformy: any }`) in a `.d.ts` file.
- **Next.js (App Router)**: in `app/layout.tsx` render `next/script` tags with `strategy="beforeInteractive"` in this order: `<Script src="https://telegram.org/js/telegram-web-app.js" strategy="beforeInteractive" />` (if missing), `<Script src="https://platfor.my/sdk.js" strategy="beforeInteractive" />`, `<Script id="platforma-init" strategy="beforeInteractive">{"Platformy.init({ pubId: 'YOUR_PUB_ID' });"}</Script>`. That way init runs before React hydrates and before any component effect. (With `afterInteractive` instead, route every call through `window.PlatformyQueue` as in the React provider in 4.2; the queue is drained at init.) Never call `Platformy.*` during server rendering; wrap calls in `typeof window !== 'undefined'`.
- **Nuxt**: add the scripts via `app.head.script` in `nuxt.config`, init in a client-only plugin (`plugins/platformy.client.ts`).
- **Rule: `Platformy.init` runs once, before any other call.** Calls made earlier (script not loaded or not initialized yet) must go through the queue, which is drained at init:
  `(window.PlatformyQueue = window.PlatformyQueue || []).push(['goal', 'name'])`.

### Special setups

**Apps on `@telegram-apps/sdk` (or `@twa-dev/sdk`) without `telegram-web-app.js`.** Telegram still passes the signed launch data in the URL (`#tgWebAppData=...`) and the SDK reads it from there, so no extra script is needed: add only our `sdk.js` and `init`. If you can read the raw launch string (`retrieveRawInitData()` from `@telegram-apps/sdk`), pass it explicitly, it is the most reliable way:

```js
import { retrieveRawInitData } from '@telegram-apps/sdk';
Platformy.init({ pubId: 'YOUR_PUB_ID', botId: 1234567890, initData: retrieveRawInitData() });
```

**Game in an iframe of the Mini App page** (for example a wrapper page `index.html` that embeds `/web/index.html`). Inside a cross-origin iframe there is no `window.Telegram`, so events arrive without a user and payments cannot be matched. The SDK already reads `window.parent.Telegram` when the parent is same-origin; otherwise pass the raw string from the wrapper into the game:

```js
// wrapper page (has telegram-web-app.js)
const frame = document.getElementById('game');
const send = () => frame.contentWindow.postMessage({ type: 'platformy:init', initData: Telegram.WebApp.initData }, GAME_ORIGIN);
frame.addEventListener('load', send);

// game page: load sdk.js, then wait for the message (check event.origin = the wrapper's origin)
window.addEventListener('message', (e) => {
  if (e.origin !== WRAPPER_ORIGIN || !e.data || e.data.type !== 'platformy:init' || window.__pfStarted) return;
  window.__pfStarted = true;
  Platformy.init({ pubId: 'YOUR_PUB_ID', botId: 1234567890, initData: e.data.initData });
});
```

Calls made before `init` (goals, purchases) are queued (`PlatformyQueue`) and delivered after it, so the game can keep calling `Platformy.goal(...)` meanwhile. If the wrapper and the game are served from the same origin, no message is needed.

**WebGL engines (Unity, Godot, Cocos, Construct, Phaser).** Load `sdk.js` and call `init` in the HTML shell (`index.html` of the export), not from game code. Engine code reaches the SDK through a JS bridge:
- Unity: a `.jslib` plugin (`mergeInto(LibraryManager.library, { PlatformyGoal: function (name) { window.Platformy.goal(UTF8ToString(name)); } })`) and `[DllImport("__Internal")]` in C#.
- Godot 4: `JavaScriptBridge.eval("Platformy.goal('tree_planted')")` (Web export; the HTML shell is the custom `html/custom_html_shell`).
- Cocos / Construct / Phaser: `window.Platformy.goal(...)` directly from script (Construct: the "Browser: execute JavaScript" action).
If the game runs inside an iframe, apply the iframe recipe above in the shell page.

### Telegram bot without a Mini App (inline API)

No script tag. Ads are woven into bot replies on the server. The owner generates a **secret key** in the panel (Resource -> Integration -> Keys) and enables inline ads there (frequency, daily cap, Premium exemption are configured in the panel, not in code). Put the key in an environment variable (for example `PLATFORMY_SECRET_KEY`), never in source; ask the owner to set it, do not ask them to paste it to you.

Node: `npm i @platforma/inline` (if the package cannot be installed, use the HTTP call below, it is the same API):

```js
import { InlineAds } from '@platforma/inline';
const ads = new InlineAds({ apiKey: process.env.PLATFORMY_SECRET_KEY, pubId: 'YOUR_PUB_ID' });

// wrap the place where the bot sends a reply
const r = await ads.inject({
  userId: msg.from.id,
  message: replyText,
  languageCode: msg.from.language_code,
  isPremium: msg.from.is_premium,
  parseMode: 'HTML',          // match how you send the message
  keyboard: existingKeyboard, // optional, the ad button is merged into it
});
await bot.sendMessage(chatId, r.message, { parse_mode: 'HTML', reply_markup: r.keyboard });
```

If the reply may contain personal data, use `ads.fetch({ userId, languageCode, isPremium })` instead: it returns `{ hasAd, ad: { adText, buttonText, buttonUrl, mediaUrl } }` and you render the text and the URL button yourself; nothing from the reply is sent to Platformy. Both calls never throw and return the original message on any error or timeout (3 s), so the bot cannot break.

Python (or any language), plain HTTP:

```python
import os, requests
def with_ad(user_id, text, lang=None, premium=False):
    try:
        r = requests.post(
            "https://api.platfor.my/api/v1/ad/inject",
            json={"pubId": "YOUR_PUB_ID", "userId": user_id, "message": text,
                  "languageCode": lang, "isPremium": premium, "parseMode": "HTML"},
            headers={"Authorization": "Bearer " + os.environ["PLATFORMY_SECRET_KEY"]},
            timeout=3)
        res = r.json().get("result") or {}
        if res.get("hasAd"):
            ad = res["ad"]  # { adText, buttonText, buttonUrl, mediaUrl }
            return res["message"], [[{"text": ad["buttonText"], "url": ad["buttonUrl"]}]]
    except Exception:
        pass
    return text, None   # fail-open: always send the original message
```

`POST /api/v1/ad/fetch` has the same request without `message`/`parseMode` and returns `{ result: { hasAd, ad } }`. Add the button row to the existing keyboard, do not replace it. Impressions are tracked automatically; the button URL handles click tracking. For a bot, skip Steps 3-5 front-end parts: pick the replies where an ad is acceptable (ask the owner in one message as in Step 3), then go to Step 6 (status will show `sdk` only for Mini App traffic; for bots, report what you added and how the owner can see impressions in the panel).

## Step 3: Find placement candidates and ask the owner (ONE message)

Search the Mini App code for these patterns and note file and line for each:

| What you find | Suggested ad | Suggested placement name |
|---|---|---|
| Free spins, extra life / continue, bonus coins, energy refill, "double the reward", revive, hint, unlock, daily bonus buttons | **Rewarded** (`showReward`) behind the existing or a new button | `extra_life`, `bonus_coins`, `free_spin`, `double_reward`, `energy_refill` |
| End of level / round / match, result screen, route change between big screens, "play again" | **Interstitial** (`showInterstitial`) | `level_end`, `round_end`, `screen_change` |
| A rewards / tasks / earn / quests / friends screen, a list of missions | **Tasks wall** (`tasks`) in that screen | `earn`, `tasks_screen` |
| Top of the home / main screen, a spot under the header or above the bottom nav that has free space | **Banner** (`banner`) | `home_top`, `home_bottom` |
| Meaningful user actions (tutorial finished, level N reached, first deposit, registration, wallet connected) | **Goals** (invisible, `Platformy.goal`) | `tutorial_done`, `level_5_reached`, `first_deposit` |

Placement names: lowercase letters, digits, underscore, 1-40 chars. Pick short descriptive names; the owner will see them in the panel and can toggle each one.

Then send the owner **one message** (in their language), plain words, short, with this content:
1. One line: what you found (stack, 1 sentence).
2. A numbered list of candidate spots: for each, where in the app (screen/button, human words), which ad type, and the suggested name. Mark your recommended default set (usually 1 rewarded + 1 interstitial at a natural break). Do not propose more than about 6.
3. The question about the tasks wall: "Add a screen/section where users get tasks from other apps (cross-promotion)? Yes / No. If yes, where?" (Only if the app has a rewards/earn area or room for one.)
4. The list of invisible analytics you intend to add (goals, purchase tracking) with names, "no visual change".
5. "Reply with the numbers to enable, or 'all' / 'none'."

**Stop and wait for the answer.** Do not implement visible things before the owner replies. Invisible things from item 4 may proceed. If the owner says "decide yourself", enable your recommended default set only.

## Step 4: Implement

Only what the owner approved. Keep each change small and local.

### 4.1 Vanilla JS / any framework (direct calls)

```js
// Rewarded: user tapped "Get extra life". Grant the reward ONLY in the callback.
button.addEventListener('click', () => {
  Platformy.showReward('extra_life', (rewarded) => {
    if (rewarded) grantExtraLife();       // true only after the user claimed
    // else: skipped / no ad / disabled by the owner: do nothing, app continues
  });
});

// Interstitial at a natural break, rate-limited
let lastAd = 0;
function onLevelEnd() {
  if (Date.now() - lastAd > 150000) { lastAd = Date.now(); Platformy.showInterstitial('level_end'); }
  showResultScreen();                      // do not wait for the ad
}

// Banner into an existing container (or declaratively in HTML:
//   <div data-platformy-banner data-platformy-placement="home_top"></div>)
Platformy.banner('#ad-slot', { placement: 'home_top' });

// Tasks wall (cross-promotion). Grant the reward in onReward.
Platformy.tasks('#earn-list', { placement: 'earn', onReward: (task) => addCoins(100) });
// or declaratively: <div data-platformy-tasks data-platformy-placement="earn"></div>

// Task ad (visit/subscribe for a reward), same contract as showReward
Platformy.showTask('bonus_task', (done) => { if (done) addCoins(50); });
```

Notes: `showReward`'s returned promise resolves `true` when the ad is shown, not when claimed; use the callback. Do not call `show*` in a loop or on render. Inside a framework, call banner/tasks after the container is mounted (see below).

### 4.2 React

**Init happens in `index.html`, not in React** (Step 2: script tags right after `telegram-web-app.js`, with `Platformy.init(...)`). React child effects run before a provider's effect, so initializing inside a provider would leave early `banner`/`tasks` calls without a pubId (they render nothing). The provider below only exposes the API; if `window.Platformy` does not exist yet (script still loading), the wrappers push the call into `window.PlatformyQueue`, which is drained at `init()`.

```tsx
// platformy.tsx  (no init here)
import { createContext, useContext, useMemo, type ReactNode } from 'react';

type P = {
  showReward: (placement: string) => Promise<boolean>;      // resolves true only if the user claimed
  showInterstitial: (placement: string) => Promise<boolean>;
  goal: (name: string, props?: Record<string, unknown>) => void;
  track: (name: string, props?: Record<string, unknown>) => void;
  purchase: (o: { amount: number; currency: string; item?: string; slug?: string }) => void;
  banner: (el: HTMLElement | string, placement: string) => void;
  tasks: (el: HTMLElement | string, placement: string, onReward?: (t: any) => void) => void;
};
const w = () => (typeof window !== 'undefined' ? (window as any) : undefined);
// call the SDK if loaded, otherwise queue the call (drained at Platformy.init)
function call(method: string, ...args: unknown[]) {
  const win = w(); if (!win) return;
  if (win.Platformy) return win.Platformy[method](...args);
  (win.PlatformyQueue = win.PlatformyQueue || []).push([method, ...args]);
}
const Ctx = createContext<P | null>(null);

export function PlatformyProvider({ children }: { children: ReactNode }) {
  const api = useMemo<P>(() => ({
    showReward: (placement) => new Promise((res) => {
      if (!w()) return res(false);
      call('showReward', placement, (ok: boolean) => res(!!ok));   // callback fires with true only after the claim
    }),
    showInterstitial: async (placement) => {
      const p = w()?.Platformy;
      if (!p) { call('showInterstitial', placement); return false; }
      return !!(await p.showInterstitial(placement));
    },
    goal: (n, p) => { call('goal', n, p); },
    track: (n, p) => { call('track', n, p); },
    purchase: (o) => { call('purchase', o); },
    banner: (el, placement) => { call('banner', el, { placement }); },
    tasks: (el, placement, onReward) => { call('tasks', el, { placement, onReward }); },
  }), []);
  return <Ctx.Provider value={api}>{children}</Ctx.Provider>;
}
export const usePlatformy = () => {
  const c = useContext(Ctx);
  if (!c) throw new Error('usePlatformy must be used inside <PlatformyProvider>');
  return c;
};
```

Usage:

```tsx
function ExtraLifeButton() {
  const pf = usePlatformy();
  return <button onClick={async () => { if (await pf.showReward('extra_life')) grantExtraLife(); }}>Extra life</button>;
}
function HomeBanner() {
  const pf = usePlatformy(); const ref = useRef<HTMLDivElement>(null);
  useEffect(() => { if (ref.current) pf.banner(ref.current, 'home_top'); }, [pf]);
  return <div ref={ref} />;
}
function EarnList() {
  const pf = usePlatformy(); const ref = useRef<HTMLDivElement>(null);
  useEffect(() => { if (ref.current) pf.tasks(ref.current, 'earn', () => addCoins(100)); }, [pf]);
  return <div ref={ref} />;
}
```

Wrap the app root once: `<PlatformyProvider>...</PlatformyProvider>`. Do not let React re-render wipe the banner container: keep the `div` stable (no changing `key`). `init` runs exactly once, from the HTML, so StrictMode double effects cannot double-init.

### 4.3 Vue 3 composable

Init in `index.html` as well (Step 2); the composable never inits and queues calls if the SDK is not loaded yet.

```ts
// usePlatformy.ts  (no init here)
const W = () => (typeof window !== 'undefined' ? (window as any) : undefined);
function call(method: string, ...args: unknown[]) {
  const w = W(); if (!w) return;
  if (w.Platformy) return w.Platformy[method](...args);
  (w.PlatformyQueue = w.PlatformyQueue || []).push([method, ...args]);
}
export function usePlatformy() {
  return {
    showReward: (placement: string) =>
      new Promise<boolean>((res) => { if (!W()) return res(false); call('showReward', placement, (ok: boolean) => res(!!ok)); }),
    showInterstitial: async (placement: string) => {
      const p = W()?.Platformy;
      if (!p) { call('showInterstitial', placement); return false; }
      return !!(await p.showInterstitial(placement));
    },
    goal: (name: string, props?: object) => { call('goal', name, props); },
    track: (name: string, props?: object) => { call('track', name, props); },
    purchase: (o: { amount: number; currency: string; item?: string; slug?: string }) => { call('purchase', o); },
    banner: (el: HTMLElement | string, placement: string) => { call('banner', el, { placement }); },
    tasks: (el: HTMLElement | string, placement: string, onReward?: (t: any) => void) => { call('tasks', el, { placement, onReward }); },
  };
}
```
Render banner/tasks in `onMounted` with a template ref.

### 4.4 Goals (analytics and cross-promotion targets)

A goal is a meaningful action. Add one for every action in the catalog (typically 5-15; do not invent actions that do not exist), at the exact place where the action is confirmed (after the server/state confirmed it, not on button click):

```js
Platformy.goal('tutorial_done');
Platformy.goal('level_reached', { level: 5 });     // props are optional, keep them small
Platformy.goal('first_deposit');
```

**Event catalog.** Scan the code for every user action worth rewarding or measuring (planting, crafting, purchases, level-ups, invites, daily login, quests, opening a wallet, ...). Pick stable `snake_case` names (`[a-z0-9_.:-]`, up to 64 chars), call `Platformy.goal('<name>')` at the exact success point, and declare the whole catalog once in `init` with human Russian titles (up to 200 entries, titles up to 80 chars):

```js
Platformy.init({
  pubId: 'YOUR_PUB_ID',
  events: {
    tree_planted: 'Посадил дерево',
    friendship_tree: 'Посадил дерево дружбы',
    wallet_opened: 'Открыл кошелёк',
    level: { title: 'Уровень', numeric: true },   // numeric: the owner can require "reach level N"
  },
});
```

The catalog is sent once per session. It shows in the panel (Integration tab, "App events"; "События приложения" in the Russian panel) and the owner picks any of these events as a task condition. Names not declared still appear (with the raw name as title). List the catalog in the final report.

<!-- event-task:start -->
**Task text for players (`task`).** `title` is a past-tense label for the owner's panel ("Крутанул рулетку"). Players see an imperative call to action instead, so also give each rewardable event a short `task` (up to 30 chars): a string means Russian, or an object per language. Without it the player sees a generic phrase.

```js
wheel_spin: { title: 'Крутанул рулетку', task: { ru: 'Крути рулетку', en: 'Spin the wheel', uk: 'Крути рулетку' } },
```
<!-- event-task:end -->

**Numeric goals.** For progress counters (level, score, streak) pass the current value: `Platformy.goal('level', { value: 5 })`, and mark the entry `numeric: true`. The owner can then set "reached N".

Goal names appear in the owner's panel and can be selected as the action that completes an exchange task of other apps ("count the task when the user did X in your app"). So name them clearly and keep them stable. Use `Platformy.track(name, props)` for other analytics events that are not goals.

### 4.5 Purchases

Find where the app creates a payment. Report it with the **real** amount, currency and item (never invent numbers; read them from the same variables the app uses to create the invoice).

Telegram Stars: call `Platformy.purchase` **right after `openInvoice` and before it closes**. The SDK holds it and records the sale only if Telegram reports `paid`:

```js
const url = await api.createInvoiceLink({ item: 'gold_pack', stars: 100 });   // existing app code
Telegram.WebApp.openInvoice(url, (status) => { if (status === 'paid') grantGold(); });  // existing
Platformy.purchase({ amount: 100, currency: 'XTR', item: 'gold_pack' });      // add this, immediately after openInvoice
```

Do not put `purchase()` inside the `openInvoice` callback (the invoice is already closed by then) and do not call it before `openInvoice`. If the invoice URL is available as a slug you may pass `slug`. Without the call, a payment is still detected (invoice closed as paid) but its amount and item are unknown.

**Where exactly to put it.**
- Stars, app calls `Telegram.WebApp.openInvoice` on this page: `Platformy.purchase(...)` right after `openInvoice` (above); it is recorded only when the callback status is `paid`.
- Stars, invoice opened by another page (wrapper/iframe) or by an engine bridge: call `purchase` in the `paid` branch of the invoice callback on the page that knows the result (`if (status === 'paid') Platformy.purchase({ amount: 100, currency: 'XTR', item: 'gold_pack' })`).
- TON/USDT: after `sendTransaction` resolves (the user signed), never before.
- Search the code for all flows: `openInvoice`, `createInvoiceLink`, `sendTransaction`, `tonConnect`, `invoiceClosed`, `payments`. Every one must be covered.

**Every successful payment must be reported.** Apps that do not load `telegram-web-app.js` (or run their own payment flow without `openInvoice`) cannot be detected automatically, so nothing is captured unless the code calls `Platformy.purchase({ amount, currency, item })` itself: for Stars once the invoice is confirmed paid (the `paid` status of the `openInvoice` callback, or the server's payment confirmation), for TON/USDT after the user signed. In such an app call it at that moment; it is recorded as a client-reported purchase.

**Payments through the bot (`sendInvoice` / `createInvoiceLink`, `successful_payment` arrives at the bot).** Stars payments are detected in the browser automatically (the SDK listens to Telegram's low-level `invoice_closed` event, also when the game runs in a same-origin iframe), but the browser never knows the amount. The bot does: in the bot's `successful_payment` handler, on the bot SERVER, call `POST <api>/api/v1/payments` with the resource secret key (Bearer; the key lives in an environment variable of the bot server, never in client code). No bot token is shared with Platformy. The call is idempotent by `telegramPaymentChargeId` (safe to retry) and merges with the browser's fact of the same payment, so nothing is counted twice:

```js
// Node (grammY / telegraf style), inside the successful_payment handler
const p = ctx.message.successful_payment;
await fetch(`${process.env.PLATFORMY_API}/api/v1/payments`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.PLATFORMY_SECRET_KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    tgUserId: ctx.from.id,
    amount: p.total_amount,                       // Stars: the number of stars as is
    currency: p.currency,                         // 'XTR' | 'TON' | ...
    telegramPaymentChargeId: p.telegram_payment_charge_id,
    invoicePayload: p.invoice_payload,            // optional, used as the item name
    item: 'gold_pack',                            // optional
  }),
}).catch(() => {});                               // never block granting the purchase
```

```python
# Python (aiogram / python-telegram-bot style), inside the successful_payment handler
import os, httpx
p = message.successful_payment
httpx.post(
    os.environ["PLATFORMY_API"] + "/api/v1/payments",
    headers={"Authorization": "Bearer " + os.environ["PLATFORMY_SECRET_KEY"]},
    json={
        "tgUserId": message.from_user.id,
        "amount": p.total_amount,
        "currency": p.currency,
        "telegramPaymentChargeId": p.telegram_payment_charge_id,
        "invoicePayload": p.invoice_payload,
    },
    timeout=5,
)
```

`PLATFORMY_API` is the API host given in the prompt; the key is the one in the panel (Resource -> Integration -> Keys). Response `200 { "result": { "created", "merged", "duplicate", "id" } }`; `401` bad key, `429` rate limited. Optional `invoiceSlug` (the `$slug` of the invoice link, if the bot knows it) makes the merge with the browser fact exact; otherwise the newest browser fact of the same user inside 10 minutes is used. If the project has no bot backend, skip this and rely on `Platformy.purchase()` above.

TON / USDT (own wallet flow): TON Connect events (`wallet_connected`, `tx_sent`, `tx_signed`) are captured automatically, nothing required. To also record the amount and item, call it when the user confirms the transaction (it is emitted immediately and marked as client-reported; on-chain confirmation of TON/USDT amounts is not guaranteed yet, so treat it as unverified):

```js
await tonConnectUI.sendTransaction(tx);                                     // existing
Platformy.purchase({ amount: 1.5, currency: 'TON', item: 'gold_pack' });    // add after the user signed
```

### 4.5.1 Bot analytics: forward the bot's updates (only if the project has a bot backend)

Mini App events are tracked by the SDK. What people do inside the BOT itself (/start and where they came from, commands, messages, buttons, inline queries, blocking and unblocking the bot, join requests of a channel/group) is only visible if the bot backend forwards its Telegram updates. Add ONE middleware/handler on the bot SERVER that sends every incoming update to `POST <api>/api/v1/bot-updates` with the resource secret key (Bearer; the key lives in an environment variable of the bot server, never in client code and never in the repository). Rules:

- Fire and forget: never `await` it in the update path, 2 second timeout, swallow every error. The bot must never slow down or fail because of analytics.
- Forward the raw `Update` object as Telegram gave it (a single object, or an array of up to 100). Do not add or remove fields, do not log them.
- For the bot to receive `my_chat_member` (blocked / unblocked), `chat_member` and `chat_join_request`, they have to be in the bot's `allowed_updates` (grammY: `bot.start({ allowed_updates: [...] })`; webhook: `setWebhook` `allowed_updates`). Add them next to the updates the bot already uses; do not drop any existing one.
- Privacy: Platformy stores only the kind of a message (text, photo, voice...), a length bucket, the command name (not its arguments), the `/start` payload, the callback data and the user's Telegram id, language and Premium flag. Message text, inline query text, names and usernames are never stored (they are dropped on the server).
- Idempotent by `update_id`, safe to retry. Response `200 { "result": { "accepted", "duplicates", "rejected", "payments" } }`; `401` bad key, `429` rate limited (send fewer, bigger batches), `400` bad body.
- A `successful_payment` inside a forwarded update is recorded as a bot payment automatically (the same path as `/api/v1/payments`), so the separate call in 4.5 is then not needed for the bot.

```js
// Node: grammY (telegraf: bot.use(...); node-telegram-bot-api: call push(update) from the webhook handler / each event)
const queue = [];
const push = (update) => { if (queue.length < 500) queue.push(update); };
setInterval(() => {
  if (!queue.length) return;
  const batch = queue.splice(0, 100);
  fetch(`${process.env.PLATFORMY_API}/api/v1/bot-updates`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.PLATFORMY_SECRET_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify(batch),
    signal: AbortSignal.timeout(2000),
  }).catch(() => {});                              // never block, never throw
}, 1000).unref();

bot.use((ctx, next) => { push(ctx.update); return next(); });   // grammY / telegraf: first middleware, not awaited
```

```python
# Python: aiogram 3 (outer middleware) - python-telegram-bot: add a TypeHandler(Update, fn) in group=-1 doing the same push
import asyncio, os, httpx
from aiogram import BaseMiddleware

queue: list[dict] = []

async def flush_loop():
    async with httpx.AsyncClient(timeout=2) as http:
        while True:
            await asyncio.sleep(1)
            if not queue:
                continue
            batch, queue[:] = queue[:100], queue[100:]
            try:
                await http.post(
                    os.environ["PLATFORMY_API"] + "/api/v1/bot-updates",
                    headers={"Authorization": "Bearer " + os.environ["PLATFORMY_SECRET_KEY"]},
                    json=batch,
                )
            except Exception:
                pass                                # never block, never raise

class PlatformyUpdates(BaseMiddleware):
    async def __call__(self, handler, event, data):
        if len(queue) < 500:
            queue.append(event.model_dump(mode="json", exclude_none=True))   # aiogram Update -> the raw dict
        return await handler(event, data)

# dp.update.outer_middleware(PlatformyUpdates()); start asyncio.create_task(flush_loop()) once at startup
```

In the panel the data appears in the app's overview under "Bot" ("Бот" in the Russian panel; starts, new and returning people, commands, messages, blocked share, sources by `/start` payload).

### 4.6 Optional: server-to-server completion of cross-promotion tasks

Only if the owner enabled the tasks wall AND wants server-side confirmation (stronger than the browser event). When your backend knows a user completed the action that other apps ask for (for example the user finished onboarding), confirm it from your backend:

```bash
curl -X POST https://api.platfor.my/api/v1/exchange/complete \
  -H "Authorization: Bearer $PLATFORMY_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tgUserId": 123456789, "goal": "tutorial_done"}'
```

- `tgUserId` = Telegram numeric id of the user (from the verified `initData` on your backend, never from the client body).
- `goal` must be EXACTLY the goal the owner chose in the panel (Exchange -> goal), one of: `start` (first launch of a NEW user; default, also used when `goal` is omitted), an event name you send with `Platformy.goal('<name>')` (letters, digits, `_ . : -`, max 64), `purchase` (user paid), or `wallet_connected`. A different string completes nothing (`reason: "goal_mismatch"`).
- Response `200 { "result": { "completed": 1, "claimIds": [123] } }`. `completed: 0` means there was nothing to complete: no open claim for this user, window expired (default 72 h), goal mismatch (`"reason": "goal_mismatch"`), or already completed (the call is idempotent, safe to repeat). A given user is paid at most once per app for its whole lifetime (a cross-task acquires a user once), so a second claim for a user that partner traffic already brought completes nothing. `401` = bad secret key, `429` = rate limited. `start` is not paid for a user who already used your app before the click.
- The secret key is the one shown in the panel (Resource -> Integration -> Keys). It must live in a server environment variable only, never in the front-end bundle. If the project has no backend, skip this section: the browser SDK `goal()` already completes tasks.

### 4.6.1 Partner check API (integration links)

The owner can create an "integration link" for an app that is not on Platformy (Resource -> Exchange -> "Integration link"; "Ссылка на интеграцию" in the Russian panel). The partner opens `https://platfor.my/x/<token>`, which shows its personal key `pfk_...`, the task slug and a button link into the owner's app tagged `startapp=p_<tag>`. If you are integrating the PARTNER side, check task completion from the partner's backend (read-only, idempotent):

```bash
curl -H "X-Api-Key: $PLATFORMY_PARTNER_KEY" https://api.platfor.my/partner/v1/ping
# {"ok":true,"partner":"Acme","checked_at":"2026-11-10T12:00:00.000Z"}
curl -H "X-Api-Key: $PLATFORMY_PARTNER_KEY" "https://api.platfor.my/partner/v1/check/123456789/level-5?joined_after=2026-11-01"
# {"completed":false,"checked_at":"...","progress":{"current":3,"target":5}}
```

- Key in the `X-Api-Key` header (`?api_key=` works as a fallback but leaks into logs). Server-side only.
- `joined_after` (optional): ISO date or unix seconds; only users who first opened the owner's app after it count. An ISO date-time without a zone is UTC.
- A user who never opened the app inside Telegram returns `completed:false, current:0`. Only the app's own signed (verified, non-test) launches count as a first launch; anything sent without a valid Telegram signature is ignored. Once `completed` is true it stays true; repeated calls are safe.
- 60 requests per minute per key, then `429` with `Retry-After`. Errors are `{"detail": "..."}`: `401` bad or revoked key, `404` unknown task slug, `422` bad `telegram_id` / `joined_after`.
- On the OWNER side nothing extra is needed: the check reads the app's own launches and `Platformy.goal(...)` events. For a numeric task ("reach level 5") send the value: `Platformy.goal('level', { value: 5 })`. Names `purchase` and `wallet_connected` are reserved and cannot be used as a link task event. **The value is reported by the app's client**: a user can send any number between 0 and 999999999 (anything else is ignored), so partners should prefer tasks the app records reliably (an action event) over numeric counters when a reward depends on it.


### 4.7 Platform fit checks
- The banner/wall containers must have a reasonable fixed spot; do not let ads shift the layout when they load (reserve height with CSS if the surrounding UI jumps).
- Dark/light: the SDK ads render with their own dark card; do not fight it.
- Content Security Policy: if the project sets a CSP, allow `script-src https://platfor.my` and `connect-src https://api.platfor.my`; images may come from any https host.

## Step 5: Run in test mode

Enable test mode while you verify, in one of two ways:
- Code: `Platformy.init({ pubId: 'YOUR_PUB_ID', test: true })` (remember to remove `test: true` afterwards), or
- URL: open the app with `?platformy_test=1` appended (no code change; preferred).

In test mode ads are built-in test creatives, nothing is billed or counted in statistics, and the SDK prints every event to the console with the prefix `[Platformy]`. Events are marked `test` and still count for the integration check below.

Run the app (dev server or the owner's staging URL), open it in a browser, and **trigger every ad spot you added** at least once: tap each rewarded button, reach each interstitial moment, open each screen with a banner or wall. Outside Telegram `window.Telegram.WebApp` has no user, which is fine for this check. Then in the page console run `Platformy.debug()`: check `stats.sent > 0`, `stats.lastError === null`, and `placements`/`formats`. If you cannot run a browser, say so to the owner and still do Step 6 using whatever traffic the owner can generate (ask them to open the staging link with `?platformy_test=1` inside Telegram and tap the spots).

## Step 6: Verify with the status endpoint

Poll (every 3-4 s, up to about 2 minutes) the public read-only endpoint (no auth, no personal data):

```
GET https://api.platfor.my/serve/status?pubId=YOUR_PUB_ID
```

Response (the JSON may be wrapped as `{ "result": { ... } }` like other `/serve` endpoints; read `result` when present):

```json
{
  "firstEventReceived": true,
  "sdk": { "ok": true, "lastEventAt": "2026-10-28T12:00:00.000Z", "lastEventHasUser": true, "verifiedShare": 1 },
  "placements": [
    { "name": "extra_life", "format": "rewarded", "enabled": true, "lastSeenAt": "2026-10-28T12:00:00.000Z", "testOnly": true }
  ],
  "exchange": { "mode": "active", "wallMounted": true },
  "goals": [ { "name": "tutorial_done", "lastSeenAt": "2026-10-28T12:00:00.000Z", "withUser": true } ],
  "goalsNeverSent": [],
  "payments": { "seen": false, "real": false }
}
```

Done when ALL are true:
- `firstEventReceived` is `true` and `sdk.ok` is `true`;
- `sdk.lastEventHasUser` is `true` when you tested inside Telegram (the newest event carries a Telegram user). `false` means the launch data does not reach the SDK: fix it with the iframe / `initData` recipes in Step 2 and check again. In a plain desktop browser it is `false`, which is expected;
- every placement you added appears in `placements` (match by `name`);
- every goal you added appears in `goals` (trigger it in the live app inside Telegram) with `withUser: true`. `withUser: false` means the event arrives without the player (it was sent from a server, a bot, a page outside Telegram or a frame without `initData`): it can count for nobody, move the `goal()` call to the Mini App page where `Platformy.init` ran;
- `goalsNeverSent` is empty: it lists events declared in `init({ events })` that have never arrived. Either make their `goal()` call fire or remove them from the catalog;
- `sdk.verifiedShare` is above 0 after a run inside Telegram. `0` means users cannot be verified: `botId` is missing or wrong (Step 2);
- if you added the tasks wall: `exchange.wallMounted` is `true`;
- if you added purchase tracking and could trigger a (test) payment: `payments.seen` is `true` (`seen` = purchase events arrive, test included; `real` = a verified non-test payment exists); if not, say it is untested.

`testOnly: true` is expected at this stage: a placement name appears as soon as any event with it arrives (test mode, desktop browser, or unsigned traffic from outside Telegram), and it stays `testOnly` until the first signed, non-test event from inside Telegram. `lastEventHasUser` is a boolean about the single newest event and contains no personal data. `verifiedShare` stays low when events come from outside Telegram; that is normal in desktop tests.

If a check fails after 2 minutes, go to "Common errors" below, fix, re-run Step 5, poll again. Never report success without a passing status. Show the owner the final status JSON (or the summary of it).

Then remove `test: true` from `init` if you added it (the `?platformy_test=1` URL needs no cleanup). Production stays on the normal config; the owner's panel decides which spots actually run.

## Step 7: Report to the owner

Send this (in the owner's language, plain words, no code unless asked):

```
Done. Platformy is connected to <app name>.

What I added
- Ad spots: <name> - <where in the app> - <type>   (one line each)
- Tasks from other apps: <where> / not added
- Event catalog (name: title): <tree_planted: Посадил дерево, ...>; numeric ones marked
- Tracked actions (no visual change): <goal names>, purchases in <Stars/TON>
- Telegram user reaches Platformy (sdk.lastEventHasUser): yes / not tested
- Files changed: <list>

Checked
- Test run: <what you triggered>. Platformy status: connected, <N> spots seen, <goals seen>.
- Not tested: <anything you could not trigger, e.g. real payments>

What you need to do
1. Deploy the changes (I did not deploy or commit anything).   [or: committed on branch X]
2. In the Platformy panel, open the app, tab "Monetization": each spot is listed there; switch spots on or off as you like.
3. <If tasks wall> Tab "Exchange": one switch turns the exchange on (with every app on the platform); it shows how many people you sent and received. "Exchange settings" holds the rare things (how your app looks to others, when a visit counts).
4. <If bot with inline ads> Set the environment variable PLATFORMY_SECRET_KEY on the server (the key is in the panel).
```

## API cheat sheet

| Call | Purpose |
|---|---|
| `Platformy.init({ pubId, botId?, level?, test?, apiBase? })` -> Promise | start; once per page load. `botId` = numeric part of the bot token (never the token) |
| `Platformy.showReward(placement?, cb?)` | rewarded ad; `cb(true)` only after the user claimed |
| `Platformy.showTask(placement?, cb?)` | visit/subscribe task ad; same callback contract |
| `Platformy.showInterstitial(placement?)` -> Promise<boolean> | full-screen ad at a natural break |
| `Platformy.banner(el_or_selector, { placement? })` | banner into a container |
| `Platformy.tasks(el_or_selector, { placement?, onReward? })` | tasks wall (exchange tasks of other apps + paid tasks) |
| `Platformy.tasks({ placement? })` -> Promise<item[]> | preferred: the same list as data (`id, title, subtitle, image, buttonLabel, label, status, flow`); draw it with the app's OWN task component so it looks native, keep the small `label` («Партнёр») in muted text |
| `item.open()` / `item.check()` (or `Platformy.openTask(id)` / `checkTask(id)`) -> Promise<{ status, reward?, reason? }> | start / check one task; keeps click tracking, serve token and the launch parameter working, never open `link` yourself |
| `Platformy.onTaskCompleted(fn)` | `fn({ taskId, externalId, reward })` once per paid or exchange task completed on this page (UI only; Platformy gives no reward for it) |
| `Platformy.goal(name, props?)` | meaningful action (cross-task target) |
| `Platformy.track(name, props?)` | any custom analytics event |
| `Platformy.purchase({ amount, currency, item, slug? })` | every successful payment: right after `openInvoice` (auto-detected apps) or once the payment is confirmed (apps without `telegram-web-app.js`) |
| `Platformy.flush()` / `Platformy.debug()` | send now / diagnostics |
| `window.PlatformyQueue.push([...])` | calls before the script loaded |
| `data-platformy-banner`, `data-platformy-tasks`, `data-platformy-placement`, `data-platformy-ignore` | declarative slots and privacy opt-out |
| `GET /serve/status?pubId=` | integration check (public) |
| `POST /api/v1/ad/inject`, `POST /api/v1/ad/fetch` (Bearer secret key) | ads in bot replies |
| `POST /api/v1/exchange/complete` (Bearer secret key) | S2S completion of cross-promotion tasks |
| `POST /api/v1/payments` (Bearer secret key) | bot reports `successful_payment` with the amount (idempotent by `telegramPaymentChargeId`) |
| `POST /api/v1/bot-updates` (Bearer secret key) | the bot backend forwards raw Telegram updates (one or an array up to 100) for bot analytics (idempotent by `update_id`) |
| `GET /api/v1/analytics/{overview,events,users,retention,payments,wallets,sources}` (Bearer secret key) | read-only analytics of the app (60 req/min) |
| `GET /partner/v1/check/{telegram_id}/{task_slug}` (X-Api-Key partner key) | partner checks an integration-link task |

Full detail, events and props: <https://platfor.my/agent/sdk-reference.md>

## Analytics API (read-only, pull your own stats)

The app owner (or the app's backend) can read the same numbers as the panel by the app's secret key. Server side only: the key goes into the backend environment (`PLATFORMY_SECRET_KEY`), never into the client bundle or the repository. The key identifies one app and the answer is always that app's data; there is no way to ask for another app.

```bash
BASE=https://api.platfor.my/api/v1/analytics
curl -H "Authorization: Bearer $PLATFORMY_SECRET_KEY" "$BASE/overview?days=30"
curl -H "Authorization: Bearer $PLATFORMY_SECRET_KEY" "$BASE/wallets?from=2026-10-01&to=2026-10-31"
curl -H "Authorization: Bearer $PLATFORMY_SECRET_KEY" "$BASE/users?page=1&pageSize=50&sort=events&country=US"
# {"result":{"range":{"from":"2026-10-12","to":"2026-11-10","days":30}, ...same fields as the panel}}
```

- Endpoints (all `GET`): `/overview`, `/events`, `/users`, `/retention`, `/payments`, `/wallets`, `/sources`.
- Common query: `from` and `to` (`YYYY-MM-DD`, inclusive) or `days` (default 30), `verifiedOnly=true` to count only events with a valid Telegram signature.
- `/users` is paginated (`page`, `pageSize` up to the server cap, `sort=last_seen|events`, filters `country`, `language`, `premium`, `verified`, `source`). Rows carry the raw Telegram `tgUserId` (your own users), activity counters, country, language, source; no names.
- `/wallets` includes `tx` (signed / sent / failed transactions, `volumeTon`, top destinations, daily series) and `balances` (total / median TON of connected wallets, buckets, whales). Transaction amounts are what the app asked the wallet to send and balances are a daily cached snapshot; neither is a blockchain audit. Numbers from unsigned batches are flagged (`unverified`).
- Errors: `401` missing or wrong key, `400` bad range or paging, `429` over 60 requests per minute per key (retry after a few seconds).

## Common errors and fixes

| Symptom | Cause | Fix |
|---|---|---|
| `Platformy is not defined` | SDK script not loaded yet or blocked | script tag order; for early code use `PlatformyQueue`; in Next/SSR only call in the browser; check CSP and network tab |
| No events in status, `firstEventReceived:false` | wrong/missing pubId, `init` not called, ad blocker, CSP `connect-src`, adblock on the SDK URL | check `Platformy.debug()` (`pubId`, `stats.lastError`); verify pubId with the owner; allow the hosts in CSP |
| `stats.lastError` = `HTTP 4xx` | bad pubId | wrong pubId (typo, or the resource id instead of pubId) |
| Placement never shows in status | the call was never executed, the name is invalid (`[a-z0-9_]{1,40}` only; uppercase, dashes, spaces are dropped) or the owner disabled it in the panel | trigger the path in the test run; fix the name |
| Reward granted even without watching | reward granted on the returned promise or outside the callback | grant only when `cb(true)` / `onReward` fires |
| `showReward` does nothing, callback gets `false` | no fill, format or placement disabled by the owner, or ad request failed | expected; the app must continue; in test mode a test ad should appear, if not check `debug().formats` and `placements` |
| Banner empty | container missing at call time (React/Vue before mount), no fill, placement disabled | call in `useEffect`/`onMounted` with the real element; in test mode a test banner shows |
| Banner/wall appears twice or flickers | `init` called twice, or component re-mounted repeatedly | init once (module flag); keep the container stable |
| Purchase has no amount | `purchase()` called before `openInvoice` or inside the close callback | call it right after `openInvoice` and before it closes |
| Purchase missing entirely | invoice cancelled/failed (nothing is recorded by design), or the app uses a payment flow without `openInvoice` or TON Connect | expected for cancelled; for custom flows call `purchase` with currency `TON`/`USDT` where the user confirms |
| Events only from desktop browser, no user ids | not opened inside Telegram, so no `initData` | normal for the dev test; real traffic inside Telegram carries identity |
| Two Telegram scripts / `Telegram` undefined | script order | load `telegram-web-app.js` first, once |
| Console shows nothing | not in test mode | add `?platformy_test=1` |
| Ads cover the UI / users complain | interstitials too frequent or at the wrong moment | cap frequency, show only at natural breaks, never during gameplay |

## Privacy notes

- The SDK collects behavior (sessions, screens, clicks on buttons/links, purchases, wallet events). It never reads text typed into inputs. Click auto-capture records only the visible label (max 50 chars) of the clicked button or link, and for links origin plus path without query string.
- To exclude an element (and everything inside it) from click auto-capture, add the attribute `data-platformy-ignore`. Use it on screens or controls whose labels may contain personal data (names, balances, messages, admin panels):
  `<div data-platformy-ignore> ... </div>`
- The SDK's own ad UI is excluded automatically.
- Never pass personal data in `goal`/`track` props (no names, phone numbers, emails, message texts, raw `initData`). Use ids, counters and enums.
- The signed Telegram `initData` is sent only to Platformy's own API to verify the user; it is never stored raw in the browser. The offline queue keeps events per Telegram user and drops them if a different user opens the app.
- For a bot with a reply that may contain personal data, use `ads.fetch` (fetch-only mode) so the reply text never leaves your server.
- Mention in your final report that the owner's privacy policy should mention analytics and advertising if it does not already.
