Update: 2026-06-11 19:26:42

This commit is contained in:
Hamza-Ayed
2026-06-11 19:26:42 +03:00
parent 727068b668
commit b87477bec4
371 changed files with 67 additions and 14257 deletions

View File

@@ -1,100 +0,0 @@
<?php
include "../../connect.php";
// 1. احصل على AUTH TOKEN
$api_key = getenv("payMobApiKey1"); // ضع API Key الخاص بك هنا
$email= filterRequest("amount");
$first_name= filterRequest("first_name");
$last_name= filterRequest("last_name");
$phone_number= filterRequest("phone_number");
$amount= filterRequest("amount");
$auth_url = "https://accept.paymob.com/api/auth/tokens";
$auth_data = json_encode(["api_key" => $api_key]);
$response = callAPI("POST", $auth_url, $auth_data);
// printResponse("AUTH TOKEN RESPONSE", $response);
$auth_token = $response->token ?? null;
if (!$auth_token) {
die("❌ فشل الحصول على AUTH TOKEN!");
}
// $amount=$amount*100;
// 2. أنشئ الطلب ORDER
$order_url = "https://accept.paymob.com/api/ecommerce/orders";
$order_data = [
"auth_token" => $auth_token,
"delivery_needed" => false,
"amount_cents" => $amount,
"currency" => "EGP",
"merchant_order_id" => uniqid(),
"items" => []
];
$response = callAPI("POST", $order_url, json_encode($order_data));
// printResponse("ORDER RESPONSE", $response);
$order_id = $response->id ?? null;
if (!$order_id) {
die("❌ فشل إنشاء الطلب!");
}
$integration_id=getenv("paymobIntegratedIdCard");
// 3. احصل على Payment Key
$payment_key_url = "https://accept.paymob.com/api/acceptance/payment_keys";
$payment_key_data = [
"auth_token" => $auth_token,
"amount_cents" => $amount,
"expiration" => 3600,
"order_id" => $order_id,
"billing_data" => [
"first_name" =>$first_name,
"last_name" => $last_name,
"email" => $email,
"phone_number" => $phone_number,
"country" => "EG",
"city" => "Cairo",
"state" => "shobra",
"street" => "Test St.",
"building" => "1",
"apartment" => "10",
"floor" => "2",
"postal_code" => "12345",
"shipping_method"=> 'card'
],
"currency" => "EGP",
"integration_id" => $integration_id, // ضع الـ Integration ID الصحيح
];
$response = callAPI("POST", $payment_key_url, json_encode($payment_key_data));
// printResponse("PAYMENT TOKEN RESPONSE", $response);
$payment_token = $response->token ?? null;
if (!$payment_token) {
die("❌ فشل الحصول على PAYMENT TOKEN!");
}
// 4. إنشاء IFRAME URL
$iframe_id = "837992"; // ضع الـ Iframe ID الصحيح
$iframe_url = "https://accept.paymob.com/api/acceptance/iframes/$iframe_id?payment_token=$payment_token";
if($payment_token){
printSuccess($iframe_url);
}
// دالة لطلب API عبر CURL
function callAPI($method, $url, $data)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ["Content-Type: application/json"]
]);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response);
}

View File

@@ -1,358 +0,0 @@
<?php
include "../../connect.php";
define("BASE_URL", "https://wl.tripz-egypt.com/v1/main/ride");
define("LOG_FILE", "../logs/payment_verification.log"); // Define log file path
// Function to write to error log
function logError($step, $message, $data = null) {
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[{$timestamp}] STEP {$step}: {$message}";
if ($data !== null) {
$logEntry .= " | Data: " . json_encode($data);
}
// Ensure log directory exists
$logDir = dirname(LOG_FILE);
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// Append to log file
file_put_contents(LOG_FILE, $logEntry . PHP_EOL, FILE_APPEND);
// Also log to PHP error log for server monitoring
// error_log("PAYMENT_VERIFICATION: {$logEntry}");
}
// Receive parameters from GET request
$user_id = filterRequest("user_id");
$passengerId = filterRequest("passengerId");
$paymentMethod = filterRequest("paymentMethod");
// Log initial request
// logError("0", "Request received", [
// "user_id" => $user_id,
// "passengerId" => $passengerId
// ]);
// Validate user_id and passengerId
if (!$user_id || !$passengerId) {
// logError("1", "Invalid parameters", [
// "user_id" => $user_id,
// "passengerId" => $passengerId
// ]);
printFailure("Invalid user ID or passenger ID.");
exit;
}
try {
// Step 1: Get the latest successful payment
// logError("1", "Querying latest payment", ["user_id" => $user_id]);
$stmt = $con->prepare("SELECT * FROM paymentsLog WHERE user_id = :user_id AND created_at >= DATE_SUB(NOW(), INTERVAL 2 MINUTE)
ORDER BY created_at DESC
LIMIT 1");
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
$stmt->execute();
$payment = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$payment) {
logError("1", "No payment found", ["user_id" => $user_id]);
printFailure("No payment data found.");
exit;
}
// logError("1", "Payment found", [
// "payment_id" => $payment['id'] ?? 'unknown',
// "status" => $payment['status'],
// "amount" => $payment['amount']/100 ?? 'unknown'
// ]);
// Step 2: Check payment status
if ($payment['status'] != 1) {
// logError("2", "Payment not successful", ["status" => $payment['status']]);
printFailure("Payment is not successful yet.");
exit;
}
// logError("2", "Payment status verified", ["status" => $payment['status']]);
$amount = $payment['amount']/100; // Paid amount
// Step 3: Calculate bonus based on the paid amount
// logError("3", "Calculating bonus", ["amount" => $amount]);
$finalAmount = calculateBonus($amount);
if ($finalAmount <= 0) {
// logError("3", "Bonus calculation failed", [
// "original_amount" => $amount,
// "calculated_amount" => $finalAmount
// ]);
printFailure("Invalid amount for bonus calculation.");
exit;
}
// logError("3", "Bonus calculated", [
// "original_amount" => $amount,
// "final_amount" => $finalAmount
// ]);
// // Step 4: Generate payment token
// logError("4", "Generating payment token", [
// "passengerId" => $passengerId,
// "amount" => $finalAmount
// ]);
$token = generatePaymentToken($passengerId, $finalAmount);
if (!$token) {
// logError("4", "Token generation failed");
printFailure("Payment verified, but failed to generate token.");
exit;
}
// logError("4", "Token generated successfully", ["token_length" => strlen($token)]);
// // Step 5: Add balance to passenger's wallet
// logError("5", "Adding balance to passenger wallet", [
// "passengerId" => $passengerId,
// "amount" => $finalAmount
// ]);
$walletResult = addToPassengerWallet($passengerId, $finalAmount, $token);
if (!$walletResult || !isset($walletResult['status']) || $walletResult['status'] != "success") {
// logError("5", "Failed to add balance to passenger wallet", $walletResult);
printFailure("Payment verified, but failed to add balance to passenger wallet.");
exit;
}
// logError("5", "Balance added to passenger wallet", $walletResult);
// Step 6: Add balance to Sefer wallet
// logError("6", "Adding balance to Sefer wallet", [
// "passengerId" => $passengerId,
// "amount" => $finalAmount,
// "paymentMethod" => $paymentMethod
// ]);
$token = generatePaymentToken($passengerId, $finalAmount);
if (!$token) {
// logError("4", "Token generation failed");
printFailure("Payment verified, but failed to generate token.");
exit;
}
// logError("4", "Token generated successfully", ["token_length" => strlen($token)]);
$seferWalletResult = addToSeferWallet($passengerId, $amount, $paymentMethod);
if (!$seferWalletResult || !isset($seferWalletResult['status']) || $seferWalletResult['status'] != "success") {
// logError("6", "Failed to add balance to Sefer wallet", $seferWalletResult);
printFailure("Payment verified, but failed to add balance to Sefer wallet.");
exit;
}
// logError("6", "Balance added to Sefer wallet", $seferWalletResult);
// // Final success
// logError("7", "Process completed successfully", [
// "payment_id" => $payment['id'] ?? 'unknown',
// "amount" => $finalAmount,
// "passengerId" => $passengerId
// ]);
printSuccess( "Payment data saved successfully");
} catch (PDOException $e) {
logError("ERROR", "Database error: " . $e->getMessage());
printFailure("Database error occurred.");
} catch (Exception $e) {
logError("ERROR", "General error: " . $e->getMessage());
printFailure("An error occurred during payment verification.");
}
// 🎯 Function to generate payment token with error logging
function generatePaymentToken($passengerId, $amount) {
$url = BASE_URL . "/passengerWallet/addPaymentTokenPassenger.php";
$postData = [
'passengerId' => $passengerId,
'amount' => $amount
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
logError("4.1", "cURL error in token generation", [
"error" => $curlError,
"url" => $url
]);
return null;
}
if ($httpCode != 200) {
logError("4.2", "HTTP error in token generation", [
"http_code" => $httpCode,
"response" => $response
]);
return null;
}
$data = json_decode($response, true);
if (!$data || !isset($data['message'])) {
logError("4.3", "Invalid response format in token generation", [
"response" => $response
]);
return null;
}
return $data['message']; // ✅ Return token
}
// 🎯 Function to add balance to passenger's wallet with error logging
function addToPassengerWallet($passengerId, $amount, $token) {
$url = BASE_URL . "/passengerWallet/add.php";
$postData = [
'passenger_id' => $passengerId,
'balance' => $amount,
'token' => $token
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
logError("5.1", "cURL error in passenger wallet update", [
"error" => $curlError,
"url" => $url
]);
return null;
}
if ($httpCode != 200) {
logError("5.2", "HTTP error in passenger wallet update", [
"http_code" => $httpCode,
"response" => $response
]);
return null;
}
$data = json_decode($response, true);
if (!$data) {
logError("5.3", "Invalid response format in passenger wallet update", [
"response" => $response
]);
return null;
}
return $data; // ✅ Return result
}
// 🎯 Function to add balance to Sefer wallet with error logging
function addToSeferWallet($passengerId, $amount, $paymentMethod) {
// Generate a new token specifically for the Sefer wallet
$seferToken = generatePaymentToken($passengerId, $amount);
if (!$seferToken) {
logError("6.0.1", "Failed to generate Sefer token");
return null;
}
logError("6.0.2", "Generated new Sefer token", [
"token_length" => ($seferToken)
]);
$url = BASE_URL . "/seferWallet/add.php";
$postData = [
'amount' => $amount,
'paymentMethod' => $paymentMethod,
'passengerId' => $passengerId,
'token' => $seferToken, // Use the new Sefer-specific token
'driverId' => 'passenger'
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
logError("6.1", "cURL error in Sefer wallet update", [
"error" => $curlError,
"url" => $url
]);
return null;
}
if ($httpCode != 200) {
logError("6.2", "HTTP error in Sefer wallet update", [
"http_code" => $httpCode,
"response" => $response
]);
return null;
}
$data = json_decode($response, true);
if (!$data) {
logError("6.3", "Invalid response format in Sefer wallet update", [
"response" => $response
]);
return null;
}
return $data; // ✅ Return result
}
// 🎯 Function to calculate bonus
function calculateBonus($amount) {
logError("3.1", "Bonus calculation input", ["amount" => $amount]);
$result = 0;
if ($amount == 100) $result = 100;
else if ($amount == 200) $result = 215;
else if ($amount == 400) $result = 450;
else if ($amount == 1000) $result = 1140;
logError("3.2", "Bonus calculation result", [
"input" => $amount,
"output" => $result
]);
return $result;
}
?>

