Created
April 1, 2025 10:45
-
-
Save sadiqsalau/53c0e7f90c7ad692195137781803a263 to your computer and use it in GitHub Desktop.
PHP / Laravel Validate Telegram WebAppData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Base64Url\Base64Url; | |
use Elliptic\EdDSA; | |
// composer require simplito/elliptic-php spomky-labs/base64url | |
class TelegramValidator { | |
/** | |
* Check if is valid WebAppData | |
* @param string $webAppData | |
* @return bool | |
*/ | |
public static function isValidWebAppData(string $webAppData) | |
{ | |
/** Calculate Secret */ | |
$secret = hash_hmac( | |
"sha256", | |
env('TELEGRAM_BOT_TOKEN', ''), | |
"WebAppData", | |
true | |
); | |
parse_str($webAppData, $data); | |
$hash = $data["hash"]; | |
$check = collect($data) | |
->except('hash') | |
->sortKeys() | |
->map(fn($v, $k) => $k . '=' . $v) | |
->implode("\n"); | |
$compare = hash_hmac('sha256', $check, $secret); | |
return hash_equals($hash, $compare); | |
} | |
/** | |
* Check if is valid Ed25519 WebAppData | |
* @param string $webAppData | |
* @return bool | |
*/ | |
public static function isValidEd25519WebAppData(string $webAppData) | |
{ | |
parse_str($webAppData, $data); | |
$prefix = config('telegram.telegram_bot_id') . ":WebAppData\n"; | |
$check = collect($data) | |
->except(['hash', 'signature']) | |
->sortKeys() | |
->map(fn($v, $k) => $k . '=' . $v) | |
->implode("\n"); | |
$message = bin2hex($prefix . $check); | |
$signature = bin2hex(Base64Url::decode($data["signature"])); | |
$ec = new EdDSA('ed25519'); | |
$key = $ec->keyFromPublic( | |
config('telegram.telegram_public_key') | |
); | |
return $key->verify($message, $signature); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment