'Not authenticated.']); exit; } if (!isset($_POST['package_id'])) { echo json_encode(['error' => 'Package ID required.']); exit; } require_once __DIR__ . '/../db/config.php'; $db = db(); // Fetch secret key $stripe_sk = $db->query("SELECT setting_value FROM stripe_config WHERE setting_key = 'stripe_secret_key'")->fetchColumn(); if (empty($stripe_sk)) { echo json_encode(['error' => 'Stripe is not configured by administrator.']); exit; } // Fetch package details $stmt = $db->prepare("SELECT * FROM credit_packages WHERE id = ? AND is_active = 1"); $stmt->execute([$_POST['package_id']]); $package = $stmt->fetch(); if (!$package) { echo json_encode(['error' => 'Invalid package.']); exit; } // Generate an initial invoice record in 'unpaid' status $invoice_number = 'INV-' . strtoupper(substr(uniqid(), -8)); $stmt = $db->prepare("INSERT INTO invoices (user_id, invoice_number, amount, currency, status, credits_added, items_json) VALUES (?, ?, ?, ?, 'unpaid', ?, ?)"); $stmt->execute([ $_SESSION['user_id'], $invoice_number, $package['price_amount'], $package['price_currency'], $package['credits'], json_encode([['name' => $pkg['name'] ?? $package['name'], 'amount' => $package['price_amount'], 'quantity' => 1]]) ]); $invoice_id = $db->lastInsertId(); // Create Checkout Session via cURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com/v1/checkout/sessions"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_USERPWD, $stripe_sk . ":"); $success_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]/dashboard.php?payment=success&invoice_id=$invoice_id"; $cancel_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]/purchase_credits.php?payment=cancelled"; $post_fields = [ 'payment_method_types[0]' => 'card', 'line_items[0][price_data][currency]' => strtolower($package['price_currency']), 'line_items[0][price_data][product_data][name]' => $package['name'], 'line_items[0][price_data][unit_amount]' => (int)($package['price_amount'] * 100), // Amount in cents 'line_items[0][quantity]' => 1, 'mode' => 'payment', 'success_url' => $success_url, 'cancel_url' => $cancel_url, 'client_reference_id' => $invoice_id, 'customer_email' => $_SESSION['user_email'] ?? null, 'metadata[invoice_id]' => $invoice_id, 'metadata[user_id]' => $_SESSION['user_id'], 'metadata[credits]' => $package['credits'] ]; curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields)); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $data = json_decode($response, true); if ($http_code === 200 && isset($data['id'])) { // Update invoice with payment intent ID (or session ID as placeholder) $stmt = $db->prepare("UPDATE invoices SET stripe_payment_intent_id = ? WHERE id = ?"); $stmt->execute([$data['id'], $invoice_id]); echo json_encode(['id' => $data['id']]); } else { error_log('Stripe Error: ' . ($data['error']['message'] ?? 'Unknown error')); echo json_encode(['error' => $data['error']['message'] ?? 'Failed to communicate with Stripe.']); }