next-mercadopago

repository·main·Indexed 20 days ago

https://github.com/goncy/next-mercadopago

A collection of implementation guides and example applications for integrating Mercado Pago payment flows into Next.js apps using the App Router. Supported integrations include Checkout Pro, Checkout Bricks, Checkout API, Subscriptions, and Marketplace. The repository provides guidance on credential management, test account setup, webhook configuration using tunneling tools, and the use of @mercadopago/sdk-react for secure payment forms.

Tokens
13.3K
Snippets
36
Records
51
Agent score
71%

What's inside next-mercadopago

  1. Overview of Mercado Pago integrations in Next.js

    main

    This repository provides various implementation patterns for integrating Mercado Pago into a Next.js application using the App Router. The primary use case demonstrated is a messaging application where users must pay or subscribe to post messages.

    Available integration patterns include:

    • Checkout Pro: Creates a payment preference and redirects the user to the Mercado Pago hosted checkout page. Includes webhook configuration for payment verification.
    • Subscriptions: Implements subscription models (without an associated plan and with pending payments) and uses webhooks to handle subscription notifications.
    • Checkout Bricks: Uses Mercado Pago's 'Bricks' to collect payment information directly within your application's UI.
    • Marketplace (Split Payments): Acts as an intermediary between a buyer and a seller (e.g., a user wanting to post on someone else's wall), using Checkout Pro to split payments and retain a commission.
    • Checkout API: Provides the highest level of UI control by using custom components and the Mercado Pago React component library to process payments securely and compliantly within your own platform.
  2. Subscription types in Mercado Pago

    main

    When integrating subscriptions, you can choose between two main patterns:

    1. Subscriptions with an associated plan: Requires a two-step process: first creating a plan (defining title, amount, etc.), then creating the subscription. This typically requires a card_token_id obtained via Checkout Bricks or Checkout API.
    2. Subscriptions without an associated plan: Created at the moment of payment without a pre-defined plan. This is ideal for redirecting users to Mercado Pago via an init_point. These can be:
      • Authorized payment: Requires a card_token_id immediately.
      • Pending payment: The user completes the payment on the Mercado Pago site (recommended for simple redirect integrations).
  3. Understand Mercado Pago credential types

    main

    Mercado Pago credentials are public or private keys used by your Next.js application to interact with the Mercado Pago API. There are two primary types:

    1. Production Credentials (Credenciales de producción): Used for real transactions in a live environment.
    2. Test Credentials (Credenciales de prueba): Used for testing transactions in a sandbox environment.

    Important distinction for specific integrations:

    • Checkout Bricks: During development, you typically use the Test Credentials of your application.
    • Checkout Pro or Subscriptions: To test these, you must log in with a test account (usually a Seller test account) and create an application. You will then use the Production Credentials of that test account. In the context of a test account, 'Production' credentials function as 'Test' credentials.
  4. Prevent duplicate processing of payments

    main

    When processing webhooks, it is critical to ensure that a single payment does not trigger the same action multiple times (idempotency).

    To prevent duplicate entries (e.g., adding the same message twice to a database), check if the unique identifier from the payment (such as payment.id) has already been processed before performing the business logic.

    // Example logic inside your processing function
    if (db.some((_message) => _message.id === message.id)) {
      throw new Error("Message already added");
    }
  5. Clone the initial application

    main

    The repository contains multiple Next.js applications, each representing a different Mercado Pago integration. To start working with a specific integration, clone the repository and navigate to the corresponding directory within the integraciones/ folder.

    Available integrations:

    • checkout-pro: For implementing Checkout Pro.
    • suscripciones: For implementing Subscriptions.
    • checkout-bricks: For implementing Checkout Bricks.
    • marketplace: For implementing Marketplace.
    # Clone the repository
    git clone https://github.com/goncy/next-mercadopago.git
    
    # Enter the repository folder
    cd next-mercadopago
    
    # Navigate to a specific integration (example: Checkout Pro)
    cd integraciones/checkout-pro
  6. Configure a Webhook in Mercado Pago

    main

    To receive payment and subscription notifications, you must configure a Webhook in the Mercado Pago Developer Panel.

    1. Expose your local environment: Before configuring, ensure your local port is exposed to the internet (e.g., using a tool like ngrok) so Mercado Pago can reach your machine.
    2. Access Webhooks: Go to the Mercado Pago Developer Panel, select your application, and click on Webhooks in the left sidebar.
    3. Configure Notifications: Click on Configurar notificaciones.
    4. Set Environment and URL:
      • Select the desired environment (e.g., Modo productivo if using a test account).
      • In the Production URL field, use the base URL from your APP_URL environment variable and append your specific API endpoint. For example, if your endpoint is /api/mercadopago, the URL should look like https://your-exposed-url.com/api/mercadopago.
    5. Select Events: Choose the specific events you wish to listen to and click Guardar configuración.

    Testing: You can use the Simular notificación button in the panel to verify connectivity. Even if the simulation returns an error (e.g., because the payment ID doesn't exist), a successful log in your local terminal confirms that Mercado Pago can communicate with your application.

  7. Expose port using VSCode Dev Tunnels

    main

    If you are using VSCode, you can use the built-in Dev Tunnels feature:

    1. Open the Ports section in VSCode (if not visible, press Ctrl+Shift+P or Cmd+Shift+P and search for Forward a Port).
    2. Click on Forward a Port.
    3. Enter your application's port (e.g., 3000).
    4. Crucial: Change the visibility of the generated URL from Private to Public so that Mercado Pago's servers can access it.
  8. Create a subscription without an associated plan

    main

    To implement subscriptions where users are redirected to Mercado Pago to complete a pending payment, use the PreApproval class from the mercadopago SDK. This method creates a subscription with a pending status and returns an init_point URL. You can then redirect the user to this URL to complete the transaction.

    Key configuration options for the subscription body:

    • back_url: The URL to redirect the user back to after the process.
    • reason: A description of the subscription.
    • auto_recurring: Defines the frequency (e.g., months), frequency type, amount, and currency.
    • payer_email: The email of the user subscribing.
    • status: Set to pending to allow the user to complete the payment on Mercado Pago's site.
    import { PreApproval } from "mercadopago";
    
    // Inside your API logic
    const suscription = 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",
      },
    });
    
    const url = suscription.init_point!;
    // Redirect the user to this url
  9. Handle subscription notifications via Webhooks

    main

    To update your application's state (e.g., granting access to a user) when a subscription is paid, you must implement a Webhook endpoint (Route Handler) to listen for subscription_preapproval events from Mercado Pago.

    Workflow:

    1. Receive a POST request from Mercado Pago.
    2. Verify the type is subscription_preapproval.
    3. Use the id from body.data.id to fetch the subscription details using PreApproval.get({ id }).
    4. If preapproval.status is authorized, update your local database with the subscription ID.
    5. Crucial: Always return a 200 OK response to Mercado Pago to acknowledge receipt. Only return non-200 status codes if you want Mercado Pago to retry the notification.
    import { PreApproval } from "mercadopago";
    import api, { mercadopago } from "@/api";
    
    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") {
          // Update your user/database with the subscription ID
          await api.user.update({ suscription: preapproval.id });
        }
      }
    
      return new Response(null, { status: 200 });
    }
  10. Configure the Mercado Pago Redirect URL

    main

    To handle the OAuth authorization flow, you must configure a redirect URL in the Mercado Pago administration panel for your Marketplace application.

    1. Log in to the Marketplace account's Mercado Pago dashboard.
    2. Edit your application settings.
    3. In the URLs de redireccionamiento (Redirect URLs) section, add your application's base URL followed by /api/mercadopago/connect.

    Example: If APP_URL is http://localhost:3000, the redirect URL should be http://localhost:3000/api/mercadopago/connect.

  11. Create a Mercado Pago application

    main

    To use next-mercadopago in your Next.js project, you must first create an application within the Mercado Pago developer ecosystem to obtain the necessary credentials and configure transaction event notifications.

    1. Navigate to the Mercado Pago Developers Panel.
    2. Create a new application.
    3. Fill in the required application details.
    4. When prompted with "¿Qué producto estás integrando?" (Which product are you integrating?), select the product relevant to your integration needs.
    5. Once created, you will be redirected to the integration screen where you can access your credentials.