63 lines
1.8 KiB
PHP
63 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\Notifications;
|
|
|
|
use App\Models\NotificationSetting;
|
|
use Illuminate\Support\Facades\Http;
|
|
|
|
/**
|
|
* WAHA (WhatsApp HTTP API) — self-hosted WhatsApp bridge.
|
|
* Docs: https://waha.devlike.pro/docs/how-to/send-messages/
|
|
*/
|
|
class WahaNotifier
|
|
{
|
|
public function sendBatch(NotificationSetting $setting, array $messages): void
|
|
{
|
|
foreach ($messages as $message) {
|
|
$this->send($setting, $message);
|
|
}
|
|
}
|
|
|
|
public function sendTest(NotificationSetting $setting): void
|
|
{
|
|
$this->send(
|
|
$setting,
|
|
"🐱 *Cathy's App — Test Notification*\n\nYour WhatsApp channel is configured correctly! 🎉"
|
|
);
|
|
}
|
|
|
|
private function send(NotificationSetting $setting, string $text): void
|
|
{
|
|
$config = $setting->config ?? [];
|
|
$endpoint = $config['waha_endpoint'] ?? null;
|
|
$session = $config['waha_session'] ?? 'default';
|
|
$chatId = $config['chat_id'] ?? null;
|
|
$apiKey = $config['api_key'] ?? null;
|
|
|
|
if (! $endpoint || ! $chatId) {
|
|
throw new \RuntimeException('WAHA waha_endpoint and chat_id are required.');
|
|
}
|
|
|
|
$http = Http::timeout(15)->acceptJson()->contentType('application/json');
|
|
|
|
if ($apiKey) {
|
|
$http = $http->withHeaders(['X-Api-Key' => $apiKey]);
|
|
}
|
|
|
|
$response = $http->post($endpoint, [
|
|
'chatId' => $chatId,
|
|
'text' => $text,
|
|
'session' => $session,
|
|
]);
|
|
|
|
if (! $response->successful()) {
|
|
$keyHint = $apiKey ? '(api_key set, length=' . strlen($apiKey) . ')' : '(no api_key)';
|
|
throw new \RuntimeException(
|
|
"WAHA API error {$response->status()} {$keyHint} → " . $response->body()
|
|
);
|
|
}
|
|
}
|
|
}
|