isMethod('get')) { $apiKey = site_settings("webhook_verify_token"); $query = $request->query(); $hubMode = $query["hub_mode"] ?? null; $hubToken = $query["hub_verify_token"] ?? null; $challenge = $query["hub_challenge"] ?? null; $usersCount = User::where("webhook_token", $hubToken)->count(); if ($hubMode && $hubToken && $hubMode === 'subscribe' && ($hubToken === $apiKey || $usersCount > 0)) { return response($challenge, 200)->header('Content-Type', 'text/plain'); } else { throw new Exception("Invalid Request"); } } else { $request = request()->all(); $user = User::where('uid',request()->input('uid'))->first(); $webhookLog = PostWebhookLog::create([ 'user_id' => $user ? $user->id : null, 'webhook_response' => json_encode($request) ]); $response = json_decode($webhookLog->webhook_response, true); $idFromRequest = $response["entry"][0]['changes'][0]['value']['statuses'][0]['id'] ?? null; if ($idFromRequest) { $whatsappLog = CommunicationLog::where("type", ServiceType::WHATSAPP->value)->whereJsonContains('response_message->messages', [['id' => $idFromRequest]])->first(); if ($whatsappLog) { $errors = $response['entry'][0]['changes'][0]['value']['statuses'][0]['errors'] ?? []; if (!empty($errors)) { $whatsappLog->status = (string) CommunicationStatusEnum::FAIL->value; $whatsAppService->addedCreditLog($whatsappLog, $errors[0]['message']); $whatsappLog->save(); } else { $status = $response['entry'][0]['changes'][0]['value']['statuses'][0]['status']; if ($status == 'failed') { $whatsappLog->status = (string) CommunicationStatusEnum::FAIL->value; $whatsAppService->addedCreditLog($whatsappLog, "Cloud API couldnt send the message."); } elseif ($status == 'sent') { $meta_data = $whatsappLog->meta_data; $meta_data['delivered_at'] = Carbon::now()->toDayDateTimeString(); $whatsappLog->meta_data = $meta_data; $whatsappLog->status = (string) CommunicationStatusEnum::DELIVERED->value; } $whatsappLog->save(); } } } } } catch (Exception $e) { return response()->json([ 'success' => false, 'error' => $e->getMessage(), ], 500); } } }