View File

@@ -1,100 +0,0 @@
<?php
include "../../../connect.php";
// 1. احصل على AUTH TOKEN
$api_key = getenv("payMobApiKey1"); // ضع API Key الخاص بك هنا
$email= filterRequest("amount");
$first_name= filterRequest("first_name");
$last_name= filterRequest("last_name");
$phone_number= filterRequest("phone_number");
$amount= filterRequest("amount");
$auth_url = "https://accept.paymob.com/api/auth/tokens";
$auth_data = json_encode(["api_key" => $api_key]);
$response = callAPI("POST", $auth_url, $auth_data);
// printResponse("AUTH TOKEN RESPONSE", $response);
$auth_token = $response->token ?? null;
if (!$auth_token) {
die("❌ فشل الحصول على AUTH TOKEN!");
}
$amount=$amount*100;
// 2. أنشئ الطلب ORDER
$order_url = "https://accept.paymob.com/api/ecommerce/orders";
$order_data = [
"auth_token" => $auth_token,
"delivery_needed" => false,
"amount_cents" => $amount,
"currency" => "EGP",
"merchant_order_id" => uniqid(),
"items" => []
];
$response = callAPI("POST", $order_url, json_encode($order_data));
// printResponse("ORDER RESPONSE", $response);
$order_id = $response->id ?? null;
if (!$order_id) {
die("❌ فشل إنشاء الطلب!");
}
$integration_id=getenv("paymobIntegratedIdCardDriver");
// 3. احصل على Payment Key
$payment_key_url = "https://accept.paymob.com/api/acceptance/payment_keys";
$payment_key_data = [
"auth_token" => $auth_token,
"amount_cents" => $amount,
"expiration" => 3600,
"order_id" => $order_id,
"billing_data" => [
"first_name" =>$first_name,
"last_name" => $last_name,
"email" => $email,
"phone_number" => $phone_number,
"country" => "EG",
"city" => "Cairo",
"state" => "shobra",
"street" => "Test St.",
"building" => "1",
"apartment" => "10",
"floor" => "2",
"postal_code" => "12345",
"shipping_method"=> 'card'
],
"currency" => "EGP",
"integration_id" => $integration_id, // ضع الـ Integration ID الصحيح
];
$response = callAPI("POST", $payment_key_url, json_encode($payment_key_data));
// printResponse("PAYMENT TOKEN RESPONSE", $response);
$payment_token = $response->token ?? null;
if (!$payment_token) {
die("❌ فشل الحصول على PAYMENT TOKEN!");
}
// 4. إنشاء IFRAME URL
$iframe_id = "837992"; // ضع الـ Iframe ID الصحيح
$iframe_url = "https://accept.paymob.com/api/acceptance/iframes/$iframe_id?payment_token=$payment_token";
if($payment_token){
printSuccess($iframe_url);
}
// دالة لطلب API عبر CURL
function callAPI($method, $url, $data)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ["Content-Type: application/json"]
]);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response);
}

View File

