alexvkokin/telegram-mini-app-validation 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

alexvkokin/telegram-mini-app-validation

最新稳定版本:1.0.0

Composer 安装命令:

composer require alexvkokin/telegram-mini-app-validation

包简介

Validating InitData received via the Mini App

README 文档

README

This PHP library provides functionality for validating users of Telegram Mini Apps based on the initData string sent to the backend by the Telegram Web App. The validation process ensures the integrity of the received data using Telegram's guidelines.

Installation

To install the library, use Composer:

composer require alexvkokin/telegram-mini-app-validation

How It Works

The library performs the following steps:

  1. Parse and decode the initData string received in the request.
  2. Validate the hash using the bot token and the received data.
  3. Resolve the user data into a structured WebAppUser object if the validation is successful.

Code Example

Backend Implementation

Here's how you can use the library in your backend application:

<?php

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()]);
}

Frontend Example

On the frontend, you can send a request to the backend as follows:

const sendDataToBackend = async (initData) => {
    const response = await fetch('https://your-backend-url.com/endpoint', {
        method: 'POST',
        headers: {
            'Authorization': initData
        }
    });

    if (!response.ok) {
        console.error('Failed to validate user:', await response.json());
        return;
    }

    const userData = await response.json();
    console.log('Validated user data:', userData);
};

// Obtain initData from Telegram WebApp
const initData = window.Telegram.WebApp.initData;
sendDataToBackend(initData);

Resources

统计信息

  • 总下载量: 1.77k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Unknown
  • 更新时间: 2025-01-27