BUILD YOUR TELEGRAM STARS BUSINESS

Telegram Stars API.
Built for your bot.

Sell Stars and gift Premium from your own bot, shop, or backend. Free Fragment API with Python SDK, REST, and GRAM or USDT on TON.

0% API feeNo API keyPython + REST

API access is free. Fragment purchase prices and network fees still apply.

https://api-stars.duckdns.orgChecking status

Choose your stack, product, payment method, and wallet. Get the matching code and setup files.

QUICK START / SDK 1.4.0

Build your integration

Choose your stack. Get code, environment templates, and a safe first test. Nothing runs in this page.

Never enter real wallet secrets here. Keep credentials on your trusted backend, outside frontend bundles and logs. These downloads contain placeholders only.

Stack
Signing flow
Product
Payment method
Wallet format

24-word wallet: no address or account-index selector needed.

Install
python3 -m pip install fragment-api-dev==1.4.0
Credential-free test
python3 fragment-python.py --test

Download the code, install dependencies, then run --test for one live price request. No credentials or payments. Offline alternative: python3 fragment-python.py --dry-run.

Generated code
View fragment-python.py (65 lines)
# /api/v1/purchases; basic backend step, not a persistent shop or bot.
# Only fulfill confirmed paid orders; --create spends real wallet funds.
# Persist purchase_id with your durable SHOP_ORDER_ID before polling.
import json
import os
import re
import sys

SELECTION = {"product":"stars","amount":50,"payment_method":"gram"}

def required(name):
    value = os.environ.get(name, "").strip()
    if not value or value.startswith("<"):
        raise ValueError(f"Set {name} on your trusted backend")
    return value

def order_payload():
    data = dict(SELECTION)
    data["product"] = os.environ.get("PRODUCT", data["product"])
    data["amount"] = int(os.environ.get("AMOUNT", data["amount"]))
    data["payment_method"] = os.environ.get("PAYMENT_METHOD", data["payment_method"])
    data["username"] = required("TELEGRAM_USERNAME")
    data["idempotency_key"] = required("SHOP_ORDER_ID")
    data["seed"] = required("TON_WALLET_SEED")
    if data["product"] not in ("stars", "premium") or data["payment_method"] not in ("gram", "usdt"):
        raise ValueError("Invalid product or payment method")
    if not (50 <= data["amount"] <= 1000000 if data["product"] == "stars" else data["amount"] in (3, 6, 12)):
        raise ValueError("Invalid amount")
    if not re.fullmatch(r"@[A-Za-z0-9_]{1,32}", data["username"]):
        raise ValueError("Invalid Telegram username")
    if not re.fullmatch(r"[\x20-\x7E]{1,128}", data["idempotency_key"]):
        raise ValueError("SHOP_ORDER_ID must be 1..128 printable ASCII characters")
    return data

def execute(test=False):
    from fragment_api import FragmentAPI
    api = FragmentAPI(base_url=os.environ.get("FRAGMENT_API_URL", "https://api-stars.duckdns.org"))
    if test:
        quote = api.get_price("stars", 50)
        return {"prices": {"gram": quote.prices.gram, "usdt": quote.prices.usdt}, "stale": quote.stale}
    data = order_payload()
    public = {key: data[key] for key in ("product", "username", "amount", "payment_method")}
    check = api.check_availability(**public)
    if not check.available:
        raise ValueError("Recipient unavailable; nothing created")
    return api.create_purchase(**data)

if __name__ == "__main__":
    if sys.argv[1:] == ["--dry-run"]:
        # Offline: imports no SDK, reads no credentials, creates no purchase.
        print(json.dumps({"offline": True, **SELECTION}))
    elif sys.argv[1:] in (["--test"], ["--create"]):
        try:
            test = sys.argv[1] == "--test"
            result = execute(test)
            if test:
                print(json.dumps(result))
            else:
                print(result.purchase_id, flush=True)
                print("Persist this purchase_id with SHOP_ORDER_ID before polling.", file=sys.stderr)
        except Exception:
            # Do not log request bodies, wallet credentials, or raw API errors.
            raise SystemExit("Request failed. Check connectivity/setup. For create: reconcile the same order; do not change its key.")
    else:
        raise SystemExit("Use --test for a live price request or --dry-run offline. --create spends real wallet funds; backend only.")

fragment-python.py

.env.example
View .env.example (10 lines)
# Template only. Set actual values on your trusted backend; never in this page.
# Keep real .env files out of version control, logs, and frontend bundles.
FRAGMENT_API_URL=https://api-stars.duckdns.org
PRODUCT=stars
AMOUNT=50
PAYMENT_METHOD=gram
TELEGRAM_USERNAME=<TELEGRAM_USERNAME>
# One durable, unique shop order ID per logical order. Reuse it for retries.
SHOP_ORDER_ID=<EXISTING_SHOP_ORDER_ID>
TON_WALLET_SEED=<24_WORD_MNEMONIC>

Template only; scripts do not auto-load .env files. Configure environment variables on your backend. Never commit real credentials.

Keep the order. Keep the ID.

This basic sample does not persist orders. Use your durable shop order ID as the idempotency key, then save the returned purchase_id before polling. Printing an ID is not persistence.

Retry the identical request with the same key only after checking your saved order and status. Never create an automatic replacement after a timeout or reconciliation_required. 202 Accepted is not delivery.

Setup and safe recovery checklist
Integration quick start: python / stars / gram

The credential-free --test makes one live GET /api/v1/prices/quote request.
It needs no wallet, username, or order ID, and never creates a purchase or checkout.
Run it after installing dependencies to check connectivity and SDK setup.
--dry-run is separate and fully offline: it checks script startup and selection only.

