PHP code example of 021 / telegram-validation

1. Go to this page and download the library: Download 021/telegram-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

021 / telegram-validation example snippets


$token = 'YOUR_BOT_TOKEN';

// Short with helper function
use function Telegram\Validation\Helpers\validate_wa_init_data;

$isValid = validate_wa_init_data('query_id=...', $token);

// Expanded with class
use Telegram\Validation\WebAppInitData;

$validator = new WebAppInitData($token);
$isValid = $validator->validate('query_id=...');

$token = 'YOUR_BOT_TOKEN';
$input = ['auth_date' => 666, /*...*/]; // request input

// Short with helper function
use function Telegram\Validation\Helpers\validate_login_widget;

$isValid = validate_login_widget($input, $token);

// Expanded with class
use Telegram\Validation\LoginWidget;

$validator = new LoginWidget($token);
$isValid = $validator->validate($input);

$token = 'YOUR_BOT_TOKEN';
/** 
 * @link https://core.telegram.org/bots/webapps#webappinitdata
 * @var \Telegram\Validation\Entities\WebAppInitData $webAppInitData 
 */
$webAppInitData;

// Short with helper function
use function Telegram\Validation\Helpers\parse_wa_init_data;

$webAppInitData = parse_wa_init_data('query_id=...', $token);

// Expanded with class
use Telegram\Validation\WebAppInitData;

$validator = new WebAppInitData($token);
$webAppInitData = $validator->extract('query_id=...');

// Accessing fields
echo $webAppInitData->queryId; // query_id
echo $webAppInitData->chat->username; // chat.username
echo $webAppInitData->chatType; // chat_type
// ... any other fields

$token = 'YOUR_BOT_TOKEN';
$input = ['auth_date' => 666, /*...*/]; // request input 
/** 
 * @link https://core.telegram.org/widgets/login#receiving-authorization-data
 * @var \Telegram\Validation\Entities\LoginWidgetCallback $loginWidget 
 */
$loginWidget;

// Short with helper function
use function Telegram\Validation\Helpers\parse_login_widget;
$loginWidget = parse_login_widget($input, $token);

// Expanded with class
use Telegram\Validation\LoginWidget;

$validator = new LoginWidget($token);
$loginWidget = $validator->extract($input);

// Accessing fields
echo $loginWidget->firstName; // first_name
echo $loginWidget->lastName; // last_name
/** @var \Carbon\CarbonInterface $carbon */
$carbon = $loginWidget->authDate; // auth_date