Skip to main content

Shopping Cart

Manage customer shopping carts including adding products, updating quantities, and removing items.
All cart endpoints require authentication. Include the JWT token in the Authorization header.

Add Product to Cart

POST /api/ecom/carrito

Add a product to the customer’s shopping cart
Add a product to the authenticated customer’s cart. If the product already exists in the cart, the quantity will be incremented.

Headers

Authorization
string
required
Bearer token from login responseFormat: Bearer {token}

Request Body

prd_codigo
string
required
Product code to add to cart

Response

message
string
Success message: “Producto añadido al carrito”

Example Request

curl -X POST https://api.example.com/api/ecom/carrito \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "prd_codigo": "PRD001"
  }'

Example Response

201 Created
{
  "message": "Producto añadido al carrito"
}
404 Not Found
{
  "message": "Carrito no encontrado"
}
500 Internal Server Error
{
  "message": "Error al añadir el producto al carrito"
}
The cart is automatically created for each customer during registration. If a product already exists in the cart, the upsert operation will increment its quantity by 1.

Get Cart Contents

GET /api/ecom/carrito

Retrieve the customer’s shopping cart with all items
Get the authenticated customer’s cart with all product details, quantities, and pagination.

Headers

Authorization
string
required
Bearer token from login response

Query Parameters

page
number
default:"1"
Page number for paginated cart items (starts at 1)

Response

page
number
Current page number
limit
number
Number of items per page (from PAGINATION_LIMIT env var)
totalPages
number
Total number of pages
carrito
object
Cart information
detalles
array
Array of cart items with product details

Example Request

curl -X GET "https://api.example.com/api/ecom/carrito?page=1" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Example Response

200 OK
{
  "page": 1,
  "limit": 20,
  "totalPages": 1,
  "carrito": {
    "crr_codigo": "CRR001",
    "cli_codigo": "CLI001",
    "crr_fecha": "2024-03-04T10:30:00.000Z",
    "crr_total": 2799.98
  },
  "detalles": [
    {
      "prd_codigo": "PRD001",
      "prd_nombre": "Laptop Gaming MSI",
      "prd_precio": 1299.99,
      "dcar_cantidad": 1,
      "dcar_subtotal": 1299.99,
      "prd_imagen": "/images/products/laptop-msi.jpg"
    },
    {
      "prd_codigo": "PRD002",
      "prd_nombre": "Laptop Dell XPS 15",
      "prd_precio": 1499.99,
      "dcar_cantidad": 1,
      "dcar_subtotal": 1499.99,
      "prd_imagen": "/images/products/laptop-dell.jpg"
    }
  ]
}
404 Not Found
{
  "message": "Carrito no encontrado"
}

Search Cart Items

GET /api/ecom/carrito/name

Search products in cart by name
Filter cart items by product name with pagination.

Headers

Authorization
string
required
Bearer token from login response

Query Parameters

name
string
required
Product name search term
page
number
default:"1"
Page number for pagination

Response

page
number
Current page number
limit
number
Items per page
totalPages
number
Total pages available
filtros
object
Applied filters
detalles
array
Filtered cart items

Example Request

curl -X GET "https://api.example.com/api/ecom/carrito/name?name=laptop&page=1" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Example Response

200 OK
{
  "page": 1,
  "limit": 20,
  "totalPages": 1,
  "filtros": {
    "name": "laptop"
  },
  "detalles": [
    {
      "prd_codigo": "PRD001",
      "prd_nombre": "Laptop Gaming MSI",
      "prd_precio": 1299.99,
      "dcar_cantidad": 1,
      "dcar_subtotal": 1299.99,
      "prd_imagen": "/images/products/laptop-msi.jpg"
    }
  ]
}
400 Bad Request
{
  "message": "Parámetro name requerido"
}

Update Item Quantity

PUT /api/ecom/carrito/detalle

Update the quantity of a product in the cart
Change the quantity of a specific product in the customer’s cart.

