Giter VIP home page Giter VIP logo

tgwebvalid's Introduction

Library for Telegram Web App User Validation and Telegram Login Widget for PHP

Testing Status Minimum PHP Version Latest version License

Documentation StandWithUkraine StandWithUkraine

StandWithUkraine

About TgWebValid

They say we are cool 😎

⭐️ Support us, give us a star on GitHub and become our sponsor 😊

🙏 Please let us know on GitHub if something isn't working for you or if you need additional functionality


User authentication occurs by encrypting the received, raw, user data and comparing it with the hash provided by the telegram. A failed check can be equated with a possible attempt to bypass or hack the system.

The library verifies users Telegram Login Widget and Telegram Web App

WARNING: Use user data only after successful authentication

To quickly and safely verify a user, we recommend following a few simple steps

Installation

You can install the TgWebValid library through the composer package manager by executing the command

composer require tg/tgwebvalid

Add the --no-dev flag to install only the dependencies needed to run your project in a production environment.

Using

The first thing you need to do is to set in the constructor of the TgWebValid class the token of the Telegram bot on behalf of which authentication is performed by default. And store the result in a variable.

Also, if you want to throw an exception in case of a validation error, set the second parameter to true. But be sure to use the try catch structure

<?php

use TgWebValid\TgWebValid;

include './vendor/autoload.php';

$tgWebValid = new TgWebValid('TELEGRAM_BOT_TOKEN', false);

If your project uses multiple bots, you can easily interact with them, just add them all

<?php

$tgWebValid->addBot('secondary', 'TELEGRAM_BOT_TOKEN_2');
$tgWebValid->addBot('minor', 'TELEGRAM_BOT_TOKEN_3');

Getting a bot to work is easy. Specify the name of the bot to work with, or leave the argument empty to get the default bot

$bot = $tgWebValid->bot('minor');

Next, you need to decide on the type of authentication you need to do.

Telegram Web App authentication

To perform this type of verification, you should use the validateInitData method. Which argument accepts data for processing. If the validation is successful, you will be returned an InitData object with the data, or false if the validation fails.

Use the second argument to enable or disable an exception on failed validation

$initData = $bot->validateInitData('query_id=...');

if (!$initData) {
    // validation fails
}

/**
 * The initData object can contain the following data:
 */

// Time opening a web application
$initData->authDate;

// An object containing data about the current user
$initData->user;

// May contain a chat partner data object
$initData->receiver;

// May contain an object with chat data
$initData->chat;

// and other data

Note. Certain data is present depending on the situation, so sometimes it can be null instead of data or a data object. More details in the Telegram official documentation

Telegram Login Widget authentication

To perform this type of check, you should use the validateLoginWidget method. Which argument accepts an array with raw user data. You will be returned a LoginWidget object with the data, or false if the validation fails

Use the second argument to enable or disable an exception on failed validation

$loginWidget = $bot->validateLoginWidget([
    'auth_date' => 1679130118,
    'first_name' => 'Сергій',
    // other fields
]);

if (!$loginWidget) {
    // validation fails
}

/**
 * The LoginWidget object can contain the following data:
 */

// User token
$loginWidget->id;

// User first name
$loginWidget->firstName;

// Username
$loginWidget->username;

// Link to profile photo
$loginWidget->photoUrl;

// Authorization time
$loginWidget->authDate;

// and other data

Note. Certain data is present depending on the situation, so sometimes it can be null instead of data or a data object.

Full example

<?php

use TgWebValid\TgWebValid;
use TgWebValid\Exceptions\BotException;
use TgWebValid\Exceptions\ValidationException;
use Exception;

include './vendor/autoload.php';

try {
    $tgWebValid = new TgWebValid('TELEGRAM_BOT_TOKEN', true);

    // Add bots only when needed
    $tgWebValid->addBot('secondary', 'TELEGRAM_BOT_TOKEN_2');
    $tgWebValid->addBot('minor', 'TELEGRAM_BOT_TOKEN_3');

    $initData = $tgWebValid->bot()->validateInitData('query_id=...');

    var_dump($initData);

} catch (ValidationException $e) {
    // Verification failed
} catch (BotException $e) {
    // The bot name is incorrect
} catch (Exception $e) {
    // Other exceptions
}

