🔐 Integrating Telegram Login with Laravel - Gianguyen1234/app-doc GitHub Wiki
Since your app is a Telegram Mini App, users can log in using Telegram OAuth (One-Click Login) instead of traditional email/password.
When a user clicks "Login with Telegram", Telegram sends their user ID, name, and profile picture to your Laravel backend. Your backend then validates the data to prevent tampering.
✅ No need for email/password
✅ Fast login using Telegram account
✅ Secure (Telegram signs the data)
- Open [@BotFather](https://t.me/BotFather) in Telegram.
- Send command:
/mybots - Select your bot, then go to Bot Settings → Allow Login Widget and enable it. ( if you don't see it , just use /setdomain commnad )
- Copy your Bot Token, you’ll need it for Laravel.
In your React Native (Expo) frontend, add a Telegram login button inside your Mini App:
<script async src="https://telegram.org/js/telegram-widget.js?7"
data-telegram-login="YOUR_BOT_USERNAME"
data-size="large"
data-auth-url="https://your-backend.com/auth/telegram"
data-request-access="write">
</script>🔹 Replace YOUR_BOT_USERNAME with your Telegram bot’s username.
🔹 Replace https://your-backend.com/auth/telegram with your Laravel backend API URL.
Create a route to handle Telegram authentication:
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
Route::get('/auth/telegram', function (Request $request) {
// Get Telegram user data
$telegramData = $request->all();
// Validate Telegram's signature (security check)
if (!validateTelegramData($telegramData)) {
return response()->json(['error' => 'Invalid Telegram Data'], 403);
}
// Find or create the user
$user = User::firstOrCreate(
['telegram_id' => $telegramData['id']],
[
'name' => $telegramData['first_name'] ?? 'Unknown',
'email' => $telegramData['id'] . '@telegram.com',
'password' => Hash::make(uniqid()) // Generate random password
]
);
// Generate Laravel Passport / Sanctum token (if needed)
$token = $user->createToken('telegram-login')->plainTextToken;
return response()->json([
'message' => 'Login successful',
'token' => $token,
'user' => $user
]);
});Create a helper function to verify Telegram’s signature:
function validateTelegramData($data)
{
$check_hash = $data['hash'];
unset($data['hash']);
ksort($data);
$secretKey = hash('sha256', env('TELEGRAM_BOT_TOKEN'), true);
$checkString = implode("\n", array_map(fn($k, $v) => "$k=$v", array_keys($data), $data));
$hash = hash_hmac('sha256', $checkString, $secretKey);
return hash_equals($hash, $check_hash);
}✅ Prevents hacking attempts by verifying Telegram’s hash.
Now, when a user clicks Login with Telegram, they will be instantly authenticated inside your Mini App. Your Laravel backend will handle the login and issue an authentication token.