Closed ezreza closed 4 months ago
Hello
After you plug in the js code that gives the telegram, the data will be available in the window.Telegram.WebApp.initData field. Keep in mind, data is only available by opening the app. This means that directly opening your program in the browser, data will not be provided. Also, sometimes these data may be missing. Therefore, you need to log the user in at the first login
After successful login, the user ID will be available here
$initData->user->id
thanks for answer
I used Telegram script
<script src="https://telegram.org/js/telegram-web-app.js"></script>
With js I can get the data
"query_id=AAFF&user=%7B%22id%22%3A123456789 ..."
I entered the received data 👆 manually in validateInitData and ID received
The problem I have is that window.Telegram.WebApp.initData is not included in validateInitData to receive data automatically.
Should validateInitData be like this? Data is not received in this way!
$initData = $tgWebValid->bot()->validateInitData('query_id=...');
Oh, the data that is available on the frontend must be transferred to the backend. I can't include them, because it requires a script connection + access to the window object, which is not available with PHP. Therefore, you need to get this data using js, and send it to which will process it and return the result.
Thus, the approximate code will look like this (check for errors)
async function auth (payload) {
try {
const response = await fetch('/auth-telegram-handler.php', {
method: 'POST',
body: payload
})
console.log(response)
} catch (e) {
console.error(e)
}
}
auth({
initData: window.Telegram.WebApp.initData
})
<?php
use TgWebValid\TgWebValid;
use TgWebValid\Exceptions\BotException;
use TgWebValid\Exceptions\ValidationException;
use Exception;
include './vendor/autoload.php';
// Get the data sent by the frontend
$initData = json_decode(file_get_contents('php://input'), true)['initData'] ?? '';
try {
$tgWebValid = new TgWebValid('TELEGRAM_BOT_TOKEN', true);
$initData = $tgWebValid->bot()->validateInitData($initData);
var_dump($initData);
} catch (ValidationException $e) {
// Verification failed
} catch (BotException $e) {
// The bot name is incorrect
} catch (Exception $e) {
// Other exceptions
}
I applied the above but the data was not received again
errors logs
The use statement with non-compound name 'Exception' has no effect in /.../auth-telegram-handler.php on line 6
auth-telegram-handler.php on line 6
use Exception;
I showed you an example of how it all works, then you need to work on the code yourself and make it work the way you need it
Ok, thanks for the help
Glad to help. If you have any questions or suggestions regarding the work of the library, please contact us
Hi Where to get the data for validateInitData ?
I need the user ID of the user to connect to the database
tnx for helping