Additionally

Our library is autonomous, so it can be used in any frameworks, or without them.

Security

If you discover a security vulnerability in TgWebValid, please create an issue with a detailed description. All security vulnerabilities will be fixed immediately. Pull requests are also welcome.

Assistance

We will be glad if you join the development and improvement of the project. You can create an issue and/or a pull request

License

TgWebValid - is open source software available under the MIT. See the license file for more information.

tgwebvalid's People

Contributors

crazytapok-bit avatar ihorchepurnyi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

tgwebvalid's Issues

It doesn't work

It doesn't work, the data is always invalid.

Steps to reproduce:

  1. I'm using the "Direct Link Web Apps" mode
  2. Frontend side:
    const response = await axios.post('myurl', {
        initData: window.Telegram.WebApp.initData,
    });
  3. Backend side:
    $initData = $_POST['initData'] ?? '';
    $tgWebValid = new TgWebValid('my-bot-token', false);
    $bot = $tgWebValid->bot();
    $validation = $bot->validateInitData($initData);
    if (!$validation) {
        die('Invalid data');
    }

PS: by using the "direct link web app" mode, my initData is:
user=%7B%22id%22%3A10081232%2C%22first_name%22%3A%22Luca%22%2C%22last_name%22%3A%22Patera%22%2C%22username%22%3A%22Lukasss93%22%2C%22language_code%22%3A%22it%22%2C%22is_premium%22%3Atrue%2C%22allows_write_to_pm%22%3Atrue%7D&chat_instance=[REDACTED]]&chat_type=private&start_param=foo&auth_date=1693264973&hash=[REDACTED]
There is no "query_id" param, maybe it can be this? I hope not.

Separate data preparation and validation

In the TgWebValid class, in all methods performing data verification, the logic for data preparation for verification and the verification itself must be separated

Check json for errors

The json_decode function may issue an error if the string passed is not really json, or json but contains syntax errors. Therefore, it is necessary to finalize the handler and check for errors

$assoc = json_decode($data, true);

Upgrade php version to 8.1

Not just update the minimum version in the composer.json file, but make the necessary changes and new language features throughout the library

Get rid of identical Make child classes

Since all child classes are identical in structure and the task they perform, and since typing is used, it is possible to make the main Make class more universal, and fill all data after type checking with ReflectionProperty, which will significantly shorten the code and help to get rid of classes of the same type

Allow to use nesbot/carbon: ^2.67

Hello,

Thank you very much for your package!

I’m trying to use it in a Laravel project, but upgrading to the latest version is challenging because Laravel specifies the following version of Carbon in the composer.json file:

"nesbot/carbon": "^2.67"

Is there any chance you could allow this version in your package?

Upgrade php version to 8.2

Not just update the minimum version in the composer.json file, but make the necessary changes and new language features throughout the library

Fill the Unit project with tests

With tests, development and support becomes simple. After all, it is the tests that help to avoid the possibility of bugs and errors in the development process

Multi-bot usability is required

Sometimes you have to work with several bots within the framework of one project. It would be nice to be able to check all of them without creating new instances of the TgWebValid class

Update README.md

Now the constructor will accept the token, and the method will accept the data. In addition, a new method isLoginValid of verifying a user who logs in through the Telegram Login Widget has been added

Change the architecture to a more understandable and scalable one

Currently, all entities in Entities are children of InitData. In my opinion, the best approach would be to move them to a separate folder. And also make them have the same name, for example, User instead of TgWebUser, etc. This will help to avoid the mess that will certainly be formed when adding a new parent entity. Also, move all classes that somehow correspond to the work of entities to the appropriate folder

Make the README clearer

Reword the README, make it more specific and provide more examples. Also, please translate it into English.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.