Telegram Authentication for Website

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1212
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

Telegram Authentication Implementation for Websites

Telegram Login Widget lets users login to your site via their Telegram account without OAuth2 redirects. User clicks button, Telegram opens confirmation dialog, site receives signed data. No password, no email—just Telegram ID.

Unlike classic OAuth2, Telegram doesn't redirect to its site. Auth happens via:

  1. Widget mode—JavaScript widget embedded on page
  2. Redirect mode—link to t.me/BotName?start=auth

Signed data passes to client, which sends to server for verification.

Creating a Bot

  1. Open @BotFather in Telegram
  2. /newbot → enter name and username
  3. Save Bot Token (format: 123456:ABCdef...)
  4. Set domain: /setdomain → select bot → specify domain (e.g., example.com)

Installing Widget

<script
  async
  src="https://telegram.org/js/telegram-widget.js?22"
  data-telegram-login="YourBotName"
  data-size="large"
  data-auth-url="https://example.com/auth/telegram/callback"
  data-request-access="write">
</script>

Parameter data-auth-url is where Telegram redirects with auth parameters. Parameter data-request-access="write" requests permission to send messages.

Alternative—callback via JavaScript:

<script
  src="https://telegram.org/js/telegram-widget.js?22"
  data-telegram-login="YourBotName"
  data-size="large"
  data-onauth="onTelegramAuth(user)"
  data-request-access="write">
</script>

<script>
function onTelegramAuth(user) {
    fetch('/auth/telegram/token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
        body: JSON.stringify(user),
    }).then(r => r.json()).then(data => {
        if (data.redirect) window.location.href = data.redirect;
    });
}
</script>

Verifying Signature on Server

Critical step. Telegram data is signed with HMAC-SHA256. Without verification, attacker can send arbitrary data:

class TelegramAuthController extends Controller
{
    public function callback(Request $request): RedirectResponse
    {
        $data = $request->only(['id','first_name','last_name','username','photo_url','auth_date','hash']);

        if (!$this->verifyTelegramHash($data)) {
            abort(422, 'Invalid Telegram signature');
        }

        // Check freshness: auth_date not older than 5 minutes
        if (abs(time() - $data['auth_date']) > 300) {
            abort(422, 'Stale authorization data');
        }

        $user = $this->findOrCreateUser($data);
        Auth::login($user, remember: true);

        return redirect()->intended('/dashboard');
    }

    private function verifyTelegramHash(array $data): bool
    {
        $receivedHash = $data['hash'];
        unset($data['hash']);

        ksort($data);
        $dataCheckString = implode("\n", array_map(
            fn($k, $v) => "{$k}={$v}",
            array_keys($data),
            array_values($data)
        ));

        // Key is SHA256 of Bot Token
        $secretKey = hash('sha256', config('services.telegram.bot_token'), true);
        $calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey);

        return hash_equals($calculatedHash, $receivedHash);
    }

    private function findOrCreateUser(array $data): User
    {
        return User::updateOrCreate(
            ['telegram_id' => $data['id']],
            [
                'name'   => trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? '')),
                'avatar' => $data['photo_url'] ?? null,
            ]
        );
    }
}

Database Schema

Telegram doesn't provide email. Need telegram_id field (bigint, unique). Username can change—update on each login:

Schema::table('users', function (Blueprint $table) {
    $table->bigInteger('telegram_id')->nullable()->unique();
    $table->string('telegram_username')->nullable();
});

Timeline

Stage Time
Bot creation, domain setup 0.5 day
Signature verification + API endpoint 1 day
Frontend widget 0.5 day
Migrations, tests 0.5 day

Total: 2.5–3.5 days.