PHP code example of alexvkokin / telegram-mini-app-validation

1. Go to this page and download the library: Download alexvkokin/telegram-mini-app-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/ */

    

alexvkokin / telegram-mini-app-validation example snippets




declare(strict_types=1);

use Alexvkokin\TelegramMiniAppValidation\InitDataService;
use Alexvkokin\TelegramMiniAppValidation\WebAppUser;

$token = 'YourBotTokenHere'; // Replace with your bot token

// Fetch the initData string from the request header
$initData = $_SERVER['HTTP_AUTHORIZATION'] ?? '';

try {
    // Create an InitDataService instance
    $initDataService = new InitDataService($token, $initData);

    // Validate the data
    if (!$initDataService->validate()) {
        throw new RuntimeException('Access Denied: User validation failed.');
    }

    // Resolve the user data
    $webAppUser = $initDataService->resolve();

    // Output the resolved user
    header('Content-Type: application/json');
    echo json_encode($webAppUser, JSON_PRETTY_PRINT);
} catch (Exception $e) {
    http_response_code(403);
    echo json_encode(['error' => $e->getMessage()]);
}