How to build a Telegram bot that accepts Syriatel Cash
A Telegram payment bot opens the order, shows your Syriatel Cash number and amount, then verifies the transaction ID through a hosted gateway. Match on the ID, check the amount as integers, reject reused IDs, and keep the matcher outside the Telegram handlers so the same logic works from a dashboard.
A lot of Syrian shops already sell inside Telegram. The catalog lives in a channel, the customer writes to a private chat, and payment is a Syriatel Cash transfer followed by a screenshot. That chat is fine until two people pay the same amount, or a transfer arrives at 1 a.m. and nobody marks the order until morning. I take the confirmation off the merchant's phone with a Telegram bot that accepts Syriatel Cash: the chat opens an order, the customer pastes the transaction ID after paying, and the bot asks a hosted payment gateway to verify the amount.
I build and run that gateway for Syriatel Cash, and for Sham Cash if you need both. It talks to a number you already own. The Syriatel Cash API is $2 per number per month, setup is same day, and you do not receive source code. A payment bot on top of it starts from $120 one-time. If you are writing the bot yourself, the rest of this article is the matching logic and a Python implementation you can run against the gateway.
The Arabic walkthrough, with the customer-facing copy I use in the chat, is بوت تيليغرام يستقبل دفعات سيريتل كاش. The website checkout version is in Syriatel Cash API: Accept Payments on Your Site. The Arabic store walkthrough is كيف تربط سيريتل كاش بمتجرك الإلكتروني. Here I stay on the bot: polling versus webhook, conversation state, and how not to mark two orders paid from one ID.
What the bot is responsible for
The bot creates an unpaid order, shows your Syriatel Cash number and the exact amount, waits for a transaction ID (رقم العملية), calls the gateway, and updates the order. It should also tell you when a case needs a person.
It does not register the wallet number, and it does not set official Syriatel limits or fees. Those stay between you and Syriatel. Receiving limits differ by account and can change. If you sell high-value items or expect a busy day, confirm the current limits for your number with Syriatel.
Syriatel Cash transfers have no memo or reference field. Do not ask the customer to type an order code into the transfer. After the payment succeeds, the app or the SMS shows a transaction ID. That ID is what they paste into the chat.
You need a bot token from BotFather, a place to store orders, and gateway credentials you receive during setup. Keep the token and the API key in environment variables. A SQLite file is enough to prove the flow. In production I use Postgres and a unique constraint on the transaction ID.
Sandbox access is available on request. I would not open the bot to real customers before you have paid a test amount, pasted the real ID, and also tried a reused ID, a wrong amount, and an ID that is not visible yet.
The flow inside one chat
- The customer sends /buy or taps a product button. Your system stores the amount, a status of awaiting payment, and the Telegram chat id.
- The bot replies with the destination number, the amount in plain numerals, and a short note that the transfer does not need a memo. I repeat the amount in this message. People pay the figure they remember from the channel post, and a small difference is enough to fail the amount check.
- They open Syriatel Cash, usually inside Akrab Ilaik, and transfer to your number.
- They paste the transaction ID in the same chat. Your backend sends that ID to the gateway at the URL you were given (use
YOUR_GATEWAY_URLuntil then). - If the transfer exists, the gateway returns the amount, the time received, and the sender number. The sender number is always returned. Store it on the order; it helps in support. Do not use it as the matching key. People often pay from a sibling's or a colleague's wallet.
- If the ID was already used on another order, reject it and leave this order unpaid. If the transfer is not found yet, do not consume the ID; ask them to wait a moment and try again. If the transfer is found and the amount does not match, flag the order for review and bind the ID to this order so it cannot be reused. If the transfer is found, the amount matches, and the ID is new, mark the order paid, store the ID and sender number, and notify both sides.
The payment window is yours. Some bots give an hour, some keep the order open until the end of the day. Put the rule in the welcome message and in the database.
Two open orders with the same total are fine. The ID distinguishes them. The amount is a check after the transfer is found, not a way to guess which chat should close.
I described the same matching rules for a website in How to Automate Payment Confirmation for Syrian Wallets. The bot adds one extra problem: Telegram can deliver the same message twice, and the customer can paste the ID twice while they wait.
Polling, webhooks, and where the matcher should live
For local development, run_polling on python-telegram-bot is enough. For production, set a webhook on HTTPS and let Telegram push updates. A laptop session that goes to sleep will miss payments; a webhook on a small VPS will not.
Keep the matcher out of the Telegram handlers. The handler should parse the message, load the open order, call one function, and turn the result into a reply. That function is what you reuse from a dashboard button, from a typist pasting an ID off a screenshot, and from a second bot if you later add WhatsApp. If the paid / not found / wrong amount rules live inside the ConversationHandler, they will drift.
Handle Telegram updates idempotently. If the webhook takes too long to answer, Telegram retries. Your unique constraint on transaction_id is the real guard. The customer-facing message should still make sense on a retry: saying "paid" twice is acceptable; marking a second order paid is not.
Compare amounts as integers. Convert both sides with the same rule, then compare. Store the sender number, and do not require it to match the Telegram account.
Notify the merchant after the row is committed. If the notify call fails, retry the notify, not the payment write.
A Python Telegram bot that calls the Syriatel Cash gateway
This is a pattern for talking to the ready-made gateway, not an official Syriatel client. Map YOUR_GATEWAY_URL and the response fields to the values you get at setup. The in-memory uniqueness check is replaced in production by the unique column, and the lookup-then-write step should run in a database transaction.
```python import os from dataclasses import dataclass from typing import Optional
import httpx import psycopg from telegram import Update from telegram.ext import ( Application, CommandHandler, ContextTypes, ConversationHandler, MessageHandler, filters, )
WAITING_TX = 1 GATEWAY_URL = os.environ["GATEWAY_URL"] # placeholder: YOUR_GATEWAY_URL GATEWAY_KEY = os.environ["GATEWAY_API_KEY"] DATABASE_URL = os.environ["DATABASE_URL"]
@dataclass class ConfirmResult: status: str paid: Optional[int] = None sender_number: Optional[str] = None paid_at: Optional[str] = None
def to_int_amount(value) -> int: return int(round(float(value)))
def connect(): return psycopg.connect(DATABASE_URL, autocommit=False)
def lookup_transfer(transaction_id: str) -> dict: # Placeholder response fields: found, amount, receivedAt, senderNumber response = httpx.post( GATEWAY_URL, headers={ "Authorization": f"Bearer {GATEWAY_KEY}", "Content-Type": "application/json", }, json={"transactionId": transaction_id}, timeout=20, ) response.raise_for_status() return response.json()
def confirm_by_transaction_id(order_id: int, transaction_id: str) -> ConfirmResult: tx_id = (transaction_id or "").strip() if not tx_id: return ConfirmResult("bad_payload")
with connect() as conn: with conn.cursor() as cur: cur.execute( """ SELECT id, amount, status FROM orders WHERE id = %s FOR UPDATE """, (order_id,), ) order = cur.fetchone() if not order or order[2] != "awaiting_payment": return ConfirmResult("closed")
cur.execute( "SELECT id FROM orders WHERE transaction_id = %s", (tx_id,), ) if cur.fetchone(): return ConfirmResult("already_used")
# The HTTP call sits outside the open transaction so a slow gateway # does not hold the row lock. Re-check the unique ID before the write. try: payload = lookup_transfer(tx_id) except httpx.HTTPError: return ConfirmResult("gateway_error")
if not payload or not payload.get("found"): return ConfirmResult("not_found")
paid = to_int_amount(payload["amount"]) sender = payload.get("senderNumber")
with connect() as conn: with conn.cursor() as cur: cur.execute( """ SELECT id, amount, status FROM orders WHERE id = %s FOR UPDATE """, (order_id,), ) order = cur.fetchone() if not order or order[2] != "awaiting_payment": return ConfirmResult("closed")
expected = to_int_amount(order[1]) new_status = "paid" if paid == expected else "needs_review" try: cur.execute( """ UPDATE orders SET status = %s, transaction_id = %s, sender_number = %s WHERE id = %s AND transaction_id IS NULL """, (new_status, tx_id, sender, order_id), ) if cur.rowcount != 1: conn.rollback() return ConfirmResult("already_used") conn.commit() except psycopg.errors.UniqueViolation: conn.rollback() return ConfirmResult("already_used")
if new_status == "needs_review": return ConfirmResult("wrong_amount", paid=paid, sender_number=sender) return ConfirmResult( "paid", paid=paid, sender_number=sender, paid_at=payload.get("receivedAt"), )
async def buy(update: Update, context: ContextTypes.DEFAULT_TYPE): amount = 45000 with connect() as conn: with conn.cursor() as cur: cur.execute( """ INSERT INTO orders (chat_id, amount, status) VALUES (%s, %s, 'awaiting_payment') RETURNING id """, (update.effective_chat.id, amount), ) order_id = cur.fetchone()[0] conn.commit()
context.user_data["order_id"] = order_id wallet = os.environ["SYRIATEL_CASH_NUMBER"] await update.message.reply_text( f"Order {order_id}: pay {amount} SYP to Syriatel Cash {wallet}. " "The transfer does not need a memo. After it succeeds, paste the transaction ID here." ) return WAITING_TX
async def receive_tx(update: Update, context: ContextTypes.DEFAULT_TYPE): order_id = context.user_data.get("order_id") if order_id is None: await update.message.reply_text("Send /buy to open an order first.") return ConversationHandler.END
result = confirm_by_transaction_id(order_id, update.message.text or "")
replies = { "paid": f"Payment received. Order {order_id} is now being prepared.", "not_found": "No transfer with that ID yet. Check the number, wait a minute if you just paid, then paste it again.", "wrong_amount": "A transfer is attached to this order, but the amount does not match. We will review it.", "already_used": "That transaction ID was already used on another order. Paste the ID of the new transfer.", "closed": "This order is no longer waiting for payment. Send /buy to start again.", "bad_payload": "Paste the transaction ID as text.", "gateway_error": "Confirmation is delayed. Please paste the ID again in a moment.", } await update.message.reply_text(replies.get(result.status, replies["gateway_error"])) if result.status in {"paid", "wrong_amount", "closed"}: return ConversationHandler.END return WAITING_TX
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE): context.user_data.clear() if update.message: await update.message.reply_text("Cancelled the current order.") return ConversationHandler.END
def main():
app = Application.builder().token(os.environ["TELEGRAM_BOT_TOKEN"]).build() app.add_handler( ConversationHandler( entry_points=[CommandHandler("buy", buy)], states={ WAITING_TX: [MessageHandler(filters.TEXT & ~filters.COMMAND, receive_tx)], }, fallbacks=[CommandHandler("cancel", cancel)], ) ) # Development: app.run_polling() app.run_webhook( listen="0.0.0.0", port=int(os.environ.get("PORT", "8443")), webhook_url=os.environ["TELEGRAM_WEBHOOK_URL"], secret_token=os.environ["TELEGRAM_WEBHOOK_SECRET"], )
if __name__ == "__main__": main() ```
Create the table before you start the process:
``sql CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, chat_id BIGINT NOT NULL, amount INTEGER NOT NULL, status TEXT NOT NULL, transaction_id TEXT UNIQUE, sender_number TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ``
The FOR UPDATE lock and the unique constraint cover the race where two updates for the same ID arrive together. The HTTP lookup is outside the first transaction so a slow gateway call does not hold the lock. After the lookup, the code locks the order again, because the customer may have cancelled, or a dashboard user may have confirmed the same ID, while the request was in flight.
If you prefer aiogram, keep confirm_by_transaction_id and swap only the handler layer. I would not rewrite the matcher to fit a framework.
Cases the chat will throw at you
The first message after a transfer is often a photo of the receipt. In the first version, do not try to read the ID from the image. Reply with a request to copy the transaction ID from the transfer details and paste it as text. You can still type that ID into the dashboard and run the same function.
A customer may paste an old ID, or an ID with a typo, or the ID plus a sentence. If the gateway does not find a transfer, leave the ID unused and ask them to try again. If you consume unknown IDs, a later retry of the correct number can be rejected by mistake.
A late payment is more common in a chat than on a website. The customer starts the transfer, leaves, and comes back after your window closed. Decide this in advance. I start with a manual review and an immediate merchant alert, then either reopen the order or arrange a refund or store credit.
If they pay and never paste the ID, the order stays unpaid. The gateway can see what landed on your number. It does not close orders by guessing an amount.
Keep a manual confirm and reject control. Search by transaction ID before you confirm anything by hand.
Sham Cash, if you add it later, is a second wallet and a second subscription ($5 per account per month), not a switch on the Syriatel plan. Details are in Syriatel Cash API vs Sham Cash API. The bot should record which wallet the order is waiting on, then verify the ID against that wallet.
Cost, setup, and a go-live list
The hosted Syriatel Cash API is $2 per number per month, with no setup fee for a single number. Several numbers in one system are quoted from what you need. The payment bot starts from $120 one-time. Setup is same day once the number is ready and the flow is agreed. The gateway works from outside Syria with no Syrian proxy or VPN, which is the usual case when the bot is hosted abroad.
I do not register the Syriatel Cash number for you. You keep the wallet and the bot; you integrate over REST.
Before real customers use the chat:
- The live number is connected, not a leftover sandbox number.
- An order is created, with an amount and a status, before payment instructions appear.
- The copy shows the exact amount and does not ask for a transfer memo.
- Amounts are compared as integers.
- A transaction ID is stored under a unique constraint, and a reused ID is rejected.
- An ID that is not found yet is left unused.
- A wrong amount is flagged and the ID is bound to that order.
- The sender number is stored and is not required to match the Telegram account.
- A dashboard action can confirm or reject a transfer, including an ID pasted from a screenshot.
- You are notified on
wrong_amount,already_used, and unresolvednot_foundcases. - You have run an exact match, a reused ID, a wrong amount, a missing ID, and a photo message.
Frequently asked questions
Do I need my own Syriatel Cash number?
Yes. The gateway connects an existing number and gives your bot programmatic access to it. Registering the number is not part of the service.
What does the customer type in the bot?
They place the order, transfer the amount you displayed, then paste the transaction ID. There is no memo field on the transfer itself.
Polling or webhook?
Polling is fine while you develop. Use a webhook in production so confirmation does not depend on a single long-running process on your laptop.
Can the bot accept Sham Cash as well?
Yes, as a second wallet with its own subscription. Each order should wait on one wallet at a time.
Is there a setup fee, and can I try this before going live?
No setup fee for a single Syriatel Cash number. The API is $2 per number per month. You can ask for sandbox access first. Setup is same day.
To start, write through the contact form on fayezalshami.com with the wallet type, how many numbers you have, and whether you want the ready-made payment bot or only the gateway under a bot you already run. You can also email fayezalshami.dev@gmail.com.