Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions monorepo-builder.yml
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ parameters:
src/Teamleader: 'git@github.com:SocialiteProviders/Teamleader.git'
src/Teamweek: 'git@github.com:SocialiteProviders/Teamweek.git'
src/Telegram: 'git@github.com:SocialiteProviders/Telegram.git'
src/TelegramWebApp: 'git@github.com:SocialiteProviders/TelegramWebApp.git'
src/Tailscale: 'git@github.com:SocialiteProviders/Tailscale.git'
src/ThirtySevenSignals: 'git@github.com:SocialiteProviders/37Signals.git'
src/Threads: 'git@github.com:SocialiteProviders/Threads.git'
Expand Down
97 changes: 97 additions & 0 deletions src/TelegramWebApp/Provider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php

namespace SocialiteProviders\TelegramWebApp;

use Illuminate\Support\Facades\Validator;
use InvalidArgumentException;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;

class Provider extends AbstractProvider
{
/**
* Unique Provider Identifier.
*/
public const IDENTIFIER = 'TELEGRAMWEBAPP';

/**
* {@inheritdoc}
*/
public static function additionalConfigKeys(): array
{
return [];
}

protected function getAuthUrl($state): string
{
return null;
}

protected function getTokenUrl(): string
{
return null;
}

/**
* {@inheritdoc}
*/
protected function getUserByToken($token)
{
return null;
}

/**
* {@inheritdoc}
*/
protected function mapUserToObject(array $user)
{
$name = trim(sprintf('%s %s', $user['first_name'] ?? '', $user['last_name'] ?? ''));

return (new User())->setRaw($user)->map([
'id' => $user['id'],
'nickname' => $user['username'] ?? $user['first_name'],
'name' => !empty($name) ? $name : null,
'avatar' => $user['photo_url'] ?? null,
]);
}

/**
* {@inheritdoc}
*/
public function user()
{
$data = $this->request->query();

if (!$this->validateTelegramHash($data)) {
throw new InvalidArgumentException('Invalid Telegram WebApp data');
}

$userString = $data['user'] ?? null;
if (!$userString) {
throw new InvalidArgumentException('User data not found in Telegram WebApp response');
}

$telegramUser = json_decode($userString, true);
if (!$telegramUser) {
throw new InvalidArgumentException('Invalid user data format');
}

return $this->mapUserToObject($telegramUser);
}

private function validateTelegramHash(array $data): bool
{
$sign = $data['hash'];

$checkString = collect($data)
->except('hash')
->sortKeys()
->transform(fn ($v, $k) => "$k=$v")
->join("\n");

$secret = hash_hmac('sha256', $this->clientSecret, 'WebAppData', true);
$calculatedHash = bin2hex(hash_hmac('sha256', $checkString, $secret, true));

return hash_equals($sign, $calculatedHash);
}
}
74 changes: 74 additions & 0 deletions src/TelegramWebApp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# TelegramWebApp

```bash
composer require socialiteproviders/telegramwebapp
```

## Installation & Basic Usage

Please see the [Base Installation Guide](https://socialiteproviders.com/usage/), then follow the provider specific instructions below.

## Configuration

First of all, you must create a bot by contacting [@BotFather](http://t.me/BotFather) (https://core.telegram.org/bots#6-botfather)

Next you must add WebApp script to your page, please see the [Initializing Mini Apps Guide](https://core.telegram.org/bots/webapps#initializing-mini-apps).

> Don't forget to set your website URL using `/setdomain`

Then, you need to add your bot's configuration to `config/services.php`. The bot username is required, `client_id` must be `null`. The provider will also ask permission for the bot to write to the user.

```php
'telegramwebapp' => [
'client_id' => null,
'client_secret' => env('TELEGRAM_TOKEN'),
'redirect' => env('TELEGRAM_REDIRECT_URI'),
],
```

### Add provider event listener

#### Laravel 11+

In Laravel 11, the default `EventServiceProvider` provider was removed. Instead, add the listener using the `listen` method on the `Event` facade, in your `AppServiceProvider` `boot` method.

* Note: You do not need to add anything for the built-in socialite providers unless you override them with your own providers.

```php
Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
$event->extendSocialite('telegramwebapp', \SocialiteProviders\TelegramWebApp\Provider::class);
});
```
<details>
<summary>
Laravel 10 or below
</summary>
Configure the package's listener to listen for `SocialiteWasCalled` events.

Add the event to your `listen[]` array in `app/Providers/EventServiceProvider`. See the [Base Installation Guide](https://socialiteproviders.com/usage/) for detailed instructions.

```php
protected $listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
// ... other providers
\SocialiteProviders\TelegramWebApp\TelegramWebAppExtendSocialite::class.'@handle',
],
];
```
</details>

### Usage

You should now be able to use the provider like you would regularly use Socialite (assuming you have the facade installed):

```php
return Socialite::driver('telegramwebapp')->redirect();
```

### Returned User fields

- ``id``
- ``first_name``
- ``last_name``
- ``username``
- ``photo_url``
18 changes: 18 additions & 0 deletions src/TelegramWebApp/TelegramWebAppExtendSocialite.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace SocialiteProviders\TelegramWebApp;

use SocialiteProviders\Manager\SocialiteWasCalled;

class TelegramWebAppExtendSocialite
{
/**
* Register the provider.
*
* @param \SocialiteProviders\Manager\SocialiteWasCalled $socialiteWasCalled
*/
public function handle(SocialiteWasCalled $socialiteWasCalled)
{
$socialiteWasCalled->extendSocialite('telegramwebapp', Provider::class);
}
}
41 changes: 41 additions & 0 deletions src/TelegramWebApp/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "socialiteproviders/telegramwebapp",
"description": "Telegram WebApp Authentication Provider for Laravel Socialite",
"license": "MIT",
"keywords": [
"telegram",
"laravel",
"oauth",
"provider",
"socialite",
"webapp",
"telegramwebapp"
],
"authors": [
{
"name": "Kirill Kudryashov",
"email": "rouzoo.pro@gmail.com"
}
],
"support": {
"issues": "https://github.com/socialiteproviders/providers/issues",
"source": "https://github.com/socialiteproviders/providers",
"docs": "https://socialiteproviders.com/telegramwebapp"
},
"require": {
"php": "^8.2",
"socialiteproviders/manager": "^4.4"
},
"extra": {
"laravel": {
"aliases": {
"Socialite": "Laravel\\Socialite\\Facades\\Socialite"
}
}
},
"autoload": {
"psr-4": {
"SocialiteProviders\\TelegramWebApp\\": ""
}
}
}