feat: implement secure OTP-based payout workflow with dynamic fee calculation and improved authentication checks

This commit is contained in:
Hamza-Ayed
2026-07-19 01:51:39 +03:00
parent 5e80c886a0
commit 085b180bdb
11 changed files with 252 additions and 193 deletions
@@ -67,9 +67,25 @@ if (!function_exists('finalizePayout')) {
}
$driverId = $payout['driver_id'];
$payoutFee = 3500;
$netAmount = (float)$payout['amount']-$payoutFee; // المبلغ الصافي الذي طلبه السائق
$totalDeducted = $netAmount; // المبلغ الإجمالي الذي سيتم خصمه
// Fetch driver site to calculate dynamic fee
$stmtDriver = $con->prepare("SELECT site FROM driver WHERE id = :id");
$stmtDriver->execute([':id' => $driverId]);
$driverInfo = $stmtDriver->fetch(PDO::FETCH_ASSOC);
$site = $encryptionHelper->decryptData($driverInfo['site'] ?? '');
$payoutFee = 0.0;
if (strtolower($site) === 'syria') {
$payoutFee = 35.00;
} elseif (strtolower($site) === 'egypt') {
$payoutFee = 10.00;
} elseif (strtolower($site) === 'jordan') {
$payoutFee = 0.00;
} else {
$payoutFee = 35.00;
}
$netAmount = (float)$payout['amount']; // The amount requested
$totalDeducted = $netAmount + $payoutFee; // Total deducted
// 2. إنشاء معرف دفع رئيسي لهذه المعاملة
// نسجل المبلغ الإجمالي المخصوم بالسالب
@@ -83,17 +99,16 @@ if (!function_exists('finalizePayout')) {
if (!$tokenDriver || !$tokenSiro) throw new Exception('Failed to generate required tokens');
logPayoutError("GEN_TOKENS", "Driver and Siro tokens generated successfully.");
// 4. تسجيل معاملة الخصم في محفظة السائق (driverWallet)
$insertDriver = $con->prepare("INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driverID, :paymentID, :amount, :paymentMethod)");
$insertDriver->execute([
// 4. Update the reserved deduction in driverWallet with the real paymentID
$updateDriver = $con->prepare("UPDATE driverWallet SET paymentID = :paymentID, paymentMethod = 'payout' WHERE driverID = :driverID AND paymentMethod = 'payout_reserved' AND amount = :amount LIMIT 1");
$updateDriver->execute([
':driverID' => $driverId,
':paymentID' => $paymentID,
':amount' => -$totalDeducted, // تسجيل المبلغ بالسالب
':paymentMethod' => 'payout'
':amount' => -$totalDeducted
]);
if ($insertDriver->rowCount() === 0) throw new Exception('Insert to driverWallet failed');
$con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token")->execute([':token' => $tokenDriver]);
logPayoutError("DRIVER_WALLET", "Negative transaction of {$totalDeducted} recorded in driverWallet.");
logPayoutError("DRIVER_WALLET", "Updated reserved transaction of {$totalDeducted} in driverWallet.");
// 5. تسجيل معاملة الربح (العمولة) في محفظة الشركة (siroWallet)
$insertSiro = $con->prepare("INSERT INTO siroWallet (driverId, passengerId, amount, paymentMethod, token) VALUES (:driverId, :passengerId, :amount, :paymentMethod, :token)");
@@ -1,16 +1,22 @@
<?php
// request_payout.php
include "../jwtconnect.php"; // ملف الاتصال الذي يتحقق من JWT
include "../connect.php"; // This initializes $decodedToken and $encryptionHelper
error_log("[RequestPayout] --- Request Started ---");
// --- 1. استقبال المدخلات ---
$driverId = filterRequest("driverId");
// --- 1. Security Fix (S1): Extract ID from JWT instead of request body ---
$driverId = null;
if (isset($decodedToken) && isset($decodedToken->sub)) {
$driverId = $decodedToken->sub;
} else {
printFailure("Unauthorized. Valid token required.");
exit;
}
$amount_raw = filterRequest("amount");
$wallet_type = filterRequest("wallet_type") ?? 'Sham Cash'; // قيمة افتراضية
$phone = filterRequest("phone");
$wallet_type = filterRequest("wallet_type") ?? 'Sham Cash';
$otp = filterRequest("otp");
// تأكيد المبلغ كرقم
$amount = is_numeric($amount_raw) ? (float)$amount_raw : 0.0;
// تحقق أساسي
@@ -19,28 +25,80 @@ if (empty($driverId) || $amount <= 0) {
exit;
}
if (empty($otp)) {
printFailure("OTP code is required for payout.");
exit;
}
try {
// --- Atomic balance check + insert with transaction ---
// --- 2. Fetch Driver info & Dynamic Fee (S3) ---
$stmtDriver = $con->prepare("SELECT phone, site FROM driver WHERE id = :id");
$stmtDriver->execute([':id' => $driverId]);
$driverInfo = $stmtDriver->fetch(PDO::FETCH_ASSOC);
if (!$driverInfo) {
printFailure("Driver not found.");
exit;
}
$phone = $encryptionHelper->decryptData($driverInfo['phone']);
$site = $encryptionHelper->decryptData($driverInfo['site']);
$payout_fee = 0.0;
if (strtolower($site) === 'syria') {
$payout_fee = 35.00;
} elseif (strtolower($site) === 'egypt') {
$payout_fee = 10.00;
} elseif (strtolower($site) === 'jordan') {
$payout_fee = 0.00;
} else {
$payout_fee = 35.00; // Default fallback
}
$total_deduction = $amount + $payout_fee;
// --- 3. OTP Verification (S6) ---
$encryptedPhone = $encryptionHelper->encryptData($phone);
$encryptedOtp = $encryptionHelper->encryptData($otp);
$stmtOtp = $con->prepare("SELECT id FROM token_verification_driver
WHERE phone_number = ? AND token = ?
AND expiration_time > NOW() AND verified = 0
LIMIT 1");
$stmtOtp->execute([$encryptedPhone, $encryptedOtp]);
$otpRow = $stmtOtp->fetch(PDO::FETCH_ASSOC);
if (!$otpRow) {
printFailure("Invalid or expired OTP. Please request a new one.");
exit;
}
// --- 4. Atomic balance check + deduction + insert (S2, S4) ---
$con->beginTransaction();
$stmt_driver = $con->prepare("
$stmt_balance = $con->prepare("
SELECT COALESCE(SUM(amount), 0) AS balance
FROM driverWallet
WHERE driverID = :id
FOR UPDATE
");
$stmt_driver->execute([':id' => $driverId]);
$driver = $stmt_driver->fetch(PDO::FETCH_ASSOC);
$stmt_balance->execute([':id' => $driverId]);
$wallet = $stmt_balance->fetch(PDO::FETCH_ASSOC);
$payout_fee = 3500.00;
$total_deduction = $amount + $payout_fee;
if ($driver['balance'] < $total_deduction) {
if ($wallet['balance'] < $total_deduction) {
$con->rollBack();
printFailure("Insufficient balance. Required: $total_deduction");
exit;
}
// S4 Fix: Deduct the balance IMMEDIATELY
$insertDriver = $con->prepare("INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driverID, NULL, :amount, :paymentMethod)");
$insertDriver->execute([
':driverID' => $driverId,
':amount' => -$total_deduction,
':paymentMethod' => 'payout_reserved'
]);
$sql = "
INSERT INTO payout_requests (driver_id, driver_phone, amount, wallet_type)
VALUES (:did, :phone, :amount, :wallet)
@@ -53,21 +111,24 @@ try {
':wallet'=> $wallet_type
]);
// Mark OTP as verified
$con->prepare("UPDATE token_verification_driver SET verified = 1 WHERE id = ?")->execute([$otpRow['id']]);
$con->commit();
if ($stmt->rowCount() > 0) {
// --- 4. إرسال إشعار لخدمة العملاء ---
$customerServicePhone = getenv('CUSTOMER_SERVICE_PHONE');
$message =
"⚠️ طلب دفع جديد:\n" .
"ID السائق: {$driverId}\n" .
"هاتف السائق: {$phone}\n" .
"البلد: {$site}\n" .
"نوع المحفظة: {$wallet_type}\n" .
"المبلغ: {$amount} SYP\n\n" .
"المبلغ المطلوب: {$amount}\n" .
"الرسوم المخصومة: {$payout_fee}\n\n" .
"الرجاء من فريق خدمة العملاء تنفيذ عملية الدفع الآن.";
// الإرسال (الفنكشن مُضمّن لديك مسبقًا)
sendWhatsAppFromServer($customerServicePhone, $message);
error_log("[RequestPayout] Successfully created payout request for driver ID: $driverId");
@@ -77,6 +138,9 @@ try {
}
} catch (PDOException $e) {
if ($con->inTransaction()) {
$con->rollBack();
}
error_log("[RequestPayout] PDOException: " . $e->getMessage());
printFailure("A database error occurred.");
}