### Mercado Pago Environment Configuration (Bash) Source: https://context7.com/goncy/next-mercadopago/llms.txt Provides essential environment variable setup for various Mercado Pago integrations, including Checkout Pro, Bricks, API, and Marketplace. Details required keys, tokens, and application URLs, along with installation and development commands. ```bash # .env.local configuration # For Checkout Pro, Checkout Bricks, Checkout API MP_ACCESS_TOKEN=TEST-1234567890-your-access-token NEXT_PUBLIC_MP_PUBLIC_KEY=TEST-your-public-key # For Marketplace integration (additional) NEXT_PUBLIC_MP_CLIENT_ID=1234567890 MP_CLIENT_SECRET=your-client-secret # Application URL for webhooks and OAuth callbacks APP_URL=https://your-app-url.com # Install dependencies npm install mercadopago @mercadopago/sdk-react # Run development server npm run dev ``` -------------------------------- ### Webhook Configuration Source: https://context7.com/goncy/next-mercadopago/llms.txt Configure webhooks to receive real-time payment and subscription notifications from Mercado Pago, enabling your application to react to events like payment success or failure. ```APIDOC ## Webhook Configuration ### Description Set up a webhook endpoint in your application to receive real-time notifications from Mercado Pago about payment status changes, subscription updates, and other relevant events. ### Method POST ### Endpoint `/api/mercadopago` (Example endpoint) ### Parameters **Request Body** - `data` (object) - Contains the specific data related to the event. - `id` (string) - The ID of the resource (e.g., payment ID). - `type` (string) - The type of event being notified (e.g., `payment`, `subscription`). ### Request Example ```bash # POST /api/mercadopago # Content-Type: application/json { "data": { "id": "1234567890" }, "type": "payment" } ``` ### Response #### Success Response (200 OK) Your webhook endpoint should return a `200 OK` status to acknowledge receipt of the notification. Mercado Pago may retry if a non-2xx status is received. #### Response Example (No specific JSON response body is required for acknowledgment, just a 200 status code) ### Local Testing Use a tunneling service like `ngrok` to expose your local development server to the internet for testing webhooks. ```bash # Start local server npm run dev # Expose local server using ngrok ngrok http 3000 # Update APP_URL in your .env.local file with the ngrok URL # Configure the ngrok URL as the webhook endpoint in your Mercado Pago dashboard ``` ``` -------------------------------- ### Environment Configuration Source: https://context7.com/goncy/next-mercadopago/llms.txt Configure the necessary environment variables in your `.env.local` file to enable Mercado Pago integrations for different features like Checkout Pro, Marketplace, and Webhooks. ```APIDOC ## Environment Variables Setup ### Description This section details the required environment variables for setting up Mercado Pago integrations, including access tokens, public keys, client IDs, and application URLs. ### Configuration File `.env.local` ### Variables **For Checkout Pro, Checkout Bricks, Checkout API:** ```bash MP_ACCESS_TOKEN=TEST-1234567890-your-access-token NEXT_PUBLIC_MP_PUBLIC_KEY=TEST-your-public-key ``` **For Marketplace integration (additional):** ```bash NEXT_PUBLIC_MP_CLIENT_ID=1234567890 MP_CLIENT_SECRET=your-client-secret ``` **For Webhooks and OAuth callbacks:** ```bash APP_URL=https://your-app-url.com ``` ### Installation Install the necessary Mercado Pago SDK packages: ```bash npm install mercadopago @mercadopago/sdk-react ``` ### Development Server Run your development server: ```bash npm run dev ``` ``` -------------------------------- ### Subscriptions - Recurring Payment Management Source: https://context7.com/goncy/next-mercadopago/llms.txt Create and manage recurring subscriptions with automatic billing using Mercado Pago's PreApproval API. ```APIDOC ## Create Subscription ### Description Creates a recurring subscription for a user, setting up automatic billing through Mercado Pago's PreApproval API. ### Method (Internal Function) ### Endpoint (Internal Function) ### Parameters #### Request Body - **email** (string) - Required - The email of the user to subscribe. ### Request Example ```typescript // src/subscription.ts import {MercadoPagoConfig, PreApproval} from "mercadopago"; const mercadopago = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN! }); async function subscribe(email: string) { const subscription = await new PreApproval(mercadopago).create({ body: { back_url: process.env.APP_URL!, reason: "Suscripción a mensajes de muro", auto_recurring: { frequency: 1, frequency_type: "months", transaction_amount: 100, currency_id: "ARS", }, payer_email: email, status: "pending", }, }); return subscription.init_point!; } ``` ### Response #### Success Response (200) - **init_point** (string) - The URL to redirect the user to complete the subscription setup. #### Response Example ```json { "init_point": "https://www.mercadopago.com.ar/subscriptions/v1/preapproval/..." } ``` ## Webhook Handler for Subscription Notifications ### Description Handles webhook notifications related to subscription status changes from Mercado Pago. ### Method POST ### Endpoint /api/webhooks/mercadopago (or similar) ### Parameters #### Request Body - **data** (object) - Required - Contains the subscription data. - **id** (string) - Required - The ID of the preapproval object. - **type** (string) - Required - The type of notification (e.g., 'subscription_preapproval'). ### Response #### Success Response (200) - **status** (integer) - 200 OK #### Response Example (No response body) ### Detailed Subscription Handling Example ```typescript // src/app/api/webhooks/mercadopago/route.ts import {MercadoPagoConfig, PreApproval} from "mercadopago"; const mercadopago = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN! }); export async function POST(request: Request) { const body: {data: {id: string}; type: string} = await request.json(); if (body.type === "subscription_preapproval") { const preapproval = await new PreApproval(mercadopago).get({ id: body.data.id }); if (preapproval.status === "authorized") { // Example: Update user subscription status in your database // await api.user.update({ subscription: preapproval.id }); } } return new Response(null, {status: 200}); } ``` ``` -------------------------------- ### Mercado Pago Webhook Configuration (Bash) Source: https://context7.com/goncy/next-mercadopago/llms.txt Demonstrates how to configure webhooks for Mercado Pago to receive real-time payment and subscription notifications. Includes setting up the webhook URL, testing locally with ngrok, and updating environment variables. ```bash # Configure webhook URL in Mercado Pago dashboard # URL format: https://your-domain.com/api/mercadopago # Webhook endpoint receives notifications POST /api/mercadopago Content-Type: application/json { "data": { "id": "1234567890" }, "type": "payment" } # Test webhook locally using tunneling service # Example with ngrok: ngrok http 3000 # Update APP_URL in .env.local with ngrok URL # Configure webhook in Mercado Pago dashboard ``` -------------------------------- ### Checkout Bricks - Embedded Payment Form (TypeScript) Source: https://context7.com/goncy/next-mercadopago/llms.txt This example integrates Mercado Pago's Checkout Bricks for an embedded payment form, allowing users to enter card details directly within your application. It includes client-side initialization and card token creation, along with server-side payment processing. Dependencies include `@mercadopago/sdk-react` and the official `mercadopago` SDK. Requires `NEXT_PUBLIC_MP_PUBLIC_KEY` for client-side and `MP_ACCESS_TOKEN` for server-side. ```typescript // Client-side form component "use client"; import { initMercadoPago, CardNumber, ExpirationDate, SecurityCode, createCardToken } from "@mercadopago/sdk-react"; initMercadoPago(process.env.NEXT_PUBLIC_MP_PUBLIC_KEY!); async function handleSubmit(formData: FormData) { const message = formData.get("message") as string; const name = formData.get("name") as string; const email = formData.get("email") as string; const token = await createCardToken({cardholderName: name}); await onSubmitAction(message, { amount: 100, email, installments: 1, token: token!.id, }); } ``` ```typescript // Server-side payment processing import {MercadoPagoConfig, Payment} from "mercadopago"; async function buy(data: { amount: number; email: string; installments: number; token: string; }) { const payment = await new Payment(mercadopago).create({ body: { payer: {email: data.email}, token: data.token, transaction_amount: data.amount, installments: data.installments, }, }); return payment; } ``` -------------------------------- ### Checkout Pro - Payment Preference with Redirect Source: https://context7.com/goncy/next-mercadopago/llms.txt Create payment preferences that redirect users to Mercado Pago's hosted checkout page and handle webhook notifications to confirm payments. ```APIDOC ## POST /api/mercadopago ### Description Handles webhook notifications from Mercado Pago to confirm payment status and process messages. ### Method POST ### Endpoint /api/mercadopago ### Parameters #### Request Body - **data** (object) - Required - Contains payment data, including the payment ID. - **id** (string) - Required - The ID of the payment. ### Response #### Success Response (200) - **status** (integer) - 200 OK #### Response Example (No response body) ## Create Payment Preference (Internal API) ### Description Creates a payment preference for Checkout Pro, generating an initialization point for redirecting users to Mercado Pago's checkout. ### Method (Internal Function) ### Endpoint (Internal Function) ### Parameters #### Request Body - **text** (string) - Required - The message content to be posted. ### Request Example ```typescript // src/api.ts import {MercadoPagoConfig, Preference} from "mercadopago"; const mercadopago = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN! }); async function submit(text: string) { const preference = await new Preference(mercadopago).create({ body: { items: [ { id: "message", unit_price: 100, quantity: 1, title: "Mensaje de muro", }, ], metadata: { text, }, }, }); return preference.init_point!; } ``` ### Response #### Success Response (200) - **init_point** (string) - The URL to redirect the user for payment. #### Response Example ```json { "init_point": "https://www.mercadopago.com.ar/checkout/v1/init?pref_id=..." } ``` ``` -------------------------------- ### Marketplace - Split Payment Integration Source: https://context7.com/goncy/next-mercadopago/llms.txt Integrate marketplace functionality with OAuth authorization and automatic platform fee collection. This allows sellers to receive payments while the platform deducts its fees. ```APIDOC ## OAuth Authorization Flow ### Description Initiates the OAuth flow to authorize your application to act on behalf of a seller or user in Mercado Pago. ### Method GET (Implicitly, via redirection) ### Endpoint `/mercadopago/connect` (Callback endpoint) ### Parameters **Query Parameters** - `code` (string) - Required - Authorization code received from Mercado Pago. ### Request Example ```typescript import {MercadoPagoConfig, OAuth} from "mercadopago"; async function authorize() { const mercadoPago = new MercadoPagoConfig({ accessToken: "YOUR_ACCESS_TOKEN" }); // Replace with actual access token handling const url = new OAuth(mercadoPago).getAuthorizationURL({ options: { client_id: process.env.NEXT_PUBLIC_MP_CLIENT_ID, redirect_uri: `${process.env.APP_URL}/api/mercadopago/connect`, }, }); return url; } ``` ### Response Example Redirects to Mercado Pago's authorization page. ## Connect Callback Handler ### Description Handles the callback from Mercado Pago after user authorization, exchanging the authorization code for access and refresh tokens. ### Method GET ### Endpoint `/api/mercadopago/connect` ### Parameters **Query Parameters** - `code` (string) - Required - The authorization code provided by Mercado Pago. ### Request Example ```typescript import { NextRequest, NextResponse } from "next/server"; import { MercadoPagoConfig, OAuth } from "mercadopago"; // Assuming 'api' and 'mercadopago' are correctly initialized and available // const mercadopago = new MercadoPagoConfig({ accessToken: "YOUR_ACCESS_TOKEN" }); // Replace with actual token handling export async function GET(request: NextRequest) { const code = request.nextUrl.searchParams.get("code"); // const mercadoPago = new MercadoPagoConfig({ accessToken: "YOUR_ACCESS_TOKEN" }); // Replace with actual token handling const credentials = await new OAuth(mercadoPago).create({ body: { client_id: process.env.NEXT_PUBLIC_MP_CLIENT_ID, client_secret: process.env.MP_CLIENT_SECRET, code: code!, redirect_uri: `${process.env.APP_URL}/api/mercadopago/connect`, }, }); // Assuming 'api.user.update' is a function to update user credentials // await api.user.update({ marketplace: credentials.access_token }); console.log("Access Token:", credentials.access_token); console.log("Refresh Token:", credentials.refresh_token); return NextResponse.redirect(process.env.APP_URL! || "/"); } ``` ### Response #### Success Response (200) Redirects to the application's home URL. ## Create Preference with Marketplace Fee ### Description Creates a payment preference for a transaction, including items, metadata, and a marketplace fee that will be automatically collected. ### Method POST (Internal SDK call) ### Endpoint N/A (SDK method) ### Parameters **Request Body (SDK payload)** - `items` (array) - Required - List of items in the order. - `id` (string) - Required - Item identifier. - `unit_price` (number) - Required - Price per unit. - `quantity` (number) - Required - Quantity of the item. - `title` (string) - Required - Name of the item. - `metadata` (object) - Optional - Additional data to be stored with the preference. - `text` (string) - Example field for metadata. - `marketplace_fee` (number) - Required - The fee charged by the marketplace. ### Request Example ```typescript import { MercadoPagoConfig, Preference } from "mercadopago"; async function submit(text: string, marketplaceAccessToken: string) { const client = new MercadoPagoConfig({ accessToken: marketplaceAccessToken }); const preference = await new Preference(client).create({ body: { items: [ { id: "message", unit_price: 100, quantity: 1, title: "Mensaje de muro", }, ], metadata: { text: text }, marketplace_fee: 5, }, }); return preference.init_point; } ``` ### Response #### Success Response (201 Created) - `id` (string) - The unique identifier for the preference. - `init_point` (string) - The URL to redirect the user to for payment. #### Response Example ```json { "id": "1234567890", "init_point": "https://www.mercadopago.com.ar/checkout/v1/payment/redirect?preference_id=1234567890" } ``` ``` -------------------------------- ### Subscriptions - Create Recurring Payment and Handle Webhook (TypeScript) Source: https://context7.com/goncy/next-mercadopago/llms.txt This snippet demonstrates how to set up and manage recurring payments using Mercado Pago's PreApproval API for subscriptions. It includes functions to create a subscription plan and a webhook handler to receive notifications about subscription status changes. It utilizes the official Mercado Pago SDK for Node.js and requires `MP_ACCESS_TOKEN` and `APP_URL` environment variables. ```typescript // Create subscription import {MercadoPagoConfig, PreApproval} from "mercadopago"; const mercadopago = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN! }); async function subscribe(email: string) { const subscription = await new PreApproval(mercadopago).create({ body: { back_url: process.env.APP_URL!, reason: "Suscripción a mensajes de muro", auto_recurring: { frequency: 1, frequency_type: "months", transaction_amount: 100, currency_id: "ARS", }, payer_email: email, status: "pending", }, }); return subscription.init_point!; } ``` ```typescript // Webhook handler for subscription notifications export async function POST(request: Request) { const body: {data: {id: string}; type: string} = await request.json(); if (body.type === "subscription_preapproval") { const preapproval = await new PreApproval(mercadopago).get({ id: body.data.id }); if (preapproval.status === "authorized") { await api.user.update({subscription: preapproval.id}); } } return new Response(null, {status: 200}); } ``` -------------------------------- ### Checkout Pro - Create Payment Preference and Handle Webhook (TypeScript) Source: https://context7.com/goncy/next-mercadopago/llms.txt This snippet demonstrates how to create a payment preference using Mercado Pago's Checkout Pro, which redirects users to a hosted payment page. It also includes a webhook handler to process payment confirmation notifications. It uses the official Mercado Pago SDK for Node.js and requires an MP_ACCESS_TOKEN. ```typescript import {MercadoPagoConfig, Preference} from "mercadopago"; const mercadopago = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN! }); async function submit(text: string) { const preference = await new Preference(mercadopago).create({ body: { items: [ { id: "message", unit_price: 100, quantity: 1, title: "Mensaje de muro", }, ], metadata: { text, }, }, }); return preference.init_point!; } ``` ```typescript // src/app/api/mercadopago/route.ts - Webhook handler import {Payment} from "mercadopago"; export async function POST(request: Request) { const body: {data: {id: string}} = await request.json(); const payment = await new Payment(mercadopago).get({id: body.data.id}); if (payment.status === "approved") { await api.message.add({ id: payment.id!, text: payment.metadata.text }); } return new Response(null, {status: 200}); } ``` -------------------------------- ### Checkout API - Custom Payment UI Source: https://context7.com/goncy/next-mercadopago/llms.txt Build fully customized payment forms using Mercado Pago's secure React components, ensuring PCI compliance while offering a seamless user experience. ```APIDOC ## Initialize SDK and Create Payment Form ### Description Initializes the Mercado Pago SDK with your public key and provides a React component for creating a custom payment form using provided input fields and card tokenization. ### Method Client-side JavaScript ### Endpoint N/A (Component) ### Parameters **Component Props** - `onSubmitAction` (function) - Required - Callback function to handle form submission with payment details. - `amount` (number) - Required - The payment amount. **Form Fields (Input)** - `message` (textarea) - Required - User's message. - `name` (input[type=text]) - Required - Cardholder's name. - `email` (input[type=email]) - Required - Cardholder's email. **Card Component Fields** - `CardNumber` - `ExpirationDate` - `SecurityCode` ### Request Example ```typescript "use client"; import { initMercadoPago, CardNumber, ExpirationDate, SecurityCode, createCardToken } from "@mercadopago/sdk-react"; import Form from "next/form"; // Initialize with your public key initMercadoPago(process.env.NEXT_PUBLIC_MP_PUBLIC_KEY!); export default function MessageForm({ onSubmitAction, amount }) { async function handleSubmit(formData: FormData) { const message = formData.get("message") as string; const name = formData.get("name") as string; const email = formData.get("email") as string; // Create card token using SDK const token = await createCardToken({ cardholderName: name, // Add other card details as needed (cardNumber, expirationDate, securityCode) }); // Execute the provided onSubmitAction with payment details await onSubmitAction(message, { amount, email, installments: 1, token: token!.id, }); } return (