Imagine a bot that sells 30 days of access to a private Telegram group. A member pays. The bot records the purchase and extends access until January 31.
Then the webhook response gets lost. Telegram retries the update. The bot handles the same payment again and extends access until March 2.
The payment itself was not necessarily duplicated. The mistake was applying its effect twice.
This piece is about that boundary: how to recognize a repeated successful payment, update a membership once, and recover when the application stops halfway through. The example uses one-off Telegram Stars purchases as manual 30-day top-ups. It does not implement a payment endpoint or a full subscription system.
A payment, an update, and an access period are different things
Telegram sends bot updates through webhooks or long polling. For a webhook, Telegram documents that it retries an unsuccessful request, including a non-2xx response. So a retry is something the application has to be ready to receive, even if the first attempt already changed the database.
Two identifiers matter in the example. update_id identifies a Telegram update. It helps recognize a repeated delivery of that update. telegram_payment_charge_id, inside successful_payment, identifies the successful payment. In the Stars flow used below, it also matches the incoming Star transaction ID.
They answer different questions: have I received this update before, and have I already applied this successful payment. Record delivery IDs for diagnostics if that helps, but protect the business action with a stable payment key too.
The example uses (bot_id, telegram_payment_charge_id) as that key and assumes one environment per database. If test and live traffic share storage, include the environment in the key. For external payment providers, choose and scope the payment identifier according to that provider's contract. Do not assume every ID has Telegram's meaning.
Do not use only the member ID or the amount as the key. A member can legitimately pay the same price twice for two different periods. invoice_payload is bot-specified data too. Whether it works as a unique purchase key depends on how you create and reuse invoices.
Keep one exception separate. A successful payment and its refund are different financial events. Telegram's Stars transaction documentation says a refund transaction can use the original transaction's identifier. A global rule that ignores anything with this charge ID could therefore hide a refund. The code below accepts successful payments only. Refunds need their own recorded transitions and policy.
Verify the payment before deduplicating its effect
For a digital membership sold inside a bot, Telegram's digital-goods documentation specifies Telegram Stars. An external checkout with a payment provider is a different integration and must be validated under that provider's rules.
For the native bot flow, check the configured webhook secret_token against the X-Telegram-Bot-Api-Secret-Token request header. Telegram documents this in setWebhook. Do not treat the header as a cryptographic signature of the request body.
Handle pre_checkout_query promptly. Telegram requires an answer within 10 seconds. Accepting pre-checkout is not proof that a payment succeeded. The successful payment arrives afterward, if the transaction succeeds. See answerPreCheckoutQuery.
For a successful_payment message, match the purchase to a server-side order, the expected Telegram recipient, the product, the amount, and the currency. The target group or channel should come from trusted configuration or the order, not from arbitrary request data.
Only after those checks should you apply the payment to the entitlement.
The example assumes these checks have already passed. It does not verify a webhook, create invoices, or validate an order. Never expose its apply_payment function directly as a public payment endpoint.
Put the payment and the entitlement in one transaction
Consider a handler that first writes payment_processed = true, commits, and then updates the membership in a second transaction. If the process stops between those writes, a retry can see the payment as processed and skip it. The member has paid but gets no extension.
The reverse order is risky too: extend access, crash before recording the payment, and the retry can extend it again.
The following self-contained Python example puts three database changes in the same SQLite transaction. It records the successful payment under a unique key. It extends the member's paid-through time if that key is new. It records a task for a separate worker to reconcile Telegram access.
It uses Python's standard sqlite3 module and SQLite 3.24 or newer. Save it as payment_ledger.py and run python3 payment_ledger.py. The database is in memory, so each run starts cleanly. Its records disappear when the process ends. That means this standalone run cannot demonstrate recovery after a restart. Use a persistent database when testing crash recovery.
import sqlite3
from datetime import datetime, timezone
PERIOD = 30 * 24 * 60 * 60
SCHEMA = """
CREATE TABLE IF NOT EXISTS payments (
bot_id INTEGER NOT NULL,
charge_id TEXT NOT NULL,
order_id TEXT NOT NULL,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
amount INTEGER NOT NULL,
currency TEXT NOT NULL,
PRIMARY KEY (bot_id, charge_id)
);
CREATE TABLE IF NOT EXISTS memberships (
bot_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
paid_until INTEGER NOT NULL,
PRIMARY KEY (bot_id, user_id, chat_id)
);
CREATE TABLE IF NOT EXISTS reconciliation_queue (
bot_id INTEGER NOT NULL,
charge_id TEXT NOT NULL,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
PRIMARY KEY (bot_id, charge_id)
);
"""
def apply_payment(db, p, now, simulate_failure=False):
"""p is already verified and matched to the buyer and order."""
facts = (p["order_id"], p["user_id"], p["chat_id"],
p["amount"], p["currency"])
db.execute("BEGIN IMMEDIATE")
try:
inserted = db.execute(
"""INSERT INTO payments VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(bot_id, charge_id) DO NOTHING""",
(p["bot_id"], p["charge_id"], *facts),
).rowcount
if not inserted:
stored = db.execute(
"""SELECT order_id, user_id, chat_id, amount, currency
FROM payments WHERE bot_id = ? AND charge_id = ?""",
(p["bot_id"], p["charge_id"]),
).fetchone()
if stored != facts:
raise ValueError("Conflicting facts for the same charge")
db.execute("COMMIT")
return "duplicate"
if simulate_failure: # Test only: fail after recording the payment.
raise RuntimeError("simulated failure")
membership = db.execute(
"""SELECT paid_until FROM memberships
WHERE bot_id = ? AND user_id = ? AND chat_id = ?""",
(p["bot_id"], p["user_id"], p["chat_id"]),
).fetchone()
previous_end = membership[0] if membership else now
paid_until = max(previous_end, now) + PERIOD
db.execute(
"""INSERT INTO memberships VALUES (?, ?, ?, ?)
ON CONFLICT(bot_id, user_id, chat_id)
DO UPDATE SET paid_until = excluded.paid_until""",
(p["bot_id"], p["user_id"], p["chat_id"], paid_until),
)
db.execute(
"INSERT INTO reconciliation_queue VALUES (?, ?, ?, ?)",
(p["bot_id"], p["charge_id"], p["user_id"], p["chat_id"]),
)
db.execute("COMMIT")
return "applied"
except Exception:
if db.in_transaction:
db.execute("ROLLBACK")
raise
if __name__ == "__main__":
db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript(SCHEMA)
now = 1735689600 # 2025-01-01 00:00 UTC
first = dict(bot_id=1, charge_id="charge-1", order_id="order-1",
user_id=42, chat_id=-100123, amount=100, currency="XTR")
second = {**first, "charge_id": "charge-2", "order_id": "order-2"}
third = {**first, "charge_id": "charge-3", "order_id": "order-3"}
print("first:", apply_payment(db, first, now))
print("replay:", apply_payment(db, first, now))
print("new payment:", apply_payment(db, second, now))
try:
apply_payment(db, third, now, simulate_failure=True)
except RuntimeError:
print("failed transaction: rolled back")
print("retry:", apply_payment(db, third, now))
end = db.execute("SELECT paid_until FROM memberships").fetchone()[0]
print("paid until:", datetime.fromtimestamp(end, timezone.utc).isoformat())
print("payments:", db.execute("SELECT COUNT(*) FROM payments").fetchone()[0])
print("queued:", db.execute("SELECT COUNT(*) FROM reconciliation_queue").fetchone()[0])
The output is:
first: applied
replay: duplicate
new payment: applied
failed transaction: rolled back
retry: applied
paid until: 2025-04-01T00:00:00+00:00
payments: 3
queued: 3
The first two calls use the same charge ID, so they produce one 30-day extension. A separate charge adds another 30 days. One call is also interrupted immediately after the payment insert to test the rollback: the insert is undone, and a later retry can apply the payment. Once all three purchases have been processed successfully, the membership has 90 days of access from January 1.
A matching charge ID is not the only condition for accepting a duplicate. The example also compares the order, recipient, resource, amount, and currency with the stored record. If any of those details conflict, the code raises an error. In production, that conflict should trigger an alert and an investigation.
BEGIN IMMEDIATE starts a write transaction before the code reads or changes the membership. SQLite allows only one writer at a time. As a result, two handlers in this example cannot both read the same expiry and then overwrite each other’s updates. The payment table’s primary key also enforces uniqueness at the database level.
If another writer holds the lock, BEGIN IMMEDIATE may wait or return a busy error, depending on the connection timeout and lock state. The handler must treat that update as unprocessed: retry it according to policy or return an error. It must not acknowledge work that was never saved. Concurrent workers should use separate connections. See SQLite's transaction documentation.
This transaction is specific to SQLite. Another database may need different locking or an atomic update; copying the transaction as written is not enough.
The example makes one business assumption: every new charge sent to the function represents an authorized purchase of another 30 days. It does not detect two separate charges for an order that should have been paid only once. If orders are single-use, enforce that rule within a transaction as well. Keep a record of any extra charge and handle it through reconciliation or a refund under your policy.
When to acknowledge the webhook
Acknowledge a valid successful-payment update after the transaction commits, or after the verified update has been durably queued for later processing. A recognized duplicate can also receive a successful response once its stored details have been checked.
If the database is unavailable and nothing durable has been recorded, return an error and alert the operator. Telegram does not promise unlimited retries: its webhook documentation says it gives up after a reasonable number of attempts. You therefore need a recovery and reconciliation process for updates that could not be applied.
Keep payment deduplication keys for as long as your replay and audit policies require. If you delete them too early, an old notification may be treated as a new purchase.
The queue does not grant access
The reconciliation_queue table acts as an outbox. In the same transaction that changes the entitlement, the example records that the membership needs attention. The script does not implement the worker, create an invitation, call the Telegram API, or confirm delivery.
A worker can later read the current membership state and decide which Telegram action to take. It must account for retries, missing bot permissions, and timeouts. A timeout alone does not tell you whether the action failed: Telegram may have created an invite even though the worker never received the response.
The database transaction cannot make an external Telegram call happen exactly once. Design retry handling for the specific operation, record outcomes, and reconcile uncertain results. Also consider what happens if the membership changes while the worker is acting on an older state. Reading the latest state just before the API call does not eliminate that race. Do not assume that a retried external action is harmless.
Payment confirmation, entitlement update, invite creation, invite delivery, and the member joining are separate states. Tracking them separately makes it easier to investigate a report such as “I paid, but I can’t get in.”
Recurring payments need different rules
For the manual top-ups in this example, the script adds exactly 30 days from the later of two times: the current paid-through time or the processing time. Under that policy, a delayed payment may give the member more access than a calculation based on the original payment date. Choose the policy you intend to offer before adopting the calculation.
Do not apply the same formula automatically to provider-managed renewals. Billing periods, trials, cancellations, and failed attempts may follow different rules. Telegram’s SuccessfulPayment can include an optional subscription_expiration_date for recurring payments. When the payment system supplies an authoritative paid-through date, follow the contract for that flow and prevent older notifications from overwriting newer state. Refunds and revocations also need explicit transitions.
If both Telegram and an external provider report the same purchase, establish a verified mapping between their identifiers. Two notifications do not necessarily represent two purchases. Conversely, matching only the user, amount, and time is not enough to prove they refer to the same transaction.
Tests before accepting payments
Run these against your endpoint and a test payment environment, not only against the isolated database function:
Send the same successful update twice, including concurrently. Check that there is one payment record and one extension.
Send two valid purchases from the same member concurrently. Check that both purchased periods are represented.
Fail after the payment insert but before the membership update. Check that the transaction rolls back and a retry applies the payment.
Stop the process after commit but before the webhook response. Check that a retry does not extend access again.
Reuse a charge ID with conflicting purchase details. Check that the conflict is flagged instead of silently accepted.
Send a refund for a recorded payment. Check that it is handled as a separate transition under your refund policy.
Make Telegram access delivery fail after the database commit. Check that the payment and entitlement remain recorded and that recovery does not require another charge.
The local script demonstrates the transaction boundary. It does not verify your webhook, payment provider, worker, or Telegram permissions.
Finally, deduplicating notifications prevents one recorded payment from extending access twice. It does not prevent a customer from being charged twice. Separate real charges require order-level controls and a reconciliation process.
Top comments (0)