Update: 2026-06-16 22:44:11

This commit is contained in:
Hamza-Ayed
2026-06-16 22:44:11 +03:00
parent b516fbc4ed
commit 2c3816badb
97 changed files with 10137 additions and 116 deletions

View File

@@ -0,0 +1,100 @@
<?php
include "../../../jwtconnect.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

@@ -0,0 +1,118 @@
<?php
include "../../../jwtconnect.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

@@ -0,0 +1,146 @@
<?php
include "../../../jwtconnect.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⃣ توكن مستقل لـ SiroWallet
$tokenSiro = generateToken($con, $driverId, $originalAmount);
if (!$tokenSiro) {
printFailure('Failed to generate token for siro 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 siroWallet
$insertSiro = $con->prepare("INSERT INTO siroWallet (driverId, passengerId, amount, paymentMethod, token, createdAt)
VALUES (:driverId, :passengerId, :amount, :paymentMethod, :token, CURRENT_TIMESTAMP)");
$insertSiro->execute([
':driverId' => $driverId,
':passengerId' => 'driver',
':amount' => $originalAmount,
':paymentMethod' => $paymentMethod,
':token' => $tokenSiro
]);
// 8⃣ Update tokenSiro to isUsed = TRUE
$markTokenSiro = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token");
$markTokenSiro->execute([':token' => $tokenSiro]);
// 🎉 Success response
printSuccess([
'message' => 'Payment verified and all wallets updated successfully.',
'amount' => $originalAmount,
'bonus' => $bonus,
'paymentID' => $paymentID,
'tokenUsed' => [
'driverWalletToken' => $tokenDriver,
'siroWalletToken' => $tokenSiro
]
]);
} 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

@@ -0,0 +1,110 @@
<?php
// paymob_payout.php
// سكريبت بي ات بي لمعاملات Paymob Payout (محفظة وبنك) بدون تخزين في قاعدة البيانات
declare(strict_types=1);
include '../../../jwtconnect.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

@@ -0,0 +1,142 @@
<?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

@@ -0,0 +1,142 @@
<?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()]);
}
}
?>