@@ -1,118 +0,0 @@
<?php
include "../../../connect.php";
// 1⃣ AUTH TOKEN
$api_key = getenv("payMobApiKey1");
$integration_id = getenv("paymobIntegratedIdDriverWallet"); // 🔁 تأكد أنه خاص بالسائق
$email = filterRequest("email");
$first_name = filterRequest("first_name");
$last_name = filterRequest("last_name");
$phone_number = filterRequest("phone_number"); // هاتف السائق
$wallet_phone = '+2'.$phone_number;
$amount = filterRequest("amount");
$auth_url = "https://accept.paymob.com/api/auth/tokens";
$auth_data = json_encode(["api_key" => $api_key]);
$response = callAPI("POST", $auth_url, $auth_data);
$auth_token = $response->token ?? null;
if (!$auth_token) {
error_log("❌ AUTH TOKEN retrieval failed!");
die("❌ AUTH TOKEN retrieval failed!");
}
$amount=$amount*100;
// 2⃣ ORDER CREATE
$order_url = "https://accept.paymob.com/api/ecommerce/orders";
$order_data = [
"auth_token" => $auth_token,
"delivery_needed" => false,
"amount_cents" => $amount,
"currency" => "EGP",
"merchant_order_id" => uniqid("DRV_"),
"items" => []
];
$response = callAPI("POST", $order_url, json_encode($order_data));
$order_id = $response->id ?? null;
if (!$order_id) {
error_log("❌ Failed to create order for driver wallet!");
die("❌ Failed to create order for driver wallet!");
}
// 3⃣ PAYMENT KEY
$payment_key_url = "https://accept.paymob.com/api/acceptance/payment_keys";
$payment_key_data = [
"auth_token" => $auth_token,
"amount_cents" => $amount,
"expiration" => 3600,
"order_id" => $order_id,
"billing_data" => [
"first_name" => $first_name,
"last_name" => $last_name,
"email" => $email,
"phone_number" => $phone_number,
"country" => "EG",
"city" => "Cairo",
"state" => "Nasr City",
"street" => "Driver Zone",
"building" => "5",
"apartment" => "D1",
"floor" => "1",
"postal_code" => "11765",
"shipping_method" => "driver_wallet"
],
"currency" => "EGP",
"integration_id" => $integration_id
];
$response = callAPI("POST", $payment_key_url, json_encode($payment_key_data));
$payment_token = $response->token ?? null;
if (!$payment_token) {
error_log("❌ Failed to get PAYMENT TOKEN for driver!");
die("❌ Failed to get PAYMENT TOKEN for driver!");
}
// 4⃣ Final Step: Pay with Wallet
$redirect_url = payWithWallet($payment_token, $wallet_phone);
if ($redirect_url) {
printSuccess($redirect_url);
error_log("✅ redirect_url (driver): " . $redirect_url);
} else {
error_log("❌ Driver wallet payment failed!");
printFailure("Payment verified, but failed to redirect.");
}
// 🔁 Shared helper functions
function callAPI($method, $url, $data)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ["Content-Type: application/json"]
]);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response);
}
function payWithWallet($paymentToken, $walletPhone)
{
$url = "https://accept.paymob.com/api/acceptance/payments/pay";
$data = [
"source" => [
"identifier" => $walletPhone,
"subtype" => "WALLET"
],
"payment_token" => $paymentToken
];
$response = callAPI("POST", $url, json_encode($data));
return $response->redirect_url ?? null;
}

View File

@@ -1,146 +0,0 @@
<?php
include "../../../connect.php";
define('BASE_URL', 'https://wl.tripz-egypt.com/v1/main/ride');
try {
$driverId = filterRequest('driverID');
$user_id = filterRequest('user_id');
$paymentMethod = filterRequest('paymentMethod');
if (empty($user_id) || empty($driverId)) {
printFailure('Missing user_id or driverID.');
exit;
}
// 1⃣ تحقق من سجل الدفع خلال آخر دقيقتين
$stmt = $con->prepare(
'SELECT * FROM payment_log_driver
WHERE user_id = :uid
AND created_at >= DATE_SUB(NOW(), INTERVAL 2 MINUTE)
ORDER BY created_at DESC LIMIT 1'
);
$stmt->execute([':uid' => $user_id]);
$payment = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$payment || $payment['status'] != 1) {
printFailure('No valid payment found.');
exit;
}
$originalAmount = floatval($payment['amount']);
$bonus = match ((int)$originalAmount) {
80 => 80.0,
200 => 215.0,
400 => 450.0,
1000 => 1140.0,
default => $originalAmount,
};
// 2⃣ توكن لـ DriverWallet
$tokenDriver = generateToken($con, $driverId, $bonus);
if (!$tokenDriver) {
printFailure('Failed to generate token for driver wallet.');
exit;
}
// 3⃣ توكن مستقل لـ SeferWallet
$tokenSefer = generateToken($con, $driverId, $originalAmount);
if (!$tokenSefer) {
printFailure('Failed to generate token for sefer wallet.');
exit;
}
// 4⃣ Payment ID
$paymentID = generatePaymentID($con, $driverId, $bonus, $paymentMethod);
if (!$paymentID) {
printFailure('Failed to generate payment ID.');
exit;
}
// 5⃣ Insert into driverWallet
$insertDriver = $con->prepare("INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driverID, :paymentID, :amount, :paymentMethod)");
$insertDriver->execute([
':driverID' => $driverId,
':paymentID' => $paymentID,
':amount' => $bonus,
':paymentMethod' => $paymentMethod
]);
if ($insertDriver->rowCount() === 0) {
printFailure('Failed to insert into driverWallet.');
exit;
}
// 6⃣ Update tokenDriver to isUsed = TRUE
$markTokenDriver = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token");
$markTokenDriver->execute([':token' => $tokenDriver]);
// 7⃣ Insert into seferWallet
$insertSefer = $con->prepare("INSERT INTO seferWallet (driverId, passengerId, amount, paymentMethod, token, createdAt)
VALUES (:driverId, :passengerId, :amount, :paymentMethod, :token, CURRENT_TIMESTAMP)");
$insertSefer->execute([
':driverId' => $driverId,
':passengerId' => 'driver',
':amount' => $originalAmount,
':paymentMethod' => $paymentMethod,
':token' => $tokenSefer
]);
// 8⃣ Update tokenSefer to isUsed = TRUE
$markTokenSefer = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token");
$markTokenSefer->execute([':token' => $tokenSefer]);
// 🎉 Success response
printSuccess([
'message' => 'Payment verified and all wallets updated successfully.',
'amount' => $originalAmount,
'bonus' => $bonus,
'paymentID' => $paymentID,
'tokenUsed' => [
'driverWalletToken' => $tokenDriver,
'seferWalletToken' => $tokenSefer
]
]);
} catch (Throwable $e) {
printFailure("Server error: " . $e->getMessage());
}
// ───────────────────────────
// FUNCTIONS
// ───────────────────────────
function generateToken($con, $driverId, $amount): ?string {
global $secretKey;
// نفس المنطق من سكربتك
$data = $driverId . $amount . time();
$data .= $secretKey;
$hash = hash('sha256', $data);
$randomBytes = bin2hex(random_bytes(16));
$token = substr($hash . $randomBytes, 0, 64);
// تخزين التوكن في قاعدة البيانات
$stmt = $con->prepare("INSERT INTO payment_tokens (token, driverID, dateCreated, amount)
VALUES (:token, :driverID, NOW(), :amount)");
$stmt->execute([
':token' => $token,
':driverID' => $driverId,
':amount' => $amount
]);
return $stmt->rowCount() > 0 ? $token : null;
}
function generatePaymentID($con, $driverId, $amount, $method): ?string {
$stmt = $con->prepare("INSERT INTO paymentsDriverPoints (`amount`, `payment_method`, `driverID`)
VALUES (:amount, :method, :driverID)");
$stmt->execute([
':driverID' => $driverId,
':amount' => $amount,
':method' => $method
]);
return $stmt->rowCount() > 0 ? $con->lastInsertId() : null;
}

View File

@@ -1,110 +0,0 @@
<?php
// paymob_payout.php
// سكريبت بي ات بي لمعاملات Paymob Payout (محفظة وبنك) بدون تخزين في قاعدة البيانات
declare(strict_types=1);
include '../../../connect.php'; // يعطيك $con، filterRequest(), printSuccess(), printFailure()
// 1) جلب باراميترات الطلب عبر filterRequest
$driverId = filterRequest('driverID');
$amount = filterRequest('amount');
$method = filterRequest('method'); // 'wallet' أو 'bank'
$msisdn = filterRequest('msisdn');
$bankCard = filterRequest('bankCard'); // يُستعمل عند method == 'bank'
$bankCode = filterRequest('bankCode'); // يُستعمل عند method == 'bank'
if (empty($driverId) || empty($amount) || empty($method)) {
printFailure('Missing parameters');
exit;
}
// 2) جلب بيانات Paymob من البيئة (Environment Variables)
$pmUser = getenv('payMobOutUserName');
$pmPass = getenv('payMobOutPassword');
$pmClientId = getenv('PAYMOBOUTCLIENT_ID'); // من static const pmobid
$pmSecret = getenv('PAYMOBOUTCLIENTSECRET'); // من static const pmobsec
// 3) دالة للحصول على OAuth Token من Paymob
function fetchPaymobToken(string $user, string $pass, string $cid, string $secret): ?string {
$ch = curl_init('https://payouts.paymobsolutions.com/api/secure/o/token/');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'password',
'username' => $user,
'password' => $pass,
'client_id' => $cid,
'client_secret' => $secret,
]),
]);
$resp = curl_exec($ch);
if (!$resp) return null;
$data = json_decode($resp, true);
return $data['access_token'] ?? null;
}
$oauthToken = fetchPaymobToken($pmUser, $pmPass, $pmClientId, $pmSecret);
if (!$oauthToken) {
printFailure('Failed to retrieve Paymob token');
exit;
}
// 4) دوال صرف الأموال
function disburseWallet(string $token, string $amt, string $msisdn): array {
$ch = curl_init('https://payouts.paymobsolutions.com/api/secure/disburse/');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $token",
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'amount' => $amt,
'issuer' => 'wallet',
'msisdn' => $msisdn,
]),
]);
$resp = curl_exec($ch);
return $resp ? json_decode($resp, true) : [];
}
function disburseBank(string $token, string $amt, string $card, string $code): array {
$ch = curl_init('https://payouts.paymobsolutions.com/api/secure/disburse/');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $token",
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'amount' => $amt,
'issuer' => 'bank_card',
'bank_card_number' => $card,
'bank_code' => $code,
'bank_transaction_type' => 'cash_transfer',
]),
]);
$resp = curl_exec($ch);
return $resp ? json_decode($resp, true) : [];
}
// 5) استدعاء الدالة المناسبة وتنفيذ الصرف
if ($method === 'wallet') {
$result = disburseWallet($oauthToken, $amount, $msisdn);
} else {
$result = disburseBank($oauthToken, $amount, $bankCard, $bankCode);
}
// 6) التحقق من نجاح الصرف وإرجاع النتيجة
if (empty($result) || ($result['disbursement_status'] ?? '') !== 'successful') {
printFailure('Disbursement failed');
exit;
}
// 7) إرجاع التوكن والنتيجة للعميل بدون تخزين في DB
printSuccess( $result);
?>

