T.ME/BIBIL_0DAY
CasperSecurity


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/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/.cursor-server/data/User/History/-fc37a7e/oIbT.php
<?php
session_start();
require_once 'config/database.php';
require_once 'config/email.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 or guest checkout
$user_id = $_SESSION['user_id'] ?? null;
$is_guest = !$user_id;

if ($is_guest) {
    error_log("process_credit_payment.php: Guest checkout detected");
    // Allow guest checkout but use a temporary user ID
    $user_id = 'guest_' . time();
}

// 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'
    ]
];

// Add shutdown handler to catch fatal errors and log them
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        $log = date('Y-m-d H:i:s') . " FATAL: {$error['message']} in {$error['file']} on line {$error['line']}\n";
        file_put_contents(__DIR__ . '/payment_errors.log', $log, FILE_APPEND);
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }
        echo json_encode(['success' => false, 'error' => 'Server error: ' . $error['message']]);
        exit;
    }
});

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) {
    global $user_id;
    try {
        error_log("handleCartPayment called with input: " . json_encode($input));
        
        $cart_data = $input['cart'] ?? [];
        
        if (empty($cart_data)) {
            error_log("handleCartPayment: Cart is empty");
            echo json_encode(['success' => false, 'error' => 'Cart is empty']);
            return;
        }
        
        // 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) {
            if (!isset($item['package']) || !isset($item['quantity'])) {
                error_log("handleCartPayment: Missing package or quantity in credit item: " . json_encode($item));
                echo json_encode(['success' => false, 'error' => 'Malformed credit item in cart']);
                return;
            }
            $package_id = $item['package'];
            $quantity = $item['quantity'];
            
            if (!isset($credit_packages[$package_id])) {
                error_log("handleCartPayment: Invalid package in cart: $package_id");
                echo json_encode(['success' => false, 'error' => 'Invalid package in cart: ' . $package_id]);
                return;
            }
            
            $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) {
            if (!isset($item['track_id']) || !isset($item['title']) || !isset($item['price'])) {
                error_log("handleCartPayment: Missing fields in track item: " . json_encode($item));
                echo json_encode(['success' => false, 'error' => 'Malformed track item in cart']);
                return;
            }
            $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_name'] ?? $item['artist'] ?? 'Unknown Artist',
                'quantity' => $quantity,
                'amount' => $item_total
            ];
        }
        
        // Get billing address data
        $billing_address = $input['billing_address'] ?? [];
        
        // 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'
        ]);
        
        // Prepare payment intent data
        $payment_intent_data = [
            'amount' => $total_amount,
            'currency' => 'usd',
            'metadata[user_id]' => $user_id,
            'metadata[cart_items]' => json_encode($cart_summary),
            'metadata[total_credits]' => $total_credits,
            'metadata[has_tracks]' => !empty($track_items) ? 'true' : 'false',
            'metadata[subscription_period]' => '30_days',
            'metadata[payment_type]' => 'mixed_cart_checkout'
        ];
        
        // Add billing address if provided
        if (!empty($billing_address)) {
            $payment_intent_data['metadata[billing_name]'] = ($billing_address['billing_first_name'] ?? '') . ' ' . ($billing_address['billing_last_name'] ?? '');
            $payment_intent_data['metadata[billing_email]'] = $billing_address['billing_email'] ?? '';
            $payment_intent_data['metadata[billing_address]'] = $billing_address['billing_address'] ?? '';
            $payment_intent_data['metadata[billing_city]'] = $billing_address['billing_city'] ?? '';
            $payment_intent_data['metadata[billing_state]'] = $billing_address['billing_state'] ?? '';
            $payment_intent_data['metadata[billing_zip]'] = $billing_address['billing_zip'] ?? '';
            $payment_intent_data['metadata[billing_country]'] = $billing_address['billing_country'] ?? '';
        }
        
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payment_intent_data));
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        
        curl_close($ch);
        
        if ($curl_error) {
            error_log("handleCartPayment: cURL error: $curl_error");
            echo json_encode(['success' => false, 'error' => 'cURL Error: ' . $curl_error]);
            return;
        }
        
        if ($http_code !== 200) {
            $error_data = json_decode($response, true);
            $error_message = $error_data['error']['message'] ?? 'HTTP Error: ' . $http_code;
            error_log("handleCartPayment: Stripe API error: $error_message");
            echo json_encode(['success' => false, 'error' => $error_message]);
            return;
        }
        
        $payment_intent = json_decode($response, true);
        
        // Log cart payment intent creation
        logPaymentEvent('cart_payment_intent_created', [
            'user_id' => $user_id,
            'cart_items' => $cart_summary,
            'total_credits' => $total_credits,
            'amount' => $total_amount,
            'payment_intent_id' => $payment_intent['id']
        ]);
        
        // Store payment data in session for email confirmation
        $_SESSION['last_payment_data'] = [
            'order_details' => [
                'total_amount' => $total_amount,
                'cart_summary' => $cart_summary,
                'payment_intent_id' => $payment_intent['id']
            ],
            'billing_address' => $billing_address
        ];
        
        $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);
    } catch (Exception $e) {
        error_log("handleCartPayment: Exception: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'Server error: ' . $e->getMessage()]);
    }
}

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
    ]);
}

// updateUserCredits function is already defined in config/database.php

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();
}
?> 

CasperSecurity Mini