Telegram
Enable Telegram authentication for customers
Medusa Telegram
Medusa v2 plugin that provides Telegram integration.
Installation
Add the plugin to your project
1pnpm add @nxmad/medusa-telegram
Add your telegram bot token to Copy to clipboard.env
file
1TELEGRAM_BOT_TOKEN=123456789:ABCdefghIJKLmnopQRSTuvwxyz
Add auth provider in Copy to clipboardmedusa.config.ts
123456789101112131415161718modules: [// other modules...{resolve: "@medusajs/medusa/auth",options: {providers: [// other providers...{id: "tma",resolve: "@nxmad/medusa-telegram/tma-auth",options: {token: process.env.TELEGRAM_BOT_TOKEN,},},],},}]
Built-in Medusa auth routes usage example
TMA auth provider verifies that init data is not tampered or malformed. To receive auth identity you need to pass stringified Copy to clipboardinitDataRaw
in the body of the request, e.g.:
1234567import { retrieveLaunchParams } from '@telegram-apps/sdk';const { initDataRaw } = retrieveLaunchParams();medusa.auth.login('customer', 'tma', { initDataRaw });// or...medusa.auth.register('customer', 'tma', { initDataRaw });
Note that Copy to clipboard@telegram-apps/sdk
should be installed separately
Workflow usage example
However, the idea behind TMA assumes that user doesn't not need neither to login nor to register since Telegram account already acts as an identity. So, this package provides Copy to clipboardtmaCustomerWorkflow
that:
- creates auth identity from init data if it doesn't exist;
- creates customer and links it to the identity if it doesn't exist;
- generates Medusa JWT token for existing or newly created customer.
You'll need a custom route to run this workflow, for example:
1234567891011121314151617181920// ./src/api/store/telegram-customer/route.tsimport { tmaCustomerWorkflow } from '@nxmad/medusa-telegram';import { ContainerRegistrationKeys } from '@medusajs/framework/utils';import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"export const GET = async (req: MedusaRequest,res: MedusaResponse) => {const [authType, initRawData = ''] = (req.header('authorization') || '').split(' ');if (authType !== 'tma' || !initRawData) {return res.status(401).json({message: 'Authorization header is missing or invalid',});}const config = req.scope.resolve(ContainerRegistrationKeys.CONFIG_MODULE);const { http } = config.projectConfig;
Note that Copy to clipboardproviderId
should match with provider id registered in Copy to clipboardmedusa.config.ts
Copy to clipboardtmaCustomerWorkflow
workflow returns Medusa JWT token for the customer. You can use it for subsequent API calls from your storefront.
1234567891011import { retrieveLaunchParams } from '@telegram-apps/sdk';const { initDataRaw } = retrieveLaunchParams();const res = await medusa.client.fetch<{ token: string }>('/store/telegram-customer', {headers: {authorization: `tma ${initDataRaw}`,}})medusa.client.setToken(res.token);
Roadmap
- TMA auth provider
- Telegram OAuth2 provider
- Telegram notifications provider