View File

@@ -1,142 +0,0 @@
<?php
include "../../../jwtconnect.php";
// ------------------------------
// قراءة HMAC من الهيدر أو من الـ query
// ------------------------------
$received_hmac = $_SERVER['HTTP_HMAC'] ?? ($_GET['hmac'] ?? '');
$received_hmac = trim($received_hmac);
// ------------------------------
// قراءة البيانات القادمة من Paymob
// ------------------------------
$raw_body = file_get_contents("php://input");
$data = json_decode($raw_body, true);
// ------------------------------
// المفتاح السري
// ------------------------------
$secret_key = getenv('hmacPaymob');
// ------------------------------
// دالة لتحويل القيم إلى النصوص
// ------------------------------
function normalize($value) {
if ($value === true) return 'true';
if ($value === false) return 'false';
if (is_null($value)) return '';
return (string)$value;
}
// ------------------------------
// التحقق من صحة HMAC
// ------------------------------
function isValidHmac($data, $secret_key, $received_hmac) {
if (!isset($data['obj'])) return false;
$obj = $data['obj'];
// دمج جميع الحقول بشكل متسلسل
$fields = [
normalize($obj['amount_cents'] ?? ''),
normalize($obj['created_at'] ?? ''),
normalize($obj['currency'] ?? ''),
normalize($obj['error_occured'] ?? false),
normalize($obj['has_parent_transaction'] ?? false),
normalize($obj['id'] ?? ''),
normalize($obj['integration_id'] ?? ''),
normalize($obj['is_3d_secure'] ?? false),
normalize($obj['is_auth'] ?? false),
normalize($obj['is_capture'] ?? false),
normalize($obj['is_refunded'] ?? false),
normalize($obj['is_standalone_payment'] ?? false),
normalize($obj['is_voided'] ?? false),
normalize($obj['order']['id'] ?? ''),
normalize($obj['owner'] ?? ''),
normalize($obj['pending'] ?? false),
normalize($obj['source_data']['pan'] ?? ''),
normalize($obj['source_data']['sub_type'] ?? ''),
normalize($obj['source_data']['type'] ?? ''),
normalize($obj['success'] ?? false)
];
// دمج الحقول في رسالة واحدة
$message = implode('', $fields);
// حساب HMAC باستخدام المفتاح السري
$calculated_hmac = hash_hmac('sha512', $message, $secret_key);
//
/*طباعة الرسائل لأغراض التصحيح
error_log("🔐 Message used for HMAC: " . $message);
error_log("🔐 Calculated HMAC: " . $calculated_hmac);
error_log("📩 Received HMAC: " . $received_hmac);
error_log("Calculated HMAC length: " . strlen($calculated_hmac));
error_log("Received HMAC length: " . strlen($received_hmac));
*/
// التحقق من تطابق HMAC
if (hash_equals($calculated_hmac, $received_hmac)) {
error_log("✅ Valid HMAC signature verified.");
return $calculated_hmac;
} else {
http_response_code(401);
echo json_encode(["error" => "Unauthorized Invalid HMAC"]);
exit;
}
}
isValidHmac($data, $secret_key, $received_hmac);
// ------------------------------
// إذا كانت HMAC صحيحة، نتابع العملية
// ------------------------------
if ($data && isset($data['obj'])) {
$transaction = $data['obj'];
$payment_id = $transaction['id'] ?? null;
$amount = $transaction['amount_cents'] ?? 0;
$status = $transaction['success'] ?? false;
$is_voided = $transaction['is_voided'] ?? false;
$is_refunded = $transaction['is_refunded'] ?? false;
$order_id = $transaction['order']['id'] ?? null;
$merchant_order_id = $transaction['order']['merchant_order_id'] ?? null;
$payment_method = $transaction['source_data']['type'] ?? 'unknown';
$card_last4 = $transaction['source_data']['pan'] ?? '****';
$transaction_type = $transaction['data']['migs_transaction']['type'] ?? 'UNKNOWN';
$created_at = $transaction['created_at'] ?? date("Y-m-d H:i:s");
$user_id = $transaction['order']['shipping_data']['phone_number'];
$user_id='+2'. $user_id;
$amount=$amount/100;
// التحقق من حالة الدفع
if (!$status) {
error_log("❌ Invalid payment status: " . $status);
echo json_encode(["error" => "Invalid payment status"]);
exit;
}
// إضافة البيانات إلى قاعدة البيانات
$query = "INSERT INTO payment_log_driver (`payment_id`, `user_id`, `amount`, `status`)
VALUES (:payment_id, :user_id, :amount, :status)";
$stmt = $con->prepare($query);
$stmt->bindParam(':payment_id', $payment_id);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':amount', $amount);
$stmt->bindParam(':status', $status);
try {
$stmt->execute();
if ($stmt->rowCount() > 0) {
http_response_code(200);
echo json_encode(["success" => true, "message" => "Payment data saved successfully"]);
error_log("Payment data saved successfully" . $status);
} else {
http_response_code(200);
echo json_encode(["success" => false, "message" => "Payment data already up to date."]);
}
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(["error" => "Failed to execute the query: " . $e->getMessage()]);
}
}
?>

View File

