Files
tehnobox/app/Http/Controllers/Shop/ContactController.php
ssww23 93a655235a
Some checks failed
Deploy / deploy (push) Has been cancelled
Initial commit
2026-03-10 00:55:37 +03:00

72 lines
2.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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'),
]);
}
}