77 lines
2.4 KiB
PHP
77 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Helpers;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use RuntimeException;
|
|
|
|
class WhatsappHelper
|
|
{
|
|
public static function send(string $target, string $message): bool
|
|
{
|
|
$target = self::normalizePhone($target);
|
|
$provider = strtolower((string) config('services.whatsapp.provider', 'fonnte'));
|
|
|
|
if ($provider === 'waha') {
|
|
$baseUrl = rtrim((string) config('services.whatsapp.waha_url'), '/');
|
|
if ($baseUrl === '') {
|
|
throw new RuntimeException('WAHA_URL belum dikonfigurasi.');
|
|
}
|
|
|
|
$headers = [];
|
|
if ($key = config('services.whatsapp.waha_api_key')) {
|
|
$headers['X-Api-Key'] = $key;
|
|
}
|
|
|
|
$response = Http::timeout(8)->withHeaders($headers)->post($baseUrl . '/api/sendText', [
|
|
'session' => config('services.whatsapp.waha_session', 'default'),
|
|
'chatId' => $target . '@c.us',
|
|
'text' => $message,
|
|
]);
|
|
|
|
if (!$response->successful()) {
|
|
throw new RuntimeException('WAHA gagal mengirim pesan: HTTP ' . $response->status());
|
|
}
|
|
return true;
|
|
}
|
|
|
|
$token = (string) config('services.whatsapp.fonnte_token');
|
|
if ($token === '') {
|
|
throw new RuntimeException('FONNTE_TOKEN belum dikonfigurasi.');
|
|
}
|
|
|
|
$response = Http::asForm()->timeout(8)->withHeaders([
|
|
'Authorization' => $token,
|
|
])->post('https://api.fonnte.com/send', [
|
|
'target' => $target,
|
|
'message' => $message,
|
|
]);
|
|
|
|
if (!$response->successful()) {
|
|
throw new RuntimeException('Fonnte gagal mengirim pesan: HTTP ' . $response->status());
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public static function configured(): bool
|
|
{
|
|
$provider = strtolower((string) config('services.whatsapp.provider', 'fonnte'));
|
|
return $provider === 'waha'
|
|
? (string) config('services.whatsapp.waha_url') !== ''
|
|
: (string) config('services.whatsapp.fonnte_token') !== '';
|
|
}
|
|
|
|
public static function normalizePhone(string $phone): string
|
|
{
|
|
$phone = preg_replace('/\D+/', '', $phone) ?: '';
|
|
if (str_starts_with($phone, '0')) {
|
|
$phone = '62' . substr($phone, 1);
|
|
}
|
|
if (!str_starts_with($phone, '62')) {
|
|
$phone = '62' . ltrim($phone, '0');
|
|
}
|
|
return $phone;
|
|
}
|
|
}
|