Plenty of shoppers live in Telegram and skim past marketing email. Chat'N'Sell turns an existing online store into a shop inside Telegram: a bot plus a Mini App storefront built from the store's own catalogue, with payment on the store's own checkout.
This post is about the Magento 2 connector. Magento gives an integrator plenty of machinery: integrations, ACL, declarative schema, fieldsets, CSP. Most of it helped. A few pieces surprised us.
The constraint: a thin connector, not a second shop
The store stays the source of truth, and all the logic lives in our service. The bot, the storefront, broadcasts and bot discounts are configured in the Chat'N'Sell dashboard; the module has no settings for any of them. It has four jobs:
- let Chat'N'Sell read the catalogue with credentials the merchant can revoke;
- report product, stock, category and bot order changes;
- open carts built in the bot in the store's own checkout;
- tag the orders that came from the bot.
It needs Magento Open Source or Adobe Commerce 2.4.6 or newer, PHP 8.1 or newer, and Magento cron.
Pairing: an integration created after the save commits
The merchant pastes a one-time code (CNS-XXXX-XXXX) from our dashboard into Stores → Configuration → Chat'N'Sell. We store only an HMAC of the code, valid for 24 hours, and the module's config backend model blanks the field before it is saved.
Pairing creates (or reuses) an API integration named "Chat'N'Sell" limited to the catalogue and store settings ACL resources the sync needs to read. Each pairing issues a fresh access token, so moving the store to another account revokes what the old one held. The module sends us the four OAuth credentials, the store view code and the base URL, and we call the store back before accepting: store/storeConfigs must know the store view, and a one-item products read must succeed, so a missing Catalog ACL fails at pairing instead of later in a background job. We answer with a signing secret, which the module keeps encrypted in config.
Our first version paired inside the config save, and every pairing failed with "A consumer having the specified key does not exist": when we called back, the integration and its token were still uncommitted. Now the code's format is checked up front and pairing runs after the commit:
$code = trim((string) $this->getValue());
$this->setValue('');
if ($code !== '') {
$this->pairing->assertCode($code);
// ...
$this->_getResource()->addCommitCallback(function () use ($code, $storeCode) {
try {
$account = $this->pairing->pair($code, $storeCode);
// ...success message
} catch (LocalizedException $e) {
$this->pairing->recordFailure($e->getMessage());
A failed pairing's reason is kept for the Status field, so the merchant sees why.
Reading the catalogue: REST, OAuth 1.0a and configurables
The module doesn't serialise products. Our server reads the catalogue through Magento's own REST API with the integration's credentials.
Every request is signed with OAuth 1.0a (HMAC-SHA256) using all four credentials. A bearer token would be simpler, but since 2.4.4 Magento accepts integration tokens as standalone bearer tokens only when the merchant switches that on; OAuth works on every 2.4.x install as shipped. One detail mattered: the query string is encoded exactly as it was signed, so Magento's check sees the same bytes.
Mapping works like this:
- simple and virtual products that are visible in catalogue or search become a product with one variant;
- a configurable becomes one product with a variant per enabled child, and its configurable attributes (Color, Size) become the options;
- children that are "not visible individually" only ever appear as variants.
Children for a whole batch of configurables are fetched together, 100 ids per call. One PHP trap: array_keys() turns a size of "40" into the integer 40, so option values are cast back to strings. Each variant also keeps the attribute ids and option ids it was built from, because checkout needs exactly those:
$parentSku = $variant['magento']['parent_sku'] ?? null;
$body = ['cartItem' => ['quote_id' => $maskedId, 'qty' => (int) $item->quantity, 'sku' => $parentSku ?: $variant['sku']]];
if ($parentSku) {
$body['cartItem']['product_option'] = ['extension_attributes' => [
'configurable_item_options' => $variant['magento']['options'] ?? [],
]];
}
Store views matter too. The sync reads the paired view's website, media URL, link URL and base currency, and only products enabled and assigned to that website go to the bot. Prices are the regular price or an active special price; catalog price rules and tier prices are left to Magento's checkout, where the shopper pays anyway. When a category name repeats under different parents, it carries its path ("Women › Tops › Jackets") so shoppers can tell them apart.
Observers write, cron sends
Saving a product must never wait on our API. So every observer that reports something (products, stock items, categories, bot orders, tracking numbers) only inserts a row into a chatnsell_outbox table declared in db_schema.xml. Nothing is queued while the store isn't paired, and a failed insert is logged, never thrown.
Shoppers see configurables, but stock lives on the simple children, so product and stock events carry the configurable parents' SKUs. The stock observer only queues when qty or is_in_stock actually changed.
A cron job runs every minute and sends the queue in batches of 100, signed with HMAC-SHA256 over timestamp.body in an X-ChatNSell-Signature header. If a batch fails, its rows get one more attempt counted and the run stops; after ten attempts a row is left alone. Sent rows are kept for seven days.
On our side the timestamp must be within five minutes, a batch's SKUs and their parents are deduplicated into re-sync jobs, and a category change triggers an incremental pass over the last day instead of guessing which products moved. Underneath sits a safety net: an incremental sync every half hour and a full one nightly.
Checkout handoff into the Magento quote
When a shopper taps Checkout in the Mini App, our server creates a guest cart over REST and adds the lines, so stock and option errors show up in the bot before the shopper leaves Telegram. The shopper then opens a signed link to /chatnsell/checkout/handoff on the store: base64url JSON with an HMAC, valid for an hour, carrying the cart's masked id, the shopper's email and name, their Telegram id and any bot-only prices.
The module checks the signature and expiry, resolves the masked id to the quote and puts it in the browser's checkout session with replaceQuote(). If the quote is no longer active (already ordered), the shopper goes to the cart instead of an error page.
REST can't set a custom line price, so bot discounts travel in the payload by cart item id and the module applies them:
foreach ($quote->getAllVisibleItems() as $item) {
if (isset($prices[(int) $item->getId()])) {
$item->setCustomPrice($prices[(int) $item->getId()]);
$item->setOriginalCustomPrice($prices[(int) $item->getId()]);
$item->getProduct()->setIsSuperMode(true);
}
}
Prefilling took a detour. The email and name are set on the quote, but Luma's checkout form reads its state from the checkout-data entry in the browser's mage-cache-storage. So the handoff page writes that entry, expires mage-cache-sessid and only then redirects, so the form and the minicart both show this cart. Hyvä Checkout and other one-step checkouts get the cart but may not show the prefill. Payment, shipping and tax stay Magento's.
Attribution: when the fieldset is not enough
Bot orders are marked by a chatnsell_telegram_user_id column that the module adds to quote and sales_order. The textbook way to carry it from cart to order is a sales_convert_quote fieldset. We added one, and orders still arrived without it: QuoteManagement rebuilds the order with mergeDataObjects(), which keeps only the fields OrderInterface has getters for, so the custom column came through empty. An observer on sales_model_service_quote_submit_before copies it explicitly:
$quote = $observer->getEvent()->getQuote();
$order = $observer->getEvent()->getOrder();
$telegramUser = $quote ? (string) $quote->getData('chatnsell_telegram_user_id') : '';
if ($order && $telegramUser !== '') {
$order->setData('chatnsell_telegram_user_id', $telegramUser);
}
That column is also the privacy boundary: the order observer ignores any order without it. For tagged orders it reports the new order, then only changes to its state, status, totals, payments or refunds, plus new tracking numbers, so the shopper gets updates in Telegram.
Widget, CSP and leaving cleanly
Once paired, the module adds our storefront widget (a Telegram popup and launcher, designed in the dashboard) to before.body.end and removes it in checkout_index_index: payment pages shouldn't load scripts they don't need. A csp_whitelist.xml adds our host to script-src, style-src, connect-src and img-src, so the widget loads under Magento's Content Security Policy.
module:uninstall --remove-data should delete the module's settings, including the signing secret, and the "Chat'N'Sell" integration, which revokes the credentials we hold. A Setup\Uninstall class would be the obvious place, but Magento 2.4.9 no longer runs those for modules that only use declarative schema. So the cleanup is the revert() of an empty data patch. Reverts run in a transaction and can't drop tables, so the outbox table and the attribution columns go away the declarative way, with module:disable and setup:upgrade.
What we'd tell anyone building for Magento
- Do work that needs committed data in a commit callback, not inside the config save.
- Sign REST calls with OAuth 1.0a; standalone bearer tokens are off by default.
- Send events with the configurable parent's SKU: shoppers see parents, stock lives on children.
- A
sales_convert_quotefieldset doesn't carry a custom column throughQuoteManagement. Copy it yourself. - Luma's checkout prefill lives in browser storage, not only in the quote.
- For uninstall cleanup in a declarative-schema module, use a revertible data patch.
If you run a Magento store, the connector is free on the Adobe Commerce Marketplace. The bot, storefront, broadcasts and discounts are all set up in the Chat'N'Sell dashboard, with a free plan to start. The step-by-step guide is here: Telegram shop for Magento. Questions about the internals are welcome in the comments.
Top comments (0)