Headers

Authorization
string
required
Bearer token from login response

Request Body

prd_codigo
string
required
Product code to update
cantidad
number
required
New quantity (must be greater than 0)

Response

message
string
Success message: “Cantidad actualizada correctamente”

Example Request

curl -X PUT https://api.example.com/api/ecom/carrito/detalle \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "prd_codigo": "PRD001",
    "cantidad": 3
  }'

Example Response

200 OK
{
  "message": "Cantidad actualizada correctamente"
}
400 Bad Request
{
  "message": "prd_codigo y cantidad son requeridos"
}
404 Not Found
{
  "message": "Carrito no encontrado"
}
To remove an item from the cart entirely, use the DELETE endpoint instead of setting quantity to 0.

Remove Item from Cart

DELETE /api/ecom/carrito/detalle/:prd_codigo

Remove a product from the shopping cart
Completely remove a product from the customer’s cart.

Headers

Authorization
string
required
Bearer token from login response

Path Parameters

prd_codigo
string
required
Product code to remove from cart

Response

message
string
Success message: “Producto eliminado del carrito”

Example Request

curl -X DELETE https://api.example.com/api/ecom/carrito/detalle/PRD001 \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Example Response

200 OK
{
  "message": "Producto eliminado del carrito"
}
400 Bad Request
{
  "message": "prd_codigo es requerido"
}
404 Not Found
{
  "message": "Carrito no encontrado"
}

Shopping Cart Workflow

Typical cart operations flow:
  1. Browse Products: Use /api/ecom/producto to view available products
  2. Add to Cart: POST to /api/ecom/carrito with product code
  3. View Cart: GET /api/ecom/carrito to see all items and total
  4. Update Quantities: PUT to /api/ecom/carrito/detalle to change item quantities
  5. Remove Items: DELETE /api/ecom/carrito/detalle/:prd_codigo to remove unwanted items
  6. Proceed to Checkout: Use /api/ecom/pagos/checkout to complete purchase

Example: Complete Cart Management

const token = 'your_jwt_token_here';
const baseURL = 'https://api.example.com';

// 1. Add product to cart
async function addToCart(productCode) {
  const response = await fetch(`${baseURL}/api/ecom/carrito`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ prd_codigo: productCode })
  });
  return response.json();
}

// 2. Get cart contents
async function getCart() {
  const response = await fetch(`${baseURL}/api/ecom/carrito?page=1`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  return response.json();
}

// 3. Update item quantity
async function updateQuantity(productCode, quantity) {
  const response = await fetch(`${baseURL}/api/ecom/carrito/detalle`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ prd_codigo: productCode, cantidad: quantity })
  });
  return response.json();
}

// 4. Remove item
async function removeFromCart(productCode) {
  const response = await fetch(
    `${baseURL}/api/ecom/carrito/detalle/${productCode}`,
    {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );
  return response.json();
}

// Usage
await addToCart('PRD001');
await addToCart('PRD002');
const cart = await getCart();
console.log('Cart total:', cart.carrito.crr_total);

await updateQuantity('PRD001', 3);
await removeFromCart('PRD002');

Error Handling

Common Error Codes

  • 400 Bad Request: Missing required parameters
  • 401 Unauthorized: Invalid or missing authentication token
  • 404 Not Found: Cart or product not found
  • 500 Internal Server Error: Server-side error

Authentication Errors

All cart endpoints require authentication. If the token is missing or invalid:
401 Unauthorized
{
  "error": "Token inválido o expirado"
}
Each customer has exactly one active cart. The cart persists across sessions until items are purchased or manually removed.

Source Code Reference

Implementation details can be found in:
  • Routes: /src/routes/ecom.carrito.routes.js:1-37
  • Controller: /src/controllers/ecom.carrito.controller.js:12-196
  • Model: /src/models/carrito.model.js
  • Middleware: /src/middlewares/auth.middleware.js

Build docs developers (and LLMs) love