authUrl = (string)getenv('NABEH_AUTH_URL'); $this->sendUrl = (string)getenv('NABEH_SEND_URL'); $this->email = (string)getenv('NABEH_EMAIL'); $this->password = (string)getenv('NABEH_PASSWORD'); // Strict validation: NO fallback defaults allowed $missing = []; if (empty($this->authUrl)) $missing[] = 'NABEH_AUTH_URL'; if (empty($this->sendUrl)) $missing[] = 'NABEH_SEND_URL'; if (empty($this->email)) $missing[] = 'NABEH_EMAIL'; if (empty($this->password)) $missing[] = 'NABEH_PASSWORD'; if (!empty($missing)) { throw new \RuntimeException("Nabeh Service configuration error: Missing environment variable(s): " . implode(', ', $missing)); } } /** * Retrieve Nabeh JWT Bearer Token, caching it in Redis for 24 hours. */ public function getBearerToken(): ?string { // 1. Try fetching from Redis first try { $redis = RedisClient::getInstance(); $cachedToken = $redis->get('nabeh_bearer_token'); if ($cachedToken) { return (string)$cachedToken; } } catch (\Exception $e) { error_log("⚠️ [Nabeh Auth Redis] Error reading token: " . $e->getMessage()); } // 2. Token not cached, authenticate via Nabeh Login API $payload = json_encode([ 'email' => $this->email, 'password' => $this->password, ]); $ch = curl_init($this->authUrl); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($curlError) { error_log("❌ [Nabeh Auth cURL Error] " . $curlError); return null; } if ($httpCode === 200 && $response) { $decoded = json_decode($response, true); $token = $decoded['token'] ?? $decoded['message']['token'] ?? $decoded['jwt'] ?? $decoded['access_token'] ?? null; if ($token) { // Cache token in Redis for 24h (86400 seconds) try { $redis = RedisClient::getInstance(); $redis->setex('nabeh_bearer_token', 86400, (string)$token); error_log("✅ [Nabeh Auth] Token cached in Redis successfully."); } catch (\Exception $e) { error_log("⚠️ [Nabeh Auth Redis Cache Save] Error saving token: " . $e->getMessage()); } return (string)$token; } } error_log("❌ [Nabeh Auth Login Failed] Code: {$httpCode} | Response: {$response}"); return null; } /** * Send OTP via Nabeh JWT Auth Gateway (WhatsApp Image/Text OTP) */ public function sendOtp(string $receiver, string $otp, string $method = 'image', string $appName = 'منصة صَقِل'): array { $bearerToken = $this->getBearerToken(); if (!$bearerToken) { return [ 'success' => false, 'error' => 'فشل الحصول على توكن المصادقة من منصة نبيه. تأكد من صحة NABEH_EMAIL و NABEH_PASSWORD.' ]; } $phoneRaw = preg_replace('/\D+/', '', $receiver); $type = in_array($method, ['text', 'voice', 'image'], true) ? $method : 'image'; // 1. First attempt with image $result = $this->attemptSend($phoneRaw, $type, $otp, $appName, $bearerToken); if ($result['success']) { return $result; } // 2. Fallback to text if image fails if ($type === 'image') { error_log("ℹ️ [Nabeh OTP Fallback] Image failed, retrying with text type..."); return $this->attemptSend($phoneRaw, 'text', $otp, $appName, $bearerToken); } return $result; } private function attemptSend(string $phone, string $type, string $otp, string $appName, string $bearerToken): array { $payload = json_encode([ 'phone' => $phone, 'type' => $type, 'code' => $otp, 'message' => "رمز التحقق الخاص بك لمنصة {$appName} هو: *{$otp}* \n الرجاء عدم مشاركته مع أي شخص لحماية حسابك.", ]); $ch = curl_init($this->sendUrl); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', "Authorization: Bearer {$bearerToken}", ], ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($curlError) { return [ 'success' => false, 'error' => 'cURL Connection Error: ' . $curlError, 'response' => null ]; } if ($httpCode === 200 && $response) { $decoded = json_decode($response, true); if ($decoded) { $statusStr = strtolower((string)($decoded['status'] ?? '')); $msgStr = strtolower((string)($decoded['message'] ?? '')); if ( !empty($decoded['success']) || in_array($statusStr, ['success', 'ok', 'true', '200', 'sent', 'queued', '1'], true) || ($decoded['status'] ?? false) === true || str_contains($msgStr, 'success') || str_contains($msgStr, 'sent') || str_contains($msgStr, 'تم') ) { return [ 'success' => true, 'message' => 'تم إرسال رمز التحقق بنجاح عبر الواتساب', 'raw' => $decoded ]; } } } return [ 'success' => false, 'http_code' => $httpCode, 'error' => 'Nabeh Gateway rejected OTP request', 'response' => $response ]; } }