Answer the question
In order to leave comments, you need to log in
How to save user's chat_id?
The question is, I want to save the user's chat_id. Initially, the system does not know it. When he goes to the bot and presses /start, the chat_id appears. How can this caht_id be intercepted from this user and entered into the system. That the user has the given chat_id. I tried to write like this, but when he leaves the site, nothing is saved in the database.
The button for switching to the bot is the following frontend/views/setting.php
<a href="http://telegram.me/HollandSotrudbot?start=<?= $model->token ?>" target="_blank" class="black-btn btn-lg">
<i class="fa fa-paper-plane"></i> Подключить
</a>
public function actionSetting($id)
{
$model = User::findOne($id);
return $this->render('setting', ['model' => $model]);
}
namespace frontend\controllers;
use app\models\User;
use frontend\components\TelegramComponent;
use yii\db\Exception;
use yii\web\Controller;
public function actionWebhook()
{
try{
$content = json_decode(file_get_contents('php://input'));
if(isset($data['message']['chat']['id']))
{
$chatId = $content['message']['chat']['id'];
$message = isset($data['message']['text']) ? $data['message']['text'] : false;
$send = false;
if (strpos($message, '/start') !== false) {
$explode = explode('', $message);
$token = isset($explode[1]) ? $explode[1] : false;
$data = [
'raw' => $token,
'chat_id' => $chatId,
];
$send = Telegram::start($data);
} else {
$send = 'Комманда не найдена. Если Вы уверены в том, что ошибка, обратитесь в тех поддержку';
}
$send = $send ? '' : 'Что-то пошло не по плану. Обратитесь в тех.поддержку';
}
} catch (Exception $e){
$e->getMessage();
}
}
<?php
namespace frontend\models;
use common\models\User;
class Telegram
{
public static function start($data){
return self::login($data);
}
public static function login($data)
{
$token = $data['raw'];
if ($token && $user_id = User::findOne(['token' => $token])) {
$user = User::findOne($user_id->id);
if ($user->telegram_chat_id) {
return "Уважаемый $user->name, Вы уже авторизованы в системе. ";
}
$user->telegram_chat_id = $data['chat_id'];
$user->save();
return "Добро пожаловать, $user->first_name $user->last_name. Вы успешно авторизовались!";
} else {
return "Извините, не удалось найти данный токен!";
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question