@@ -1,142 +0,0 @@
<?php
include "../../../jwtconnect.php";
// ------------------------------
// قراءة HMAC من الهيدر أو من الـ query
// ------------------------------
$received_hmac = $_SERVER['HTTP_HMAC'] ?? ($_GET['hmac'] ?? '');
$received_hmac = trim($received_hmac);
// ------------------------------
// قراءة البيانات القادمة من Paymob
// ------------------------------
$raw_body = file_get_contents("php://input");
$data = json_decode($raw_body, true);
// ------------------------------
// المفتاح السري
// ------------------------------
$secret_key = getenv('hmacPaymob');
// ------------------------------
// دالة لتحويل القيم إلى النصوص
// ------------------------------
function normalize($value) {
if ($value === true) return 'true';
if ($value === false) return 'false';
if (is_null($value)) return '';
return (string)$value;
}
// ------------------------------
// التحقق من صحة HMAC
// ------------------------------
function isValidHmac($data, $secret_key, $received_hmac) {
if (!isset($data['obj'])) return false;
$obj = $data['obj'];
// دمج جميع الحقول بشكل متسلسل
$fields = [
normalize($obj['amount_cents'] ?? ''),
normalize($obj['created_at'] ?? ''),
normalize($obj['currency'] ?? ''),
normalize($obj['error_occured'] ?? false),
normalize($obj['has_parent_transaction'] ?? false),
normalize($obj['id'] ?? ''),
normalize($obj['integration_id'] ?? ''),
normalize($obj['is_3d_secure'] ?? false),
normalize($obj['is_auth'] ?? false),
normalize($obj['is_capture'] ?? false),
normalize($obj['is_refunded'] ?? false),
normalize($obj['is_standalone_payment'] ?? false),
normalize($obj['is_voided'] ?? false),
normalize($obj['order']['id'] ?? ''),
normalize($obj['owner'] ?? ''),
normalize($obj['pending'] ?? false),
normalize($obj['source_data']['pan'] ?? ''),
normalize($obj['source_data']['sub_type'] ?? ''),
normalize($obj['source_data']['type'] ?? ''),
normalize($obj['success'] ?? false)
];
// دمج الحقول في رسالة واحدة
$message = implode('', $fields);
// حساب HMAC باستخدام المفتاح السري
$calculated_hmac = hash_hmac('sha512', $message, $secret_key);
//
/*طباعة الرسائل لأغراض التصحيح
error_log("🔐 Message used for HMAC: " . $message);
error_log("🔐 Calculated HMAC: " . $calculated_hmac);
error_log("📩 Received HMAC: " . $received_hmac);
error_log("Calculated HMAC length: " . strlen($calculated_hmac));
error_log("Received HMAC length: " . strlen($received_hmac));
*/
// التحقق من تطابق HMAC
if (hash_equals($calculated_hmac, $received_hmac)) {
error_log("✅ Valid HMAC signature verified.");
return $calculated_hmac;
} else {
http_response_code(401);
echo json_encode(["error" => "Unauthorized Invalid HMAC"]);
exit;
}
}
isValidHmac($data, $secret_key, $received_hmac);
// ------------------------------
// إذا كانت HMAC صحيحة، نتابع العملية
// ------------------------------
if ($data && isset($data['obj'])) {
$transaction = $data['obj'];
$payment_id = $transaction['id'] ?? null;
$amount = $transaction['amount_cents'] ?? 0;
$status = $transaction['success'] ?? false;
$is_voided = $transaction['is_voided'] ?? false;
$is_refunded = $transaction['is_refunded'] ?? false;
$order_id = $transaction['order']['id'] ?? null;
$merchant_order_id = $transaction['order']['merchant_order_id'] ?? null;
$payment_method = $transaction['source_data']['type'] ?? 'unknown';
$card_last4 = $transaction['source_data']['pan'] ?? '****';
$transaction_type = $transaction['data']['migs_transaction']['type'] ?? 'UNKNOWN';
$created_at = $transaction['created_at'] ?? date("Y-m-d H:i:s");
$user_id = $transaction['order']['shipping_data']['phone_number'];
$user_id='+'. $user_id;
$amount=$amount/100;
// التحقق من حالة الدفع
if (!$status) {
error_log("❌ Invalid payment status: " . $status);
echo json_encode(["error" => "Invalid payment status"]);
exit;
}
// إضافة البيانات إلى قاعدة البيانات
$query = "INSERT INTO payment_log_driver (`payment_id`, `user_id`, `amount`, `status`)
VALUES (:payment_id, :user_id, :amount, :status)";
$stmt = $con->prepare($query);
$stmt->bindParam(':payment_id', $payment_id);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':amount', $amount);
$stmt->bindParam(':status', $status);
try {
$stmt->execute();
if ($stmt->rowCount() > 0) {
http_response_code(200);
echo json_encode(["success" => true, "message" => "Payment data saved successfully"]);
error_log("Payment data saved successfully" . $status);
} else {
http_response_code(200);
echo json_encode(["success" => false, "message" => "Payment data already up to date."]);
}
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(["error" => "Failed to execute the query: " . $e->getMessage()]);
}
}
?>

View File

@@ -1,33 +0,0 @@
Transaction ID: 275749381
Amount (EGP): 25
Order ID: 308769116
Merchant Order ID: 67db4baf5ad92
Payment Method: card (Last 4: 2346)
Transaction Type: PAYMENT
Success: Yes
Voided: No
Refunded: No
Created At: 2025-03-20T00:57:04.742244
----------------------------
Transaction ID: 275751796
Amount (EGP): 25
Order ID: 308771809
Merchant Order ID: 67db4dc9f0427
Payment Method: card (Last 4: 2346)
Transaction Type: PAYMENT
Success: Yes
Voided: No
Refunded: No
Created At: 2025-03-20T01:06:02.249734
----------------------------
Transaction ID: 275752145
Amount (EGP): 25
Order ID: 308772211
Merchant Order ID: 67db4e263aafe
Payment Method: card (Last 4: 2346)
Transaction Type: PAYMENT
Success: Yes
Voided: No
Refunded: No
Created At: 2025-03-20T01:07:31.653223
----------------------------

View File

