This commit is contained in:
71
app/Http/Controllers/Shop/ContactController.php
Normal file
71
app/Http/Controllers/Shop/ContactController.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Shop;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
class ContactController extends Controller
|
||||
{
|
||||
public function submit(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:120'],
|
||||
'email' => ['required', 'email:rfc,dns', 'max:190'],
|
||||
'message' => ['required', 'string', 'max:2000'],
|
||||
]);
|
||||
|
||||
$botToken = trim((string) config('shop.telegram_bot_token'));
|
||||
$chatId = trim((string) config('shop.telegram_chat_id'));
|
||||
|
||||
if ($botToken === '' || $chatId === '') {
|
||||
return back()
|
||||
->withInput()
|
||||
->withErrors(['contact' => 'Не настроена отправка в Telegram. Заполните SHOP_TELEGRAM_BOT_TOKEN и SHOP_TELEGRAM_CHAT_ID.']);
|
||||
}
|
||||
|
||||
$message = $this->buildTelegramMessage($validated, $request);
|
||||
$telegramUrl = sprintf('https://api.telegram.org/bot%s/sendMessage', $botToken);
|
||||
|
||||
try {
|
||||
$response = Http::asForm()
|
||||
->timeout(12)
|
||||
->post($telegramUrl, [
|
||||
'chat_id' => $chatId,
|
||||
'text' => $message,
|
||||
'disable_web_page_preview' => true,
|
||||
]);
|
||||
} catch (Throwable) {
|
||||
return back()
|
||||
->withInput()
|
||||
->withErrors(['contact' => 'Не удалось отправить заявку в Telegram. Попробуйте еще раз.']);
|
||||
}
|
||||
|
||||
if (!$response->successful() || $response->json('ok') !== true) {
|
||||
return back()
|
||||
->withInput()
|
||||
->withErrors(['contact' => 'Telegram не принял заявку. Проверьте токен бота и chat id.']);
|
||||
}
|
||||
|
||||
return back()->with('status', 'Заявка отправлена. Мы свяжемся с вами в ближайшее время.');
|
||||
}
|
||||
|
||||
private function buildTelegramMessage(array $data, Request $request): string
|
||||
{
|
||||
$siteName = (string) config('shop.company_name', config('app.name', 'PC Shop'));
|
||||
|
||||
return implode("\n", [
|
||||
'Новая заявка с формы контактов',
|
||||
'Сайт: ' . $siteName,
|
||||
'Имя: ' . trim((string) ($data['name'] ?? '')),
|
||||
'Email: ' . trim((string) ($data['email'] ?? '')),
|
||||
'Сообщение:',
|
||||
trim((string) ($data['message'] ?? '')),
|
||||
'IP: ' . $request->ip(),
|
||||
'Дата: ' . now()->format('d.m.Y H:i'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user