40 lines
1.9 KiB
PHP
40 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Notification\Adapters;
|
|
|
|
use App\Models\NotificationDelivery;
|
|
use App\Services\Notification\Contracts\NotificationChannelAdapter;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class WhatsAppOfficialAdapter implements NotificationChannelAdapter
|
|
{
|
|
public function send(NotificationDelivery $delivery): array
|
|
{
|
|
$config = $delivery->channelConfig;
|
|
$credentials = $config?->credentials ?? [];
|
|
$settings = $config?->settings ?? [];
|
|
$phoneId = $credentials['phone_number_id'] ?? null;
|
|
$token = $credentials['access_token'] ?? null;
|
|
$templateName = data_get($delivery->provider_response, 'request_context.provider_template_name');
|
|
if (! $phoneId || ! $token || ! $templateName) {
|
|
throw ValidationException::withMessages(['channel' => 'Phone Number ID, access token, dan template WhatsApp Official wajib tersedia.']);
|
|
}
|
|
$baseUrl = rtrim($settings['base_url'] ?? 'https://graph.facebook.com/v22.0', '/');
|
|
$parameters = collect(data_get($delivery->provider_response, 'request_context.template_parameters', []))
|
|
->map(fn ($value) => ['type' => 'text', 'text' => (string) $value])->values()->all();
|
|
$response = Http::withToken($token)->timeout(30)->post("{$baseUrl}/{$phoneId}/messages", [
|
|
'messaging_product' => 'whatsapp',
|
|
'to' => $delivery->destination,
|
|
'type' => 'template',
|
|
'template' => [
|
|
'name' => $templateName,
|
|
'language' => ['code' => data_get($delivery->provider_response, 'request_context.language', 'id')],
|
|
'components' => $parameters ? [['type' => 'body', 'parameters' => $parameters]] : [],
|
|
],
|
|
])->throw()->json();
|
|
|
|
return ['provider_message_id' => data_get($response, 'messages.0.id'), 'response' => $response];
|
|
}
|
|
}
|