Skip to main content

Create Order (Checkout)

curl -X POST https://api.miscompras.com/api/pedidos/checkout \
  -H "Content-Type: application/json" \
  -d '{
    "usuario_id": 5,
    "items": [
      {
        "id": 1,
        "cantidad": 2,
        "precio": 999.99,
        "subtotal": 1999.98
      },
      {
        "id": 3,
        "cantidad": 1,
        "precio": 49.99,
        "subtotal": 49.99
      }
    ],
    "total": 2049.97,
    "direccion": "123 Main St, City, Country"
  }'
Process a checkout and create a new order. This endpoint handles transaction creation, order details insertion, and stock updates atomically.

Request Body

usuario_id
integer
ID of the user placing the order. Can be null for guest checkouts.
items
array
required
Array of products being ordered
total
decimal
required
Total order amount
direccion
string
Delivery address

Response

success
boolean
Indicates whether the order was successfully created
message
string
Human-readable result message
pedido_id
integer
ID of the newly created order (only on success)
{
  "success": true,
  "message": "Pedido registrado con éxito",
  "pedido_id": 42
}
This endpoint uses database transactions to ensure data consistency. If any step fails (order creation, detail insertion, or stock update), the entire transaction is rolled back.

Order Processing Flow

  1. Validation: Checks that the cart is not empty
  2. Transaction Start: Begins a database transaction
  3. Order Creation: Inserts a new order with status “pendiente” (pending)
  4. Order Details: Inserts each cart item into the order details table
  5. Stock Update: Decrements product stock for each ordered item
  6. Transaction Commit: Commits the transaction if all steps succeed
  7. Rollback: Rolls back on any error
The endpoint automatically reduces product stock. Ensure your frontend validates stock availability before submitting the order.

Create Order (PHP Checkout)

curl -X POST https://api.miscompras.com/php/checkout.php \
  -H "Content-Type: application/json" \
  -d '{
    "usuario_id": 5,
    "items": [
      {
        "id": 1,
        "cantidad": 2,
        "precio": 999.99
      }
    ],
    "total": 1999.98
  }'
Alternative PHP-based checkout endpoint with simplified structure.

Request Body

usuario_id
integer
User ID placing the order (optional)
items
array
required
Array of cart items
total
decimal
required
Total order amount

Response

success
boolean
Order success status
message
string
Result message
redirect
string
Redirect URL on success (typically “gracias.html”)
{
  "success": true,
  "message": "Compra registrada correctamente.",
  "redirect": "gracias.html"
}

Order Data Structure

The order is stored in two tables: pedidos table:
  • id_pedido - Auto-generated order ID
  • id_usuario - User ID (nullable)
  • total - Order total amount
  • fecha_pedido - Timestamp (auto-generated)
  • estado - Status (default: “pendiente”)
  • metodo_pago - Payment method (Node.js version sets to “Tarjeta”)
detalle_pedido table:
  • id_pedido - Foreign key to pedidos
  • id_producto - Product ID
  • cantidad - Quantity ordered
  • precio_unitario - Unit price (Node.js version)
  • precio - Unit price (PHP version)
  • subtotal - Line item total (Node.js version)
There are slight schema differences between the Node.js and PHP implementations. The Node.js version includes subtotal and precio_unitario fields in the order details, while the PHP version uses precio.

Order Status Values

Orders in the system use the following status values:
StatusDescription
pendienteOrder has been placed but not yet processed
procesandoOrder is being prepared
enviadoOrder has been shipped
entregadoOrder has been delivered
canceladoOrder has been cancelled
The default status for new orders is “pendiente” (pending).

Error Handling

Both checkout endpoints implement robust error handling:
  • Validation errors return 400 status with descriptive messages
  • Database errors return 500 status with error details
  • Transaction failures trigger automatic rollback (Node.js version)
  • Debug logging is enabled for troubleshooting (PHP version writes to debug_input.txt)
The PHP version includes debug logging that writes request bodies to debug_input.txt. Remove this in production environments to avoid exposing sensitive data.

Build docs developers (and LLMs) love