Skip to main content

Overview

The MercadoPago integration endpoint creates payment preferences that allow users to complete purchases through MercadoPago’s checkout system. This endpoint is implemented as a Cloudflare Worker and handles both preference creation and webhook processing.

Endpoint

POST https://mercadopago-jcv.fagal142010.workers.dev/
Alternatively, you can use the Next.js API route:
POST /api/payment/mercadopago/create-preference

Authentication

This endpoint requires server-side authentication using MercadoPago credentials:
  • MP_ACCESS_TOKEN: MercadoPago access token (server-side only)
  • NEXT_PUBLIC_MP_PUBLIC_KEY: Public key for client-side SDK initialization
Never expose your MP_ACCESS_TOKEN on the client side. Always make preference creation requests from your backend.

Request Body

items
array
required
Array of items to be purchased. Each item must include:
payer
object
Optional payer information
backUrls
object
Custom redirect URLs (optional, defaults to JCV Fitness URLs)
planType
string
Plan identifier for internal tracking (e.g., PLAN_BASICO, PLAN_PRO, PLAN_PREMIUM)
userId
string
User ID for associating the payment with a specific user. This is included in the external_reference.

Response

id
string
MercadoPago preference ID
initPoint
string
URL to redirect the user for production checkout
sandboxInitPoint
string
URL to redirect the user for sandbox/test checkout

Example Request

const response = await fetch('https://mercadopago-jcv.fagal142010.workers.dev/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    items: [
      {
        title: 'JCV Fitness - Plan Pro',
        description: 'Plan de alimentacion personalizado + Rutina gimnasio',
        quantity: 1,
        unitPrice: 89900,
        currencyId: 'COP'
      }
    ],
    payer: {
      email: '[email protected]',
      name: 'Juan Perez'
    },
    planType: 'PLAN_PRO',
    userId: 'user-uuid-123'
  })
});

const data = await response.json();
console.log('Preference ID:', data.id);
// Redirect user to data.initPoint or data.sandboxInitPoint

Example Response

{
  "id": "123456789-abcd-efgh-ijkl-mnopqrstuvwx",
  "initPoint": "https://www.mercadopago.com.co/checkout/v1/redirect?pref_id=123456789-abcd-efgh-ijkl-mnopqrstuvwx",
  "sandboxInitPoint": "https://sandbox.mercadopago.com.co/checkout/v1/redirect?pref_id=123456789-abcd-efgh-ijkl-mnopqrstuvwx"
}

Payment Flow Diagram

Predefined Plans

JCV Fitness has three predefined subscription plans:

Plan Basico

Price: $49,900 COP
  • 7-day meal plan
  • Home workout routine
  • App access
  • Email support

Plan Pro

Price: $89,900 COP
  • Personalized meal plan
  • Gym + home routines
  • Exercise videos
  • Priority support
  • Weekly tracking

Plan Premium

Price: $149,900 COP
  • Everything in Pro
  • 1-on-1 coaching
  • Monthly adjustments
  • VIP community access
  • Results guarantee

Using the Client SDK

For client-side integration, use the JCV Fitness payment utility functions:
import { createPaymentPreference, renderWalletBrick } from '@/features/payment/utils/mercado-pago';

// Step 1: Create preference from backend
const preference = await createPaymentPreference({
  items: [{
    title: 'JCV Fitness - Plan Pro',
    quantity: 1,
    unitPrice: 89900,
    currencyId: 'COP'
  }],
  payer: {
    email: user.email,
    name: user.name
  }
});

// Step 2: Render MercadoPago Wallet Brick
await renderWalletBrick(
  'wallet-container', // Container ID
  preference.id,
  {
    onReady: () => console.log('Wallet ready'),
    onSubmit: () => console.log('Payment submitted'),
    onError: (error) => console.error('Payment error:', error)
  }
);

Error Handling

error
string
Error message if the request fails
details
string
Additional error details from MercadoPago

Common Errors

Status CodeErrorDescription
400Items are requiredNo items provided in request
401Authentication errorInvalid MP_ACCESS_TOKEN
500Server configuration errorMissing environment variables
500Failed to create preferenceMercadoPago API error

Security

CORS Protection: The Cloudflare Worker only accepts requests from approved origins:
  • https://jcv24fitness.com
  • https://www.jcv24fitness.com
  • https://*.pages.dev
  • http://localhost:3000 (development)
External Reference Format: The worker automatically generates an external reference in the format JCV-{timestamp}-{userId} which is used for webhook processing and subscription activation.

Testing

Test Cards

Use these test cards in sandbox mode:
CardNumberCVVExpiry
Visa4509 9535 6623 3704123Any future date
Mastercard5031 7557 3453 0604123Any future date

Sandbox Environment

To test in sandbox mode:
  1. Use NEXT_PUBLIC_MP_PUBLIC_KEY starting with TEST-
  2. Redirect users to sandboxInitPoint instead of initPoint
  3. Use test card numbers from the table above

Payment Webhook

Handle MercadoPago payment notifications

Additional Resources

Build docs developers (and LLMs) love