aiogram 3 FSM checkout example — full working code
Name → phone → address → confirm. Copy-paste ready. Validation, cancel, state cleanup — the version you actually ship, not the 10-line snippet from the docs.
Every Telegram shop bot needs a multi-step checkout. You ask the user for 3-5 things (name, phone, address, maybe a note) and stage through them one message at a time. aiogram 3's FSMContext is the clean way.
The docs show you the 10-line toy version. This is the production version — validation, cancel command, state cleanup, admin notification on confirm. Tested on Python 3.12 + aiogram 3.4.
The state machine
Four states, one per field, plus a confirm gate so the user reviews before you commit:
from aiogram.fsm.state import State, StatesGroup
class Checkout(StatesGroup):
name = State()
phone = State()
address = State()
confirm = State()
States are declarative. aiogram tracks the user's current state in storage (memory by default; swap to Redis for production — one line).
Starting the flow
From a callback button on the cart (or /checkout command):
from aiogram import Router, F
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message, ReplyKeyboardRemove
router = Router(name="checkout")
@router.callback_query(F.data == "checkout:start")
async def cb_start_checkout(cb: CallbackQuery, state: FSMContext):
# (In a real bot you'd check cart is non-empty here)
await state.set_state(Checkout.name)
await cb.message.answer(
"📝 Checkout — step 1 of 4\n\nWhat's your full name?",
reply_markup=ReplyKeyboardRemove(),
)
await cb.answer()
Step handlers — one per field, guarded by state
Each step validates, stores, and transitions. The StateFilter ensures only messages received while the user is in the right state hit this handler — no cross-talk with other message handlers.
import re
from aiogram.filters import StateFilter
PHONE_RE = re.compile(r"^[\+\d][\d\s\-\(\)]{5,20}$")
@router.message(StateFilter(Checkout.name), F.text)
async def step_name(msg: Message, state: FSMContext):
name = (msg.text or "").strip()
if len(name) < 2 or len(name) > 100:
await msg.answer("Please send a real name (2–100 characters).")
return # stays in Checkout.name, user can retry
await state.update_data(name=name)
await state.set_state(Checkout.phone)
await msg.answer("📞 Step 2 of 4\n\nWhat's the best phone number?")
@router.message(StateFilter(Checkout.phone), F.text)
async def step_phone(msg: Message, state: FSMContext):
phone = (msg.text or "").strip()
if not PHONE_RE.match(phone):
await msg.answer("That doesn't look like a phone number. Digits, + and spaces/dashes only.")
return
await state.update_data(phone=phone)
await state.set_state(Checkout.address)
await msg.answer("📍 Step 3 of 4\n\nDelivery address (street, city, zip — one line is fine).")
@router.message(StateFilter(Checkout.address), F.text)
async def step_address(msg: Message, state: FSMContext):
addr = (msg.text or "").strip()
if len(addr) < 5 or len(addr) > 500:
await msg.answer("Please send a complete address (5–500 characters).")
return
await state.update_data(address=addr)
await state.set_state(Checkout.confirm)
data = await state.get_data()
await msg.answer(
f"🧾 Please confirm\n\n"
f"👤 {data['name']}\n"
f"📞 {data['phone']}\n"
f"📍 {data['address']}\n\n"
f"Reply /confirm to place the order or /cancel to abort.",
)
Confirming and persisting
@router.message(StateFilter(Checkout.confirm), Command("confirm"))
async def confirm(msg: Message, state: FSMContext):
data = await state.get_data()
# Persist to DB / Google Sheets / send to admin here
order_id = save_order(user_id=msg.from_user.id, **data)
await state.clear() # critical — wipes FSM data
await msg.answer(f"✅ Order #{order_id} received. We'll be in touch.")
Cancel — the step most tutorials skip
Users abandon mid-checkout all the time. Without a cancel, their next /start gets routed back into the checkout handler because they're still in Checkout.address state. Confusing.
@router.message(StateFilter(Checkout), Command("cancel"))
async def cancel(msg: Message, state: FSMContext):
await state.clear()
await msg.answer("❌ Checkout cancelled. Your cart was kept.")
Note StateFilter(Checkout) without a specific state — this matches any state inside the Checkout group. Perfect for cancel: works from any step.
Wire it up in bot.py
import asyncio
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage
from handlers.checkout import router as checkout_router
async def main():
bot = Bot(TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher(storage=MemoryStorage()) # Redis in prod
dp.include_router(checkout_router)
await bot.delete_webhook(drop_pending_updates=True)
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
Three things that bit me first time
- Validate before
set_state. If you callset_state(Checkout.phone)before checking the name length, a bad name still advances the flow. Validate first, then update data, then transition. MemoryStorageis dev-only. Restart the process and every in-flight checkout evaporates. Acceptable during development. For production useRedisStorage.from_url(...)— same API, state survives restarts.- Register the state-filtered router first. aiogram processes routers in registration order. If a generic catch-all handler is registered before
checkout_router, the state handler never fires. Put state-scoped routers at the top ofdp.include_router(...)calls.
Beyond the basics
A production checkout usually adds:
- An optional note step (allergies, delivery time) — same pattern, extra state.
- A confirm inline keyboard (Confirm / Cancel buttons) instead of
/confirm. - Admin notification on confirm —
bot.send_message(admin_id, ...)inside theconfirmhandler, wrapped in try/except so a failed admin DM doesn't block the user's success response. - Order persistence to JSON / SQLite / Postgres / Google Sheets.
All four are implemented in the open-source lite template (checkout.py), and the production version adds admin inline keyboard + Google Sheets logger. If you're shipping this for a client, borrowing the whole pattern saves a day.
Related
- aiogram 3 vs python-telegram-bot in 2026 — why aiogram 3's FSM beats
ConversationHandlerfor new projects. - Deploying to Railway — 3 traps — Python 3.13 vs pydantic-core, polling conflict, ephemeral filesystem.
Want the whole order bot, not just checkout?
Catalog + cart + FSM checkout + admin alerts + Google Sheets, Railway-deployable. Lite is free, full is $9 (48h flash: $5 with LAUNCH5).