@@ -1,137 +0,0 @@
<?php
include "../../jwtconnect.php";
// ------------------------------
// قراءة HMAC من الهيدر أو من الـ query
// ------------------------------
$received_hmac = $_SERVER['HTTP_HMAC'] ?? ($_GET['hmac'] ?? '');
$received_hmac = trim($received_hmac);
// ------------------------------
// قراءة البيانات القادمة من Paymob
// ------------------------------
$raw_body = file_get_contents("php://input");
$data = json_decode($raw_body, true);
// ------------------------------
// المفتاح السري
// ------------------------------
$secret_key = getenv('hmacPaymob');
// ------------------------------
// دالة لتحويل القيم إلى النصوص
// ------------------------------
function normalize($value) {
if ($value === true) return 'true';
if ($value === false) return 'false';
if (is_null($value)) return '';
return (string)$value;
}
// ------------------------------
// التحقق من صحة HMAC
// ------------------------------
function isValidHmac($data, $secret_key, $received_hmac) {
if (!isset($data['obj'])) return false;
$obj = $data['obj'];
// دمج جميع الحقول بشكل متسلسل
$fields = [
normalize($obj['amount_cents'] ?? ''),
normalize($obj['created_at'] ?? ''),
normalize($obj['currency'] ?? ''),
normalize($obj['error_occured'] ?? false),
normalize($obj['has_parent_transaction'] ?? false),
normalize($obj['id'] ?? ''),
normalize($obj['integration_id'] ?? ''),
normalize($obj['is_3d_secure'] ?? false),
normalize($obj['is_auth'] ?? false),
normalize($obj['is_capture'] ?? false),
normalize($obj['is_refunded'] ?? false),
normalize($obj['is_standalone_payment'] ?? false),
normalize($obj['is_voided'] ?? false),
normalize($obj['order']['id'] ?? ''),
normalize($obj['owner'] ?? ''),
normalize($obj['pending'] ?? false),
normalize($obj['source_data']['pan'] ?? ''),
normalize($obj['source_data']['sub_type'] ?? ''),
normalize($obj['source_data']['type'] ?? ''),
normalize($obj['success'] ?? false)
];
// دمج الحقول في رسالة واحدة
$message = implode('', $fields);
// حساب HMAC باستخدام المفتاح السري
$calculated_hmac = hash_hmac('sha512', $message, $secret_key);
// طباعة الرسائل لأغراض التصحيح
// error_log("🔐 Message used for HMAC: " . $message);
// error_log("🔐 Calculated HMAC: " . $calculated_hmac);
// error_log("📩 Received HMAC: " . $received_hmac);
// error_log("Calculated HMAC length: " . strlen($calculated_hmac));
// error_log("Received HMAC length: " . strlen($received_hmac));
// التحقق من تطابق HMAC
if (hash_equals($calculated_hmac, $received_hmac)) {
error_log("✅ Valid HMAC signature verified.");
return $calculated_hmac;
} else {
http_response_code(401);
echo json_encode(["error" => "Unauthorized Invalid HMAC"]);
exit;
}
}
isValidHmac($data, $secret_key, $received_hmac);
// ------------------------------
// إذا كانت HMAC صحيحة، نتابع العملية
// ------------------------------
if ($data && isset($data['obj'])) {
$transaction = $data['obj'];
$payment_id = $transaction['id'] ?? null;
$amount = $transaction['amount_cents'] ?? 0;
$status = $transaction['success'] ?? false;
$is_voided = $transaction['is_voided'] ?? false;
$is_refunded = $transaction['is_refunded'] ?? false;
$order_id = $transaction['order']['id'] ?? null;
$merchant_order_id = $transaction['order']['merchant_order_id'] ?? null;
$payment_method = $transaction['source_data']['type'] ?? 'unknown';
$card_last4 = $transaction['source_data']['pan'] ?? '****';
$transaction_type = $transaction['data']['migs_transaction']['type'] ?? 'UNKNOWN';
$created_at = $transaction['created_at'] ?? date("Y-m-d H:i:s");
$user_id = $transaction['order']['shipping_data']['phone_number'];
// التحقق من حالة الدفع
if (!$status) {
error_log("❌ Invalid payment status: " . $status);
echo json_encode(["error" => "Invalid payment status"]);
exit;
}
// إضافة البيانات إلى قاعدة البيانات
$query = "INSERT INTO paymentsLog (`payment_id`, `user_id`, `amount`, `status`)
VALUES (:payment_id, :user_id, :amount, :status)";
$stmt = $con->prepare($query);
$stmt->bindParam(':payment_id', $payment_id);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':amount', $amount);
$stmt->bindParam(':status', $status);
try {
$stmt->execute();
if ($stmt->rowCount() > 0) {
http_response_code(200);
echo json_encode(["success" => true, "message" => "Payment data saved successfully"]);
} else {
http_response_code(200);
echo json_encode(["success" => false, "message" => "Payment data already up to date."]);
}
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(["error" => "Failed to execute the query: " . $e->getMessage()]);
}
}
?>

View File

@@ -1,27 +0,0 @@
[21-Mar-2025 19:37:11 Europe/Berlin] PHP Notice: Array to string conversion in /home2/seferli1/wallet.sefer.live/seferpw.shop/sefer/ride/payMob/wallet/paymob_webhook.php on line 15
[21-Mar-2025 19:37:11 Europe/Berlin] Data: Array
[21-Mar-2025 19:37:11 Europe/Berlin] ✅ Valid HMAC signature verified.
[21-Mar-2025 19:37:11 Europe/Berlin] ❌ Invalid payment status:
[21-Mar-2025 19:37:11 Europe/Berlin] ❌ فشل الدفع عبر المحفظة!
[21-Mar-2025 19:37:11 Europe/Berlin]
[21-Mar-2025 19:38:41 Europe/Berlin] PHP Notice: Array to string conversion in /home2/seferli1/wallet.sefer.live/seferpw.shop/sefer/ride/payMob/wallet/paymob_webhook.php on line 15
[21-Mar-2025 19:38:41 Europe/Berlin] Data: Array
[21-Mar-2025 19:38:41 Europe/Berlin] ✅ Valid HMAC signature verified.
[21-Mar-2025 19:38:41 Europe/Berlin] ❌ Invalid payment status:
[21-Mar-2025 19:38:41 Europe/Berlin] ❌ فشل الدفع عبر المحفظة!
[21-Mar-2025 19:38:41 Europe/Berlin]
[21-Mar-2025 19:39:40 Europe/Berlin] PHP Notice: Array to string conversion in /home2/seferli1/wallet.sefer.live/seferpw.shop/sefer/ride/payMob/wallet/paymob_webhook.php on line 15
[21-Mar-2025 19:39:40 Europe/Berlin] Data: Array
[21-Mar-2025 19:39:40 Europe/Berlin] ✅ Valid HMAC signature verified.
[21-Mar-2025 19:39:40 Europe/Berlin] ❌ Invalid payment status:
[21-Mar-2025 19:39:40 Europe/Berlin] ❌ فشل الدفع عبر المحفظة!
[21-Mar-2025 19:41:14 Europe/Berlin] ✅ Valid HMAC signature verified.
[21-Mar-2025 19:41:14 Europe/Berlin] ❌ Invalid payment status:
[21-Mar-2025 19:41:14 Europe/Berlin] ❌ فشل الدفع عبر المحفظة!
[21-Mar-2025 19:41:58 Europe/Berlin] ✅ Valid HMAC signature verified.
[21-Mar-2025 19:41:58 Europe/Berlin] ❌ Invalid payment status:
[21-Mar-2025 19:41:59 Europe/Berlin] ❌ فشل الدفع عبر المحفظة!
[21-Mar-2025 19:43:19 Europe/Berlin] redirect_url ishttps://vcheckout.paymobsolutions.com/checkout/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDI1ODI4OTksImlkIjo2MTk5MDYyNzI0fQ.KH7jKKINyVzxJMH9IT2MyiAXRK_yMHVw-f4pIzyHzj0
[22-Mar-2025 15:38:59 Europe/Berlin] ✅ Valid HMAC signature verified.
[22-Mar-2025 15:38:59 Europe/Berlin] ❌ Invalid payment status:
[22-Mar-2025 15:39:00 Europe/Berlin] ❌ فشل الدفع عبر المحفظة!

View File

