![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/.cursor-server/data/User/History/-fc37a7e/ |
<?php
session_start();
require_once 'config/database.php';
// Enable error logging
error_log("process_credit_payment.php called at " . date('Y-m-d H:i:s'));
// Set content type to JSON
header('Content-Type: application/json');
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
error_log("process_credit_payment.php: User not logged in");
echo json_encode(['success' => false, 'error' => 'User not logged in']);
exit;
}
// Get POST data
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
error_log("process_credit_payment.php: Action = '$action', Input = " . json_encode($input));
// Stripe configuration
$stripe_secret_key = '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';
// Credit package configurations
$credit_packages = [
'starter' => [
'name' => 'Starter',
'credits' => 30,
'price' => 1999, // $19.99 in cents
'stripe_price_id' => 'price_starter_credits'
],
'pro' => [
'name' => 'Pro',
'credits' => 200,
'price' => 5900, // $59.00 in cents
'stripe_price_id' => 'price_pro_credits'
],
'premium' => [
'name' => 'Premium',
'credits' => 500,
'price' => 12900, // $129.00 in cents
'stripe_price_id' => 'price_premium_credits'
]
];
try {
switch ($action) {
case 'create_payment_intent':
handleCreatePaymentIntent($input, $credit_packages, $stripe_secret_key);
break;
case 'process_cart_payment':
handleCartPayment($input, $credit_packages, $stripe_secret_key);
break;
case 'confirm_payment':
handleConfirmPayment($input, $stripe_secret_key);
break;
case 'process_paypal_payment':
handlePayPalPayment($input, $credit_packages);
break;
default:
echo json_encode(['success' => false, 'error' => 'Invalid action']);
break;
}
} catch (Exception $e) {
// Log error
error_log("Credit payment error: " . $e->getMessage());
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
function handleCreatePaymentIntent($input, $credit_packages, $stripe_secret_key) {
$package_id = $input['package'] ?? '';
$quantity = $input['quantity'] ?? 1;
if (!isset($credit_packages[$package_id])) {
throw new Exception('Invalid package selected');
}
$package = $credit_packages[$package_id];
$total_amount = $package['price'] * $quantity;
$total_credits = $package['credits'] * $quantity;
// Create Stripe payment intent
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_intents');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $stripe_secret_key,
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'amount' => $total_amount,
'currency' => 'usd',
'metadata' => json_encode([
'user_id' => $_SESSION['user_id'],
'package' => $package_id,
'credits' => $total_credits,
'quantity' => $quantity,
'subscription_period' => '30_days'
])
]));
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_error) {
throw new Exception('cURL Error: ' . $curl_error);
}
if ($http_code !== 200) {
$error_data = json_decode($response, true);
$error_message = $error_data['error']['message'] ?? 'HTTP Error: ' . $http_code;
throw new Exception($error_message);
}
$payment_intent = json_decode($response, true);
// Log payment intent creation
logPaymentEvent('payment_intent_created', [
'user_id' => $_SESSION['user_id'],
'package' => $package_id,
'credits' => $total_credits,
'amount' => $total_amount,
'payment_intent_id' => $payment_intent['id']
]);
echo json_encode([
'success' => true,
'client_secret' => $payment_intent['client_secret'],
'payment_intent_id' => $payment_intent['id'],
'amount' => $total_amount,
'credits' => $total_credits
]);
}
function handleCartPayment($input, $credit_packages, $stripe_secret_key) {
error_log("handleCartPayment called with input: " . json_encode($input));
$cart_data = $input['cart'] ?? [];
if (empty($cart_data)) {
error_log("handleCartPayment: Cart is empty");
throw new Exception('Cart is empty');
}
// Handle different cart formats
$credit_items = [];
$track_items = [];
if (isset($cart_data['credits']) && isset($cart_data['tracks'])) {
// New mixed cart format with credits and tracks properties
$credit_items = $cart_data['credits'] ?? [];
$track_items = $cart_data['tracks'] ?? [];
} elseif (is_array($cart_data) && !empty($cart_data) && isset($cart_data[0]['package'])) {
// Frontend is sending credit items array directly
$credit_items = $cart_data;
$track_items = [];
} else {
// Legacy format - assume all items are credits
$credit_items = $cart_data;
$track_items = [];
}
error_log("handleCartPayment: Credit items = " . json_encode($credit_items));
error_log("handleCartPayment: Track items = " . json_encode($track_items));
// Calculate total amount and credits
$total_amount = 0;
$total_credits = 0;
$cart_summary = [];
// Process credit items
foreach ($credit_items as $item) {
$package_id = $item['package'];
$quantity = $item['quantity'];
if (!isset($credit_packages[$package_id])) {
throw new Exception('Invalid package in cart: ' . $package_id);
}
$package = $credit_packages[$package_id];
$item_total = $package['price'] * $quantity;
$item_credits = $package['credits'] * $quantity;
$total_amount += $item_total;
$total_credits += $item_credits;
$cart_summary[] = [
'type' => 'credit',
'package' => $package_id,
'name' => $package['name'],
'credits' => $item_credits,
'quantity' => $quantity,
'amount' => $item_total
];
}
// Process track items
foreach ($track_items as $item) {
$track_price = $item['price'] * 100; // Convert to cents
$quantity = $item['quantity'] ?? 1;
$item_total = $track_price * $quantity;
$total_amount += $item_total;
$cart_summary[] = [
'type' => 'track',
'track_id' => $item['track_id'],
'title' => $item['title'],
'artist' => $item['artist'],
'quantity' => $quantity,
'amount' => $item_total
];
}
// Create Stripe payment intent for cart
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_intents');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $stripe_secret_key,
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'amount' => $total_amount,
'currency' => 'usd',
'metadata' => json_encode([
'user_id' => $_SESSION['user_id'],
'cart_items' => json_encode($cart_summary),
'total_credits' => $total_credits,
'has_tracks' => !empty($track_items),
'subscription_period' => '30_days',
'payment_type' => 'mixed_cart_checkout'
])
]));
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_error) {
throw new Exception('cURL Error: ' . $curl_error);
}
if ($http_code !== 200) {
$error_data = json_decode($response, true);
$error_message = $error_data['error']['message'] ?? 'HTTP Error: ' . $http_code;
throw new Exception($error_message);
}
$payment_intent = json_decode($response, true);
// Log cart payment intent creation
logPaymentEvent('cart_payment_intent_created', [
'user_id' => $_SESSION['user_id'],
'cart_items' => $cart_summary,
'total_credits' => $total_credits,
'amount' => $total_amount,
'payment_intent_id' => $payment_intent['id']
]);
$response_data = [
'success' => true,
'client_secret' => $payment_intent['client_secret'],
'payment_intent_id' => $payment_intent['id'],
'amount' => $total_amount,
'credits' => $total_credits,
'cart_summary' => $cart_summary
];
error_log("handleCartPayment: Returning success response: " . json_encode($response_data));
echo json_encode($response_data);
}
function handleConfirmPayment($input, $stripe_secret_key) {
$payment_intent_id = $input['payment_intent_id'] ?? '';
if (empty($payment_intent_id)) {
throw new Exception('Payment intent ID is required');
}
// Retrieve payment intent from Stripe
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_intents/' . $payment_intent_id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $stripe_secret_key
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_error) {
throw new Exception('cURL Error: ' . $curl_error);
}
if ($http_code !== 200) {
$error_data = json_decode($response, true);
$error_message = $error_data['error']['message'] ?? 'HTTP Error: ' . $http_code;
throw new Exception($error_message);
}
$payment_intent = json_decode($response, true);
// Check if payment was successful
if ($payment_intent['status'] !== 'succeeded') {
throw new Exception('Payment not completed. Status: ' . $payment_intent['status']);
}
// Extract metadata
$metadata = json_decode($payment_intent['metadata']['metadata'] ?? '{}', true);
$user_id = $metadata['user_id'] ?? $_SESSION['user_id'];
$credits = $metadata['credits'] ?? $metadata['total_credits'] ?? 0;
$package = $metadata['package'] ?? 'unknown';
// Add credits to user account
$current_credits = $_SESSION['credits'] ?? 0;
$new_credits = $current_credits + $credits;
$_SESSION['credits'] = $new_credits;
// Update user credits in database (you'll need to implement this)
updateUserCredits($user_id, $new_credits);
// Log successful payment
logPaymentEvent('payment_succeeded', [
'user_id' => $user_id,
'payment_intent_id' => $payment_intent_id,
'credits_added' => $credits,
'total_credits' => $new_credits,
'amount' => $payment_intent['amount'],
'package' => $package
]);
echo json_encode([
'success' => true,
'credits_added' => $credits,
'total_credits' => $new_credits,
'payment_intent_id' => $payment_intent_id
]);
}
function updateUserCredits($user_id, $credits) {
// This function should update the user's credits in your database
// Implementation depends on your database structure
// For now, we'll just log the update
logPaymentEvent('credits_updated', [
'user_id' => $user_id,
'new_credits' => $credits
]);
}
function logPaymentEvent($event_type, $data) {
$log_entry = [
'timestamp' => date('Y-m-d H:i:s'),
'event_type' => $event_type,
'data' => $data
];
$log_file = __DIR__ . '/logs/credit_payments.log';
file_put_contents($log_file, json_encode($log_entry) . "\n", FILE_APPEND | LOCK_EX);
}
function handlePayPalPayment($input, $credit_packages) {
$cart_items = $input['cart'] ?? [];
if (empty($cart_items)) {
throw new Exception('Cart is empty');
}
// Calculate total amount and credits
$total_amount = 0;
$total_credits = 0;
$cart_summary = [];
foreach ($cart_items as $item) {
$package_id = $item['package'];
$quantity = $item['quantity'];
if (!isset($credit_packages[$package_id])) {
throw new Exception('Invalid package in cart: ' . $package_id);
}
$package = $credit_packages[$package_id];
$item_total = $package['price'] * $quantity;
$item_credits = $package['credits'] * $quantity;
$total_amount += $item_total;
$total_credits += $item_credits;
$cart_summary[] = [
'package' => $package_id,
'name' => $package['name'],
'credits' => $item_credits,
'quantity' => $quantity,
'amount' => $item_total
];
}
// For now, redirect to a PayPal checkout page
// In a real implementation, you would create a PayPal order here
$paypal_url = "https://www.paypal.com/checkoutnow?token=" . generatePayPalToken($total_amount, $cart_summary);
// Log PayPal payment attempt
logPaymentEvent('paypal_payment_attempt', [
'user_id' => $_SESSION['user_id'],
'cart_items' => $cart_summary,
'total_credits' => $total_credits,
'amount' => $total_amount,
'paypal_url' => $paypal_url
]);
echo json_encode([
'success' => true,
'paypal_url' => $paypal_url,
'amount' => $total_amount,
'credits' => $total_credits,
'cart_summary' => $cart_summary
]);
}
function generatePayPalToken($amount, $cart_summary) {
// This is a placeholder function
// In a real implementation, you would:
// 1. Create a PayPal order via PayPal API
// 2. Return the PayPal order ID/token
// 3. Handle the payment completion via webhook
// For now, return a dummy token
return 'PAYPAL_' . uniqid() . '_' . time();
}
?>