Overview
The checkout process on Mis Compras converts your shopping cart into a confirmed order. The system validates your cart, processes your purchase, and generates an order record in the database.
Starting Checkout
Prerequisites
Before you can checkout, ensure:
Items in Cart
Your cart must contain at least one product
User Account
You should be logged in (optional but recommended for order tracking)
Review Cart
Verify all items, quantities, and prices are correct
Initiating Checkout
On the cart page (carrito de compras.html), click the “Finalizar Compra” (Complete Purchase) button to begin checkout.
// Checkout button handler from carrito.js:192-194
const btnFinalizar = document . querySelector ( '.carrito-btn' );
if ( btnFinalizar ) {
btnFinalizar . addEventListener ( 'click' , () => carrito . checkout ());
}
If your cart is empty, you’ll see an alert: “Tu carrito está vacío” and checkout will be blocked.
Checkout Workflow
Step-by-Step Process
Cart Validation
System checks if cart contains items if ( ! cart . length ) {
alert ( 'Tu carrito está vacío.' );
return ;
}
User Identification
Retrieves user ID from localStorage (or sets to null for guest checkout) const usuario_id = localStorage . getItem ( "usuario_id" , 1 ) || null ;
Calculate Total
Computes final order total from cart items const total = this . getTotal (); // Returns formatted price like "1998.00"
Build Payload
Constructs order data with all necessary information
Submit to Server
Sends order data to php/checkout.php via POST request
Process Response
Handles success or error from the server
Checkout Data Structure
Order Payload
The checkout system sends the following JSON payload to the server:
{
"usuario_id" : 123 ,
"items" : [
{
"id" : "1" ,
"nombre" : "iPhone 15 Pro" ,
"precio" : 999 ,
"imagen" : "imagenes/ipone15.jpg" ,
"cantidad" : 2 ,
"subtotal" : 1998
}
],
"total" : "1998.00" ,
"direccion" : null
}
The direccion (address) field is currently optional and defaults to null. Future versions may include address collection.
Checkout Implementation
// From carrito.js:69-128
async checkout ( extraData = {}) {
const cart = getCart ();
if ( ! cart . length ) {
alert ( 'Tu carrito está vacío.' );
return ;
}
const usuario_id = localStorage . getItem ( "usuario_id" , 1 ) || null ;
const total = this . getTotal ();
const payload = {
usuario_id ,
items: cart ,
total ,
direccion: extraData . direccion || null
};
try {
const resp = await fetch ( 'php/checkout.php' , {
method: 'POST' ,
headers: { 'Content-Type' : 'application/json' },
body: JSON . stringify ( payload )
});
const data = await resp . json ();
// Handle response...
} catch ( e ) {
console . error ( 'Error en checkout:' , e );
alert ( '⚠️ Error de conexión con el servidor.' );
}
}
Server-Side Processing
Database Operations
The checkout PHP script (php/checkout.php) performs two main database operations:
1. Create Order Record
// Insert into pedidos table
$stmt = $conn -> prepare ( " INSERT INTO pedidos (id_usuario, total) VALUES (?, ?)" );
$stmt -> bind_param ( "id" , $id_usuario , $total );
$stmt -> execute ();
$id_pedido = $stmt -> insert_id ; // Get new order ID
2. Create Order Details
// Insert each item into detalle_pedido table
$stmt = $conn -> prepare ( " INSERT INTO detalle_pedido (id_pedido, id_producto, cantidad, precio) VALUES (?, ?, ?, ?)" );
foreach ( $items as $item ) {
$id_producto = intval ( $item [ 'id' ]);
$cantidad = intval ( $item [ 'cantidad' ]);
$precio = floatval ( $item [ 'precio' ]);
$stmt -> bind_param ( "iiid" , $id_pedido , $id_producto , $cantidad , $precio );
$stmt -> execute ();
}
Database Schema
pedidos Table
detalle_pedido Table
CREATE TABLE pedidos (
id_pedido INT PRIMARY KEY AUTO_INCREMENT,
id_usuario INT ,
total DECIMAL ( 10 , 2 ),
fecha TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
estado VARCHAR ( 50 )
);
Success Response
Successful Checkout
When checkout succeeds, the server returns:
{
"success" : true ,
"message" : "Compra registrada correctamente." ,
"redirect" : "gracias.html"
}
Success Modal
A beautiful success modal appears on screen:
// Success modal from carrito.js:98-120
if ( data . success ) {
this . clear (); // Clear cart
const modal = document . createElement ( 'div' );
modal . innerHTML = `
<div style="...modern styling...">
<div style="...card styling...">
<div style="font-size:60px;">🎉</div>
<h2 style="color:#2e7d32;">¡Compra realizada con éxito!</h2>
<p>Tu pedido ha sido registrado correctamente.</p>
<p>Serás redirigido en unos segundos...</p>
</div>
</div>
` ;
document . body . appendChild ( modal );
setTimeout (() => {
window . location . href = 'gracias.html' ;
}, 3000 );
}
Cart Cleared
Your shopping cart is automatically emptied via this.clear()
Success Modal Displays
A celebration modal appears with a 🎉 emoji and success message
Auto-Redirect
After 3 seconds, you’re redirected to the thank you page
Thank You Page
After successful checkout, you’re redirected to gracias.html:
< body >
< h1 > 🎉 ¡Gracias por tu compra! </ h1 >
< p > Tu pedido ha sido procesado correctamente. </ p >
< button onclick = " window . location . href = 'index.html'" >
Volver al inicio
</ button >
</ body >
Post-Purchase Options
View confirmation message
Return to homepage to continue shopping
Check your profile for order history (future feature)
Error Handling
Empty Cart Error
if ( ! cart . length ) {
alert ( 'Tu carrito está vacío.' );
return ;
}
Server Error
if ( ! data . success ) {
alert ( '⚠️ No se pudo completar la compra: ' +
( data . message || 'Error desconocido.' ));
}
Connection Error
catch ( e ) {
console . error ( 'Error en checkout:' , e );
alert ( '⚠️ Error de conexión con el servidor.' );
}
If checkout fails, your cart is NOT cleared. You can review your items and try again.
Payment Processing
Currently, Mis Compras does not integrate with payment gateways. The checkout process creates an order record but does not process actual payments. This would need to be implemented with services like Stripe, PayPal, or local payment providers.
Future Payment Integration
To add payment processing, you would:
Collect payment information before calling checkout
Process payment with a payment gateway
Verify payment success before creating order
Include payment details in order record
Guest Checkout
Anonymous Purchases
The system supports guest checkout:
usuario_id is set to null if not logged in
Order is still created in database
No order tracking available without account
const usuario_id = localStorage . getItem ( "usuario_id" , 1 ) || null ;
While guest checkout is technically supported, registering an account is recommended for order tracking and customer support.
Order Confirmation
What Happens After Checkout
Order Created
New record in pedidos table with unique id_pedido
Items Recorded
Each cart item saved to detalle_pedido table
Cart Cleared
LocalStorage cart data removed
Confirmation Displayed
Success modal and thank you page shown
Order Details Stored
Your order record includes:
Order ID - Unique identifier for the order
User ID - Your account ID (or null for guest)
Total Amount - Final purchase price
Timestamp - Date and time of order
Item Details - Each product, quantity, and price
Checkout Security
Data Validation
The server validates all incoming data:
// Validation from checkout.php:18-22
if ( empty ( $data ) || ! isset ( $data [ 'items' ]) || ! is_array ( $data [ 'items' ])) {
echo json_encode ([
'success' => false ,
'message' => 'Estructura JSON inválida'
]);
exit ;
}
SQL Injection Prevention
All database queries use prepared statements:
$stmt = $conn -> prepare ( " INSERT INTO pedidos (id_usuario, total) VALUES (?, ?)" );
$stmt -> bind_param ( "id" , $id_usuario , $total );
Troubleshooting
Cart appears empty during checkout
Check browser console for JavaScript errors
Verify localStorage is enabled in your browser
Try refreshing the page and re-adding items
Check internet connection
Verify php/checkout.php is accessible
Check browser console for network errors
Ensure server is running (if local development)
Order created but cart not cleared
Check browser console for errors in success handler
Manually clear cart by navigating away and back
Report bug if persistent
Stuck on checkout - no response
Check network tab for failed requests
Verify PHP error logs for server-side issues
Ensure database connection is working
Best Practices
Review Before Submit
Always double-check your cart before clicking “Finalizar Compra”
Create Account
Register an account for better order tracking and support
Note Order ID
Future versions will provide order IDs - save these for reference
Contact Sellers
After purchase, you may need to contact sellers directly for fulfillment
Technical References
Shopping Cart Learn about cart management
Order Tracking Track your orders after purchase
Code References
Client-side checkout : carrito.js:69-128
Server-side processing : php/checkout.php
Thank you page : gracias.html
Success modal : carrito.js:98-120