@@ -1,129 +0,0 @@
<?php
include "../../../connect.php";
// 1. احصل على AUTH TOKEN
$api_key = getenv("payMobApiKey1");
$integration_id = getenv("paymobIntegratedIdWallet");
$email = filterRequest("email");
$first_name = filterRequest("first_name");
$last_name = filterRequest("last_name");
$phone_number = filterRequest("phone_number");
$wallet_phone = filterRequest("phone_number");
$amount = filterRequest("amount");
$auth_url = "https://accept.paymob.com/api/auth/tokens";
$auth_data = json_encode(["api_key" => $api_key]);
$response = callAPI("POST", $auth_url, $auth_data);
$auth_token = $response->token ?? null;
if (!$auth_token) {
error_log("❌ فشل الحصول على AUTH TOKEN!");
die("❌ فشل الحصول على AUTH TOKEN!");
}
// 2. أنشئ الطلب ORDER
$order_url = "https://accept.paymob.com/api/ecommerce/orders";
$order_data = [
"auth_token" => $auth_token,
"delivery_needed" => false,
"amount_cents" => $amount,
"currency" => "EGP",
"merchant_order_id" => uniqid(),
"items" => []
];
$response = callAPI("POST", $order_url, json_encode($order_data));
$order_id = $response->id ?? null;
if (!$order_id) {
error_log("❌ فشل إنشاء الطلب!");
die("❌ فشل إنشاء الطلب!");
}
// error_log("orde is" .$order_id);
// 3. احصل على Payment Key
$payment_key_url = "https://accept.paymob.com/api/acceptance/payment_keys";
$payment_key_data = [
"auth_token" => $auth_token,
"amount_cents" => $amount,
"expiration" => 3600,
"order_id" => $order_id,
"billing_data" => [
"first_name" => $first_name,
"last_name" => $last_name,
"email" => $email,
"phone_number" => $phone_number,
"country" => "EG",
"city" => "Cairo",
"state" => "shobra",
"street" => "Test St.",
"building" => "1",
"apartment" => "10",
"floor" => "2",
"postal_code" => "12345",
"shipping_method" => "wallet"
],
"currency" => "EGP",
"integration_id" => $integration_id // إذا كان مضبوط
];
$response = callAPI("POST", $payment_key_url, json_encode($payment_key_data));
$payment_token = $response->token ?? null;
// error_log("payment_token is" .$payment_token);
if (!$payment_token) {
error_log("❌ فشل الحصول على PAYMENT TOKEN!");
die("❌ فشل الحصول على PAYMENT TOKEN!");
}
// error_log("phone wallet is ".$wallet_phone);
// 4. الدفع عبر المحفظة Wallet
$redirect_url = payWithWallet($payment_token, $wallet_phone);
if ($redirect_url) {
printSuccess($redirect_url);
error_log("redirect_url is" .$redirect_url);
} else {
error_log("❌ فشل الدفع عبر المحفظة!");
printFailure("Payment verified, but failed to generate token.");
// die("❌ فشل الدفع عبر المحفظة!");
}
// دالة لطلب API عبر CURL
function callAPI($method, $url, $data)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ["Content-Type: application/json"]
]);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response);
}
// الدالة الخاصة بالدفع بالمحفظة
function payWithWallet($paymentToken, $walletPhone)
{
$url = "https://accept.paymob.com/api/acceptance/payments/pay";
$data = [
"source" => [
"identifier" => $walletPhone,
"subtype" => "WALLET"
],
"payment_token" => $paymentToken
];
// Log the full data being sent to Paymob
// error_log("Data being sent to Paymob: " . json_encode($data));
$response = callAPI("POST", $url, json_encode($data));
// Log the full response for debugging
// error_log("Payment response: " . print_r($response, true));
return $response->redirect_url ?? null;
}

View File

@@ -1,358 +0,0 @@
<?php
include "../../../connect.php";
define("BASE_URL", "https://wl.tripz-egypt.com/v1/main/ride");
define("LOG_FILE", "../logs/payment_verification.log"); // Define log file path
// Function to write to error log
function logError($step, $message, $data = null) {
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[{$timestamp}] STEP {$step}: {$message}";
if ($data !== null) {
$logEntry .= " | Data: " . json_encode($data);
}
// Ensure log directory exists
$logDir = dirname(LOG_FILE);
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// Append to log file
file_put_contents(LOG_FILE, $logEntry . PHP_EOL, FILE_APPEND);
// Also log to PHP error log for server monitoring
// error_log("PAYMENT_VERIFICATION: {$logEntry}");
}
// Receive parameters from GET request
$user_id = filterRequest("user_id");
$passengerId = filterRequest("passengerId");
$paymentMethod = filterRequest("paymentMethod");
// Log initial request
// logError("0", "Request received", [
// "user_id" => $user_id,
// "passengerId" => $passengerId
// ]);
// Validate user_id and passengerId
if (!$user_id || !$passengerId) {
// logError("1", "Invalid parameters", [
// "user_id" => $user_id,
// "passengerId" => $passengerId
// ]);
printFailure("Invalid user ID or passenger ID.");
exit;
}
try {
// Step 1: Get the latest successful payment
// logError("1", "Querying latest payment", ["user_id" => $user_id]);
$stmt = $con->prepare("SELECT * FROM paymentsLog WHERE user_id = :user_id AND created_at >= DATE_SUB(NOW(), INTERVAL 2 MINUTE)
ORDER BY created_at DESC
LIMIT 1");
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
$stmt->execute();
$payment = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$payment) {
logError("1", "No payment found", ["user_id" => $user_id]);
printFailure("No payment data found.");
exit;
}
// logError("1", "Payment found", [
// "payment_id" => $payment['id'] ?? 'unknown',
// "status" => $payment['status'],
// "amount" => $payment['amount']/100 ?? 'unknown'
// ]);
// Step 2: Check payment status
if ($payment['status'] != 1) {
// logError("2", "Payment not successful", ["status" => $payment['status']]);
printFailure("Payment is not successful yet.");
exit;
}
// logError("2", "Payment status verified", ["status" => $payment['status']]);
$amount = $payment['amount']/100; // Paid amount
// Step 3: Calculate bonus based on the paid amount
// logError("3", "Calculating bonus", ["amount" => $amount]);
$finalAmount = calculateBonus($amount);
if ($finalAmount <= 0) {
// logError("3", "Bonus calculation failed", [
// "original_amount" => $amount,
// "calculated_amount" => $finalAmount
// ]);
printFailure("Invalid amount for bonus calculation.");
exit;
}
// logError("3", "Bonus calculated", [
// "original_amount" => $amount,
// "final_amount" => $finalAmount
// ]);
// // Step 4: Generate payment token
// logError("4", "Generating payment token", [
// "passengerId" => $passengerId,
// "amount" => $finalAmount
// ]);
$token = generatePaymentToken($passengerId, $finalAmount);
if (!$token) {
// logError("4", "Token generation failed");
printFailure("Payment verified, but failed to generate token.");
exit;
}
// logError("4", "Token generated successfully", ["token_length" => strlen($token)]);
// // Step 5: Add balance to passenger's wallet
// logError("5", "Adding balance to passenger wallet", [
// "passengerId" => $passengerId,
// "amount" => $finalAmount
// ]);
$walletResult = addToPassengerWallet($passengerId, $finalAmount, $token);
if (!$walletResult || !isset($walletResult['status']) || $walletResult['status'] != "success") {
// logError("5", "Failed to add balance to passenger wallet", $walletResult);
printFailure("Payment verified, but failed to add balance to passenger wallet.");
exit;
}
// logError("5", "Balance added to passenger wallet", $walletResult);
// Step 6: Add balance to Sefer wallet
// logError("6", "Adding balance to Sefer wallet", [
// "passengerId" => $passengerId,
// "amount" => $finalAmount,
// "paymentMethod" => $paymentMethod
// ]);
$token = generatePaymentToken($passengerId, $finalAmount);
if (!$token) {
// logError("4", "Token generation failed");
printFailure("Payment verified, but failed to generate token.");
exit;
}
// logError("4", "Token generated successfully", ["token_length" => strlen($token)]);
$seferWalletResult = addToSeferWallet($passengerId, $amount, $paymentMethod);
if (!$seferWalletResult || !isset($seferWalletResult['status']) || $seferWalletResult['status'] != "success") {
// logError("6", "Failed to add balance to Sefer wallet", $seferWalletResult);
printFailure("Payment verified, but failed to add balance to Sefer wallet.");
exit;
}
// logError("6", "Balance added to Sefer wallet", $seferWalletResult);
// // Final success
// logError("7", "Process completed successfully", [
// "payment_id" => $payment['id'] ?? 'unknown',
// "amount" => $finalAmount,
// "passengerId" => $passengerId
// ]);
printSuccess( "Payment data saved successfully");
} catch (PDOException $e) {
logError("ERROR", "Database error: " . $e->getMessage());
printFailure("Database error occurred.");
} catch (Exception $e) {
logError("ERROR", "General error: " . $e->getMessage());
printFailure("An error occurred during payment verification.");
}
// 🎯 Function to generate payment token with error logging
function generatePaymentToken($passengerId, $amount) {
$url = BASE_URL . "/passengerWallet/addPaymentTokenPassenger.php";
$postData = [
'passengerId' => $passengerId,
'amount' => $amount
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
logError("4.1", "cURL error in token generation", [
"error" => $curlError,
"url" => $url
]);
return null;
}
if ($httpCode != 200) {
logError("4.2", "HTTP error in token generation", [
"http_code" => $httpCode,
"response" => $response
]);
return null;
}
$data = json_decode($response, true);
if (!$data || !isset($data['message'])) {
logError("4.3", "Invalid response format in token generation", [
"response" => $response
]);
return null;
}
return $data['message']; // ✅ Return token
}
// 🎯 Function to add balance to passenger's wallet with error logging
function addToPassengerWallet($passengerId, $amount, $token) {
$url = BASE_URL . "/passengerWallet/add.php";
$postData = [
'passenger_id' => $passengerId,
'balance' => $amount,
'token' => $token
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
logError("5.1", "cURL error in passenger wallet update", [
"error" => $curlError,
"url" => $url
]);
return null;
}
if ($httpCode != 200) {
logError("5.2", "HTTP error in passenger wallet update", [
"http_code" => $httpCode,
"response" => $response
]);
return null;
}
$data = json_decode($response, true);
if (!$data) {
logError("5.3", "Invalid response format in passenger wallet update", [
"response" => $response
]);
return null;
}
return $data; // ✅ Return result
}
// 🎯 Function to add balance to Sefer wallet with error logging
function addToSeferWallet($passengerId, $amount, $paymentMethod) {
// Generate a new token specifically for the Sefer wallet
$seferToken = generatePaymentToken($passengerId, $amount);
if (!$seferToken) {
logError("6.0.1", "Failed to generate Sefer token");
return null;
}
logError("6.0.2", "Generated new Sefer token", [
"token_length" => ($seferToken)
]);
$url = BASE_URL . "/seferWallet/add.php";
$postData = [
'amount' => $amount,
'paymentMethod' => $paymentMethod,
'passengerId' => $passengerId,
'token' => $seferToken, // Use the new Sefer-specific token
'driverId' => 'passenger'
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
logError("6.1", "cURL error in Sefer wallet update", [
"error" => $curlError,
"url" => $url
]);
return null;
}
if ($httpCode != 200) {
logError("6.2", "HTTP error in Sefer wallet update", [
"http_code" => $httpCode,
"response" => $response
]);
return null;
}
$data = json_decode($response, true);
if (!$data) {
logError("6.3", "Invalid response format in Sefer wallet update", [
"response" => $response
]);
return null;
}
return $data; // ✅ Return result
}
// 🎯 Function to calculate bonus
function calculateBonus($amount) {
logError("3.1", "Bonus calculation input", ["amount" => $amount]);
$result = 0;
if ($amount == 100) $result = 100;
else if ($amount == 200) $result = 215;
else if ($amount == 400) $result = 450;
else if ($amount == 1000) $result = 1140;
logError("3.2", "Bonus calculation result", [
"input" => $amount,
"output" => $result
]);
return $result;
}
?>