This basic sample does not persist orders or IDs and does not poll.
It is not a complete bot. The aiogram sample uses the SDK's AsyncFragmentAPI.
For database-backed purchase recovery, use the full starter: https://github.com/slightbasebo/fragment-api-dev/tree/main/examples/starters/aiogram

Install the dependencies, download the code, then run the --test command.
Configure environment variables through your trusted backend or secret manager.
.env.example is a template, not automatically loaded by these scripts. Do not source it.

Only the explicit --create argument sends a purchase and spends real wallet funds.
Use it only for an order whose customer payment your backend has verified.
Never put a secret in the browser, command-line arguments, telemetry, or logs.
For USDT on TON, the payer also needs GRAM for network fees.

Before fulfillment, persist the order and its stable SHOP_ORDER_ID. After create,
persist the returned purchase_id in the same order before polling. Printing is not persistence.
Check availability before charging a customer; the sample rechecks before fulfillment.
Read GET /api/v1/purchases/{purchase_id} to recover an existing purchase.
202 Accepted is queued, not delivered. Mark delivered only at completed.
Stop on failed.

Pause for manual review on reconciliation_required. Never treat it as delivered.
Safe retry: first read the saved purchase_id and status. Never invent a replacement order key.
If the create response was lost, retry the identical request with the same order key.
Do not change the recipient, product, amount, payment method, or wallet on a retry.
On 409, stop and inspect the conflict. On 429, honor Retry-After. After a timeout or
5xx, reconcile first. Do not automatically replace failed or uncertain purchases.

Docs: /docs/quick-start and /docs

202 Accepted means queued — delivery is not complete yet. Save the returned ID and track the original order.

01 / OVERVIEW

What is Fragment API?

Fragment API is a backend API for buying Telegram Stars and gifting Telegram Premium through Fragment. Telegram bots, shops, marketplaces, and services can integrate it through the Python SDK or REST API, pay with GRAM or USDT on TON, and track delivery with one purchase ID.

The API turns Fragment's purchase flow into a small server-to-server interface: create a purchase, store the returned ID, poll the status, and finish only after a terminal result. No API key is required, and the public API does not add an API access fee.

Telegram Stars API

Buy from 50 to 1,000,000 Stars for a supported Telegram username.

Telegram Premium API

Gift 3, 6, or 12 months of Telegram Premium through the same purchase endpoint.

GRAM or USDT on TON

Choose gram or usdt. USDT purchases require a small GRAM balance for TON network fees.

Python SDK and REST

Use typed Python helpers or send ordinary JSON requests from any backend language.

02 / USE CASES

Who uses the Telegram Stars API?

The Telegram Stars API is designed for services that already manage an order and need a reliable backend purchase step. It fits Telegram bots, digital-goods shops, reseller panels, marketplaces, support tools, and automated Premium gifting systems.

BOT

Telegram bots

Turn a confirmed bot order into Stars or Premium and return a final delivery result to the user.

SHOP

Stars stores

Add Telegram Stars to an existing checkout while keeping wallet credentials on a trusted backend.

B2B

Reseller backends

Queue purchases behind your own order IDs and reconcile every attempt through idempotency and polling.

GIFT

Premium gifting

Offer fixed 3, 6, or 12-month Telegram Premium gifts through the same integration pattern.

12 / AI ASSISTED

Integrate with Codex or Claude

The public GitHub repository includes a portable Fragment API integration skill for Codex and Claude. It gives a coding agent the current request fields, wallet rules, examples, status handling, idempotency requirements, and safe retry behavior.

What the skill covers

Telegram Stars, Telegram Premium, GRAM, USDT on TON, Python SDK, REST, wallet selection, polling, and errors.

What it protects

Backend-only wallet secrets, stable idempotency keys, terminal-status checks, and manual reconciliation when the outcome is uncertain.

# Codex
cp -R skills/fragment-api-integration "${CODEX_HOME:-$HOME/.codex}/skills/"

# Claude
cp -R skills/fragment-api-integration "$HOME/.claude/skills/"

Then ask your coding agent: Use $fragment-api-integration to add Telegram Stars purchases to this project.

Open the Codex and Claude integration skill on GitHub ↗

BUILD YOUR NEXT FEATURE

Guides for your stack

See how our own demo integrates the API · Service checks · Changelog

BEFORE YOU INTEGRATE

Answers that matter

Do I need an API key?

No. Public Fragment API endpoints require no API key or signup. Purchase requests still need the inputs for the payment flow you choose.

Is buying Telegram Stars free?

API access has a 0% fee. You still pay the Fragment purchase amount and TON network fees. A USDT purchase also needs GRAM for network fees.

Can I check a recipient before accepting money?

Yes. The availability endpoint needs only product, username, amount, and payment_method. An available result is a point-in-time check, not a reservation.

Does HTTP 202 mean the order was delivered?

No. It means the purchase was accepted. Save purchase_id and track it; only completed confirms delivery.

What should I do after a timeout?

Recover the saved purchase ID, or repeat creation with the same idempotency key and identical fields. Never create an automatic replacement for reconciliation_required.

Can I keep signing in my own wallet?

Yes. Client-signed checkout returns a transaction for your wallet to review and approve. It accepts the payer address and signed result, never your seed.

14 / RESOURCES

Public integration resources

Use the public repository as the source for runnable examples, the REST specification, Python SDK installation, wallet resolver guidance, and integration support. The production API endpoint remains separate from the documentation and source repository.

YOUR NEXT STEP

Add Stars to your bot.

Python, Node.js, another backend, or AI-assisted coding: start with an example that matches your stack.

Get integration examplesTalk to @tondotdev