$gateway->params['api_key'], 'campaignName' => $template->template, 'destination' => $phone, 'userName' => $name, 'templateParams' => self::buildParams($template, $data), 'buttons' => self::aiSensyButtons($data['copy_text'] ?? ''), 'media' => self::buildMedia($template), ]; // 🔍 Log payload before sending \Illuminate\Support\Facades\Log::info('AiSensy Payload', $payload); $response = Http::withHeaders([ 'Content-Type' => 'application/json', ])->post( 'https://backend.aisensy.com/campaign/t1/api/v2', $payload ); if ($response->successful()) { return $response->json(); } throw new \Exception( 'AiSensy Error: ' . $response->body() ); } /** * Convert named data → positional params (WhatsApp only) */ protected static function buildParams($template, array $data): array { if (empty($template->variables) || !is_array($template->variables)) { return []; } $params = []; foreach ($template->variables as $variable) { // Skip button-related vars if (in_array($variable, ['copy_text', 'expire_at'])) { continue; } if (!isset($data[$variable])) { continue; } $params[] = $data[$variable]; } return $params; } protected static function aiSensyButtons(? string $copyText = null) { if (!$copyText) { return []; } return [ [ 'type' => 'button', 'sub_type' => 'url', 'index' => 0, 'parameters' => [ [ 'type' => 'text', 'text' => $copyText ?? '' ] ] ] ]; } protected static function buildMedia($template): ?array { if (empty($template?->attachment)) { return null; } return [ 'url' => asset($template->attachment), 'filename' => 'sample_media', ]; } }