View File

@@ -1,137 +0,0 @@
<?php
include "../../../jwtconnect.php";
// ------------------------------
// قراءة HMAC من الهيدر أو من الـ query
// ------------------------------
$received_hmac = $_SERVER['HTTP_HMAC'] ?? ($_GET['hmac'] ?? '');
$received_hmac = trim($received_hmac);
// ------------------------------
// قراءة البيانات القادمة من Paymob
// ------------------------------
$raw_body = file_get_contents("php://input");
$data = json_decode($raw_body, true);
// ------------------------------
// المفتاح السري
// ------------------------------
$secret_key = getenv('hmacPaymob');
// ------------------------------
// دالة لتحويل القيم إلى النصوص
// ------------------------------
function normalize($value) {
if ($value === true) return 'true';
if ($value === false) return 'false';
if (is_null($value)) return '';
return (string)$value;
}
// ------------------------------
// التحقق من صحة HMAC
// ------------------------------
function isValidHmac($data, $secret_key, $received_hmac) {
if (!isset($data['obj'])) return false;
$obj = $data['obj'];
// دمج جميع الحقول بشكل متسلسل
$fields = [
normalize($obj['amount_cents'] ?? ''),
normalize($obj['created_at'] ?? ''),
normalize($obj['currency'] ?? ''),
normalize($obj['error_occured'] ?? false),
normalize($obj['has_parent_transaction'] ?? false),
normalize($obj['id'] ?? ''),
normalize($obj['integration_id'] ?? ''),
normalize($obj['is_3d_secure'] ?? false),
normalize($obj['is_auth'] ?? false),
normalize($obj['is_capture'] ?? false),
normalize($obj['is_refunded'] ?? false),
normalize($obj['is_standalone_payment'] ?? false),
normalize($obj['is_voided'] ?? false),
normalize($obj['order']['id'] ?? ''),
normalize($obj['owner'] ?? ''),
normalize($obj['pending'] ?? false),
normalize($obj['source_data']['pan'] ?? ''),
normalize($obj['source_data']['sub_type'] ?? ''),
normalize($obj['source_data']['type'] ?? ''),
normalize($obj['success'] ?? false)
];
// دمج الحقول في رسالة واحدة
$message = implode('', $fields);
// حساب HMAC باستخدام المفتاح السري
$calculated_hmac = hash_hmac('sha512', $message, $secret_key);
// طباعة الرسائل لأغراض التصحيح
// error_log("🔐 Message used for HMAC: " . $message);
// error_log("🔐 Calculated HMAC: " . $calculated_hmac);
// error_log("📩 Received HMAC: " . $received_hmac);
// error_log("Calculated HMAC length: " . strlen($calculated_hmac));
// error_log("Received HMAC length: " . strlen($received_hmac));
// التحقق من تطابق HMAC
if (hash_equals($calculated_hmac, $received_hmac)) {
error_log("✅ Valid HMAC signature verified.");
return $calculated_hmac;
} else {
http_response_code(401);
echo json_encode(["error" => "Unauthorized Invalid HMAC"]);
exit;
}
}
isValidHmac($data, $secret_key, $received_hmac);
// ------------------------------
// إذا كانت HMAC صحيحة، نتابع العملية
// ------------------------------
if ($data && isset($data['obj'])) {
$transaction = $data['obj'];
$payment_id = $transaction['id'] ?? null;
$amount = $transaction['amount_cents'] ?? 0;
$status = $transaction['success'] ?? false;
$is_voided = $transaction['is_voided'] ?? false;
$is_refunded = $transaction['is_refunded'] ?? false;
$order_id = $transaction['order']['id'] ?? null;
$merchant_order_id = $transaction['order']['merchant_order_id'] ?? null;
$payment_method = $transaction['source_data']['type'] ?? 'unknown';
$card_last4 = $transaction['source_data']['pan'] ?? '****';
$transaction_type = $transaction['data']['migs_transaction']['type'] ?? 'UNKNOWN';
$created_at = $transaction['created_at'] ?? date("Y-m-d H:i:s");
$user_id = $transaction['order']['shipping_data']['phone_number'];
// التحقق من حالة الدفع
if (!$status) {
error_log("❌ Invalid payment status: " . $status);
echo json_encode(["error" => "Invalid payment status"]);
exit;
}
// إضافة البيانات إلى قاعدة البيانات
$query = "INSERT INTO paymentsLog (`payment_id`, `user_id`, `amount`, `status`)
VALUES (:payment_id, :user_id, :amount, :status)";
$stmt = $con->prepare($query);
$stmt->bindParam(':payment_id', $payment_id);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':amount', $amount);
$stmt->bindParam(':status', $status);
try {
$stmt->execute();
if ($stmt->rowCount() > 0) {
http_response_code(200);
echo json_encode(["success" => true, "message" => "Payment data saved successfully"]);
} else {
http_response_code(200);
echo json_encode(["success" => false, "message" => "Payment data already up to date."]);
}
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(["error" => "Failed to execute the query: " . $e->getMessage()]);
}
}
?>