293 lines
11 KiB
PHP
293 lines
11 KiB
PHP
<?php
|
|
/**
|
|
* Nabeh Payment Verification Endpoint
|
|
*
|
|
* Auto-detects the user's pending invoice and uses Gemini AI to verify
|
|
* the receipt image against the invoice. No manual invoice number needed.
|
|
*
|
|
* ===============================
|
|
* INPUT (JSON body)
|
|
* ===============================
|
|
* driver_id (optional) — from Nabeh's Siro API resolution (preferred)
|
|
* phone (required if no driver_id) — lookup via Siro backend resolve_user
|
|
* payment_method (required) — shamcash / cliq / mtn / sms
|
|
* receipt_image (optional for AI verification)
|
|
* image_mime_type (optional, default: image/jpeg)
|
|
*
|
|
* ===============================
|
|
* FLOW
|
|
* ===============================
|
|
* 1. Auth via jwtconnect.php (X-API-Key → NABEH_API_KEY)
|
|
* 2. Resolve driverID:
|
|
* a. Use driver_id directly if provided
|
|
* b. Otherwise call Siro backend resolve_user.php (phone → driverID)
|
|
* 3. Auto-find latest pending invoice for that driver
|
|
* 4. If shamcash + receipt_image:
|
|
* a. Call GeminiAi::verifyPayment(invoice_number, amount, "ShamCash", "", receipt_image)
|
|
* b. Gemini returns {"verified": true/false, "reason": "..."}
|
|
* c. If verified → UPDATE status='processing' → finalizeShamCashDeposit()
|
|
* d. Return result
|
|
* 5. If other methods or no receipt_image:
|
|
* - Return invoice status info
|
|
*
|
|
* Auth: X-API-Key header → NABEH_API_KEY (via jwtconnect.php Path 5)
|
|
*/
|
|
|
|
require_once __DIR__ . '/../../jwtconnect.php';
|
|
require_once __DIR__ . '/../GeminiAi.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['status' => 'failure', 'message' => 'Method not allowed']);
|
|
exit;
|
|
}
|
|
|
|
$raw = file_get_contents('php://input');
|
|
$data = json_decode($raw, true) ?: $_POST;
|
|
|
|
$driverId = trim($data['driver_id'] ?? '');
|
|
$phone = trim($data['phone'] ?? '');
|
|
$paymentMethod = strtolower(trim($data['payment_method'] ?? ''));
|
|
$receiptImage = $data['receipt_image'] ?? '';
|
|
$imageMimeType = $data['image_mime_type'] ?? 'image/jpeg';
|
|
|
|
// ── Step 1: Resolve driverID ──────────────────────────────────
|
|
// driver_id (from Nabeh's Siro API resolution) is preferred
|
|
// phone fallback calls Siro backend resolve_user endpoint via S2S
|
|
$userName = '';
|
|
$userPhone = $phone;
|
|
$userType = 'driver';
|
|
|
|
if (empty($driverId) && empty($phone)) {
|
|
printFailure('driver_id or phone is required');
|
|
exit;
|
|
}
|
|
|
|
if (empty($driverId) && !empty($phone)) {
|
|
$siroBackendUrl = rtrim(getenv('SIRO_BACKEND_URL') ?: 'https://api-syria.siromove.com/siro', '/');
|
|
$resolveUrl = $siroBackendUrl . '/nabeh/resolve_user.php';
|
|
|
|
$resolvePayload = json_encode(['phone' => $phone]);
|
|
$apiKey = getenv('NABEH_API_KEY') ?: '';
|
|
|
|
$ch = curl_init($resolveUrl);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_POST => true,
|
|
CURLOPT_POSTFIELDS => $resolvePayload,
|
|
CURLOPT_HTTPHEADER => [
|
|
'Content-Type: application/json',
|
|
'X-API-Key: ' . $apiKey,
|
|
],
|
|
CURLOPT_TIMEOUT => 10,
|
|
]);
|
|
$resolveRes = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
|
|
if ($httpCode !== 200 || empty($resolveRes)) {
|
|
printFailure('Could not resolve user. Please ensure you are registered in Siro.');
|
|
exit;
|
|
}
|
|
|
|
$resolveData = json_decode($resolveRes, true);
|
|
if (($resolveData['status'] ?? '') !== 'success' || empty($resolveData['data']['user_id'] ?? '')) {
|
|
printFailure('User not found in Siro system.');
|
|
exit;
|
|
}
|
|
|
|
$driverId = $resolveData['data']['user_id'];
|
|
$userName = $resolveData['data']['name'] ?? '';
|
|
$userPhone = $resolveData['data']['phone'] ?? $phone;
|
|
$userType = $resolveData['data']['type'] ?? 'driver';
|
|
}
|
|
|
|
$paymentMethod = $paymentMethod ?: 'shamcash';
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// SHAMCASH — AI Verification (auto-find pending invoice)
|
|
// ═══════════════════════════════════════════════════════════════
|
|
if ($paymentMethod === 'shamcash') {
|
|
// Auto-find latest pending invoice for this driver
|
|
$stmt = $con->prepare("
|
|
SELECT id, invoice_number, amount, status, created_at
|
|
FROM invoices_shamcash
|
|
WHERE driverID = ? AND status = 'pending'
|
|
ORDER BY created_at DESC
|
|
LIMIT 1
|
|
");
|
|
$stmt->execute([$driverId]);
|
|
$invoice = $stmt->fetch();
|
|
|
|
if (!$invoice) {
|
|
$stmt = $con->prepare("
|
|
SELECT id, invoice_number, amount, status, created_at
|
|
FROM invoices_shamcash
|
|
WHERE driverID = ? AND status = 'completed'
|
|
ORDER BY created_at DESC
|
|
LIMIT 1
|
|
");
|
|
$stmt->execute([$driverId]);
|
|
$lastCompleted = $stmt->fetch();
|
|
|
|
if ($lastCompleted) {
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'verified'=> true,
|
|
'message' => 'آخر فاتورة لديك مكتملة بالفعل.',
|
|
'invoice' => $lastCompleted,
|
|
], JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'verified'=> false,
|
|
'message' => 'لا توجد فاتورة معلقة. يرجى إنشاء فاتورة عبر تطبيق Siro أولاً.',
|
|
], JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
|
|
// ── If no receipt image, just return invoice info ─────
|
|
if (empty($receiptImage)) {
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'verified' => false,
|
|
'requires_image' => true,
|
|
'message' => "تم العثور على فاتورة رقم {$invoice['invoice_number']} بمبلغ {$invoice['amount']} ل.س. يرجى إرسال صورة الإيصال.",
|
|
'invoice' => $invoice,
|
|
], JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
|
|
// ── Run AI verification ─────────────────────────────────
|
|
$geminiKey = getenv('GEMINI_API_KEY');
|
|
if (empty($geminiKey)) {
|
|
printFailure('AI verification service not configured');
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$gemini = new GeminiAi($geminiKey);
|
|
$aiResult = $gemini->verifyPayment(
|
|
$invoice['invoice_number'],
|
|
$invoice['amount'],
|
|
'ShamCash',
|
|
'',
|
|
$receiptImage
|
|
);
|
|
|
|
if (!empty($aiResult['verified'])) {
|
|
// ── AI confirmed → finalize ─────────────────────
|
|
$con->beginTransaction();
|
|
|
|
$upd = $con->prepare("
|
|
UPDATE invoices_shamcash
|
|
SET status = 'processing'
|
|
WHERE id = ? AND status = 'pending'
|
|
");
|
|
$upd->execute([$invoice['id']]);
|
|
|
|
if ($upd->rowCount() > 0) {
|
|
require_once __DIR__ . '/../shamcash/finalize_deposit.php';
|
|
|
|
$finalized = finalizeShamCashDeposit($con, $invoice['id']);
|
|
|
|
if ($finalized) {
|
|
$con->commit();
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'verified' => true,
|
|
'message' => '✅ تم التحقق من عملية الدفع بنجاح! تم تحديث رصيد حسابك.',
|
|
'invoice' => [
|
|
'invoice_number' => $invoice['invoice_number'],
|
|
'amount' => $invoice['amount'],
|
|
'status' => 'completed',
|
|
],
|
|
'ai_reason' => $aiResult['reason'] ?? null,
|
|
], JSON_UNESCAPED_UNICODE);
|
|
} else {
|
|
$con->rollBack();
|
|
echo json_encode([
|
|
'status' => 'error',
|
|
'message' => 'Verification passed but wallet update failed. Contact support.',
|
|
], JSON_UNESCAPED_UNICODE);
|
|
}
|
|
} else {
|
|
$con->rollBack();
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'verified'=> false,
|
|
'message' => 'These funds have already been credited.',
|
|
], JSON_UNESCAPED_UNICODE);
|
|
}
|
|
} else {
|
|
$reason = $aiResult['reason'] ?? 'لم يتم التأكيد';
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'verified' => false,
|
|
'message' => "⚠️ $reason",
|
|
'ai_reason' => $reason,
|
|
], JSON_UNESCAPED_UNICODE);
|
|
}
|
|
} catch (Exception $e) {
|
|
error_log("[Nabeh ShamCash AI] " . $e->getMessage());
|
|
printFailure('AI verification service error');
|
|
}
|
|
exit;
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// OTHER METHODS — Status query (find pending invoice by phone)
|
|
// ═══════════════════════════════════════════════════════════════
|
|
$table = '';
|
|
$columns = '';
|
|
$conditions = '';
|
|
|
|
switch ($paymentMethod) {
|
|
case 'sms':
|
|
case 'syriatel':
|
|
$table = 'invoices_sms';
|
|
$columns = "id, invoice_number, amount, status, NULL AS transaction_id, created_at, paid_at";
|
|
$conditions = "driverID = ? AND status = 'pending'";
|
|
break;
|
|
|
|
case 'cliq':
|
|
$table = 'cliq_invoices';
|
|
$columns = "id, invoice_number, amount, status, NULL AS transaction_id, created_at, updated_at AS paid_at";
|
|
$conditions = "user_id = ? AND user_type = 'driver' AND status = 'pending'";
|
|
break;
|
|
|
|
case 'mtn':
|
|
$table = 'mtn_invoices';
|
|
$columns = "id, invoice_number, amount, status, mtn_transaction_id AS transaction_id, created_at, updated_at AS paid_at";
|
|
$conditions = "user_id = ? AND user_type = 'driver' AND status = 'pending'";
|
|
break;
|
|
|
|
default:
|
|
printFailure("Invalid payment method: $paymentMethod");
|
|
exit;
|
|
}
|
|
|
|
$stmt = $con->prepare("
|
|
SELECT $columns, ? AS payment_method
|
|
FROM $table
|
|
WHERE $conditions
|
|
ORDER BY created_at DESC
|
|
LIMIT 5
|
|
");
|
|
$stmt->execute([$paymentMethod, $driverId]);
|
|
$invoices = $stmt->fetchAll();
|
|
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'verified' => !empty($invoices),
|
|
'message' => empty($invoices) ? 'لا توجد فواتير معلقة.' : null,
|
|
'user' => [
|
|
'id' => $driverId,
|
|
'phone' => $userPhone,
|
|
'name' => $userName,
|
|
],
|
|
'invoices' => $invoices,
|
|
], JSON_UNESCAPED_UNICODE);
|