### Install Medusa Payment Mercadopago Plugin Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/README.md Install the plugin using npm or yarn. Ensure you are in the Medusa backend directory. ```bash npm install @nicogorga/medusa-payment-mercadopago ``` -------------------------------- ### Create a Basic GET API Route Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/api/README.md Define a simple GET endpoint at `/store/hello-world` by creating a `route.ts` file in the appropriate directory. This example shows the basic structure for a Medusa API route. ```typescript import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"; export async function GET(req: MedusaRequest, res: MedusaResponse) { res.json({ message: "Hello world!", }); } ``` -------------------------------- ### Create API Route with Path Parameter Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/api/README.md Define API routes that accept dynamic path parameters by naming directories in the `[param]` format. This example shows how to capture a `productId` from the URL. ```typescript import type { MedusaRequest, MedusaResponse, } from "@medusajs/framework/http" export async function GET(req: MedusaRequest, res: MedusaResponse) { const { productId } = req.params; res.json({ message: `You're looking for product ${productId}` }) } ``` -------------------------------- ### Mercado Pago Payment Methods Response Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Example response structure for fetching available payment methods from Mercado Pago. ```json { "paymentMethods": [ { "id": "1234567890", "data": { "id": "1234567890", "customer_id": "123456789-abcdef", "expiration_month": 12, "expiration_year": 2028, "first_six_digits": "450995", "last_four_digits": "3704", "payment_method": { "id": "visa", "name": "Visa", "payment_type_id": "credit_card" }, "cardholder": { "name": "APRO", "identification": { "type": "CI", "number": "12345678" } }, "issuer": { "id": 1, "name": "Visa" } } } ] } ``` -------------------------------- ### Get Store Mercadopago Payment Methods Params Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Interface for query parameters when fetching Mercado Pago payment methods for a store. Ensure the provider_id is correctly set. ```typescript // Query parameters interface GetStoreMercadopagoPaymentMethodsParams { provider_id: string; // Must be "pp_mercadopago_mercadopago" limit?: number; // Default: 50 offset?: number; // Default: 0 } ``` -------------------------------- ### Create a Custom Scheduled Job Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/jobs/README.md This example demonstrates how to create a custom scheduled job in TypeScript. It defines a handler function that resolves services from the Medusa container and a configuration object specifying the job's name and schedule. ```typescript import { MedusaContainer } from "@medusajs/framework/types"; export default async function myCustomJob(container: MedusaContainer) { const productService = container.resolve("product") const products = await productService.listAndCountProducts(); // Do something with the products } export const config = { name: "daily-product-report", schedule: "0 0 * * *", // Every day at midnight }; ``` -------------------------------- ### Get Saved Payment Methods Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Retrieve saved payment methods (cards) for an authenticated customer from Mercado Pago. Requires customer authentication and the provider ID. ```bash # Get saved payment methods for the customer curl -X GET "http://localhost:9000/store/mercadopago/payment-methods?provider_id=pp_mercadopago_mercadopago" \ -H "Authorization: Bearer {customer_token}" ``` -------------------------------- ### Configure Middleware for API Routes Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/api/README.md Apply custom middleware functions to specific API routes by defining them in `/api/middlewares.ts`. This example shows how to apply a `logger` middleware to the `/store/custom` route using `defineMiddlewares`. ```typescript import { defineMiddlewares } from "@medusajs/framework/http" import type { MedusaRequest, MedusaResponse, MedusaNextFunction, } from "@medusajs/framework/http"; async function logger( req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction ) { console.log("Request received"); next(); } export default defineMiddlewares({ routes: [ { matcher: "/store/custom", middlewares: [logger], }, ], }) ``` -------------------------------- ### Access Medusa Container in API Route Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/api/README.md Utilize the Medusa container available on `req.scope` to resolve and use core services within your API route handlers. This example demonstrates fetching product data using the `product` module service. ```typescript import type { MedusaRequest, MedusaResponse, } from "@medusajs/framework/http" export const GET = async ( req: MedusaRequest, res: MedusaResponse ) => { const productModuleService = req.scope.resolve("product") const [, count] = await productModuleService.listAndCount() res.json({ count, }) } ``` -------------------------------- ### GET /store/mercadopago/payment-methods Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Retrieves saved payment methods (cards) for the authenticated customer from Mercado Pago. Requires authentication and returns a list of cards previously saved to the customer's Mercado Pago account. ```APIDOC ## GET /store/mercadopago/payment-methods ### Description Retrieves saved payment methods (cards) for the authenticated customer from Mercado Pago. Requires authentication and returns a list of cards previously saved to the customer's Mercado Pago account. ### Method GET ### Endpoint /store/mercadopago/payment-methods ### Parameters #### Query Parameters - **provider_id** (string) - Required - The ID of the payment provider (e.g., "pp_mercadopago_mercadopago") #### Headers - **Authorization** (string) - Required - Bearer token for customer authentication (e.g., "Bearer {customer_token}") ### Request Example ```bash curl -X GET "http://localhost:9000/store/mercadopago/payment-methods?provider_id=pp_mercadopago_mercadopago" \ -H "Authorization: Bearer {customer_token}" ``` ### Response #### Success Response (200) Returns a list of saved payment methods (cards). #### Response Example ```json [ { "id": "card_1234567890abcdef", "brand": "visa", "last4": "1111", "exp_month": 12, "exp_year": 2025 } ] ``` ``` -------------------------------- ### Define Multiple HTTP Method Handlers Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/api/README.md Export functions named after supported HTTP methods (GET, POST, PUT, etc.) within your `route.ts` file to handle different request types for the same endpoint. This allows for a single route to manage various operations. ```typescript import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"; export async function GET(req: MedusaRequest, res: MedusaResponse) { // Handle GET requests } export async function POST(req: MedusaRequest, res: MedusaResponse) { // Handle POST requests } export async function PUT(req: MedusaRequest, res: MedusaResponse) { // Handle PUT requests } ``` -------------------------------- ### Generate Database Migrations Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/modules/README.md Run this command in the plugin's directory to generate database migrations for your module's data models. ```bash npx medusa plugin:db:genreate ``` -------------------------------- ### Configure Mercado Pago Webhook URL Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Instructions for configuring the webhook URL in the Mercado Pago dashboard and using ngrok for local development. ```bash # Configure webhook URL in Mercado Pago dashboard # URL: https://your-domain.com/hooks/payment/mercadopago_mercadopago # Events: Pagos (payment.created, payment.updated) # For local development with ngrok: ngrok http 9000 # Then set webhook URL to: https://{ngrok-id}.ngrok-free.app/hooks/payment/mercadopago_mercadopago ``` -------------------------------- ### MercadopagoProviderService Payment Lifecycle Methods Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Demonstrates the core payment lifecycle methods implemented by the MercadopagoProviderService, including initiation, authorization, capture, cancellation, and refund. ```typescript // Payment lifecycle methods implemented by the provider // initiatePayment - Called when payment session is created // Returns session data with amount for reference const session = await provider.initiatePayment({ data: { session_id: "payses_01..." }, amount: 15000, // Amount in cents currency_code: "UYU" }); // authorizePayment - Called during checkout completion // Searches Mercado Pago for approved payment by external_reference const result = await provider.authorizePayment({ data: { session_id: "payses_01..." } }); // Returns: { status: "captured", data: { id: "12345", ... } } // capturePayment - Auto-capture is assumed for card payments const captured = await provider.capturePayment({ data: { id: "12345" } }); // cancelPayment - Cancels authorized or refunds captured payments const cancelled = await provider.cancelPayment({ data: { id: "12345" }, context: { idempotency_key: "unique-key" } }); // refundPayment - Creates full or partial refunds const refund = await provider.refundPayment({ data: { id: "12345" }, amount: 5000 // Partial refund amount }); ``` -------------------------------- ### MercadopagoProviderService Options Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Defines the options required for initializing the MercadopagoProviderService, including API credentials. ```typescript // Provider initialization with options interface MercadopagoOptions { accessToken: string; // Mercado Pago API access token webhookSecret?: string; // Optional webhook signature secret } ``` -------------------------------- ### Sync Module Links to Database Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/links/README.md Run this command in your Medusa application to apply the defined module links to the database schema. ```bash npx medusa db:migrate ``` -------------------------------- ### Create Payment with Card Token Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Use this endpoint to create a payment in Mercado Pago using tokenized card data from the Payment Brick. It validates the transaction amount, creates the payment, and can save the card for authenticated customers. Handles success (201) and rejection (400) responses. ```bash # Create a payment with card token from Payment Brick curl -X POST http://localhost:9000/store/mercadopago/payment \ -H "Content-Type: application/json" \ -H "Authorization: Bearer {customer_token}" \ -d '{ "paymentSessionId": "payses_01HXYZ123456789ABCDEF", "paymentData": { "token": "ee9e1d5a9b76f3ec4a1e91c7c99f7e03", "transaction_amount": 150.00, "installments": 1, "payment_method_id": "visa", "payer": { "email": "customer@example.com", "identification": { "type": "CI", "number": "12345678" } } } }' # Response on success # HTTP 201 {} # Response on payment rejection # HTTP 400 { "type": "payment_authorization_error", "message": "Saldo insuficiente." } ``` -------------------------------- ### Create a Module Service Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/modules/README.md Define a service class for your module, extending `MedusaService` and specifying the data models it will interact with. This class holds the business logic for the module. ```typescript import { MedusaService } from "@medusajs/framework/utils" import Post from "./models/post" class BlogModuleService extends MedusaService({ Post, }){ } export default BlogModuleService ``` -------------------------------- ### Configure Mercado Pago Environment Variables Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/README.md Set the Mercado Pago Access Token and an optional Webhook Secret in your .env file. The Access Token is found in your Mercado Pago application's Test Credentials. ```env MERCADOPAGO_ACCESS_TOKEN= # (Optional) Webhook secret available in your Mercado Pago application Webhooks section MERCADOPAGO_WEBHOOK_SECRET= ``` -------------------------------- ### Create a Product Details Widget Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/admin/README.md Define a React widget to be injected into the product details page in the Medusa Admin. Ensure the widget configuration specifies the desired zone for insertion. ```tsx import { defineWidgetConfig } from "@medusajs/admin-sdk" // The widget const ProductWidget = () => { return (

Product Widget

) } // The widget's configurations export const config = defineWidgetConfig({ zone: "product.details.after", }) export default ProductWidget ``` -------------------------------- ### Configure Plugin with Module Options Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/modules/README.md When registering a plugin in the Medusa application, you can pass options that will be forwarded to the modules within the plugin. This is done in the `defineConfig` configuration. ```typescript import { defineConfig } from "@medusajs/framework/utils" module.exports = defineConfig({ // ... plugins: [ { resolve: "@myorg/plugin-name", options: { apiKey: process.env.API_KEY, }, }, ], }) ``` -------------------------------- ### Save and List Payment Methods Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt These functions allow saving a customer's card for future use and listing their previously saved payment methods. Ensure you have the card token from the frontend Payment Brick. ```typescript // savePaymentMethod - Saves a card to customer's account const saved = await provider.savePaymentMethod({ data: { token: "card-token-from-brick" }, context: { account_holder: { data: { id: "123456789-abcdef" } }, idempotency_key: "card-token-from-brick" } }); // Returns: { id: "card-id", data: { ... } } ``` ```typescript // listPaymentMethods - Lists saved cards const methods = await provider.listPaymentMethods({ context: { account_holder: { data: { id: "123456789-abcdef" } } } }); // Returns: [{ id: "card-id", data: { last_four_digits: "3704", ... } }] ``` -------------------------------- ### Configure Payment Module for Mercado Pago Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/README.md Configure the payment module in `medusa-config.ts` to use the Mercado Pago provider. Specify the provider's resolve path, ID, and options, including dependencies like the logger. ```typescript modules: [ { resolve: '@medusajs/medusa/payment', options: { providers: [ { resolve: '@nicogorga/medusa-payment-mercadopago/providers/mercado-pago', id: 'mercadopago', options: { accessToken: process.env.MERCADOPAGO_ACCESS_TOKEN, webhookSecret: process.env.MERCADOPAGO_WEBHOOK_SECRET, }, dependencies: [ ContainerRegistrationKeys.LOGGER ] } ], } } ], ``` -------------------------------- ### Add Plugin to Medusa Config Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/README.md Register the Mercado Pago payment plugin in the `plugins` array of your `medusa-config.ts` file. Ensure the `accessToken` and `webhookSecret` are correctly passed from environment variables. ```typescript projectConfig: { plugins = [ // ... { resolve: `@nicogorga/medusa-payment-mercadopago`, options: { accessToken: process.env.MERCADOPAGO_ACCESS_TOKEN, webhookSecret: process.env.MERCADOPAGO_WEBHOOK_SECRET, }, }, ] } ``` -------------------------------- ### Basic Product Created Subscriber Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/subscribers/README.md A simple subscriber that logs a message when a product is created. Ensure the subscriber file is placed in the `src/subscribers` directory. ```typescript import { type SubscriberConfig, } from "@medusajs/framework" // subscriber function export default async function productCreateHandler() { console.log("A product was created") } // subscriber config export const config: SubscriberConfig = { event: "product.created", } ``` -------------------------------- ### Configure Medusa Payment Mercadopago Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Configure the plugin in your MedusaJS backend's medusa-config.ts file. Ensure your Mercado Pago access token and webhook secret are set as environment variables. ```typescript import { defineConfig, Modules } from '@medusajs/medusa' import { ContainerRegistrationKeys } from '@medusajs/framework/utils' export default defineConfig({ projectConfig: { plugins: [ { resolve: `@nicogorga/medusa-payment-mercadopago`, options: { accessToken: process.env.MERCADOPAGO_ACCESS_TOKEN, webhookSecret: process.env.MERCADOPAGO_WEBHOOK_SECRET, }, }, ], }, modules: [ { resolve: '@medusajs/medusa/payment', options: { providers: [ { resolve: '@nicogorga/medusa-payment-mercadopago/providers/mercado-pago', id: 'mercadopago', options: { accessToken: process.env.MERCADOPAGO_ACCESS_TOKEN, webhookSecret: process.env.MERCADOPAGO_WEBHOOK_SECRET, }, dependencies: [ ContainerRegistrationKeys.LOGGER ] } ], } } ], }) ``` -------------------------------- ### Define a Data Model for a Module Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/modules/README.md Create a data model for a module by defining its schema using `model.define`. This represents a table in the database. Ensure the file is located under the `models` directory of your module. ```typescript import { model } from "@medusajs/framework/utils" const Post = model.define("post", { id: model.id().primaryKey(), title: model.text(), }) export default Post ``` -------------------------------- ### Subscriber with Event Data and Container Access Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/subscribers/README.md This subscriber retrieves product details using the product ID from the event data and the `productModuleService` resolved from the container. It logs the product's title upon creation. ```typescript import type { SubscriberArgs, SubscriberConfig, } from "@medusajs/framework" export default async function productCreateHandler({ event: { data }, container, }: SubscriberArgs<{ id: string }>) { const productId = data.id const productModuleService = container.resolve("product") const product = await productModuleService.retrieveProduct(productId) console.log(`The product ${product.title} was created`) } export const config: SubscriberConfig = { event: "product.created", } ``` -------------------------------- ### MercadopagoProviderService Methods Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Core payment provider service methods for handling payment operations. ```APIDOC ## MercadopagoProviderService ### Description The core payment provider service that implements the Medusa `AbstractPaymentProvider` interface. It handles all payment operations through the Mercado Pago SDK. ### Provider Initialization ```typescript interface MercadopagoOptions { accessToken: string; // Mercado Pago API access token webhookSecret?: string; // Optional webhook signature secret } // The provider is registered with identifier "mercadopago" // Full provider ID in Medusa: "pp_mercadopago_mercadopago" ``` ### Payment Lifecycle Methods #### initiatePayment - **Description**: Called when payment session is created. - **Returns**: Session data with amount for reference. - **Example**: ```typescript const session = await provider.initiatePayment({ data: { session_id: "payses_01..." }, amount: 15000, // Amount in cents currency_code: "UYU" }); ``` #### authorizePayment - **Description**: Called during checkout completion. Searches Mercado Pago for approved payment by external_reference. - **Returns**: `{ status: "captured", data: { id: "12345", ... } }` - **Example**: ```typescript const result = await provider.authorizePayment({ data: { session_id: "payses_01..." } }); ``` #### capturePayment - **Description**: Auto-capture is assumed for card payments. - **Example**: ```typescript const captured = await provider.capturePayment({ data: { id: "12345" } }); ``` #### cancelPayment - **Description**: Cancels authorized or refunds captured payments. - **Example**: ```typescript const cancelled = await provider.cancelPayment({ data: { id: "12345" }, context: { idempotency_key: "unique-key" } }); ``` #### refundPayment - **Description**: Creates full or partial refunds. - **Example**: ```typescript const refund = await provider.refundPayment({ data: { id: "12345" }, amount: 5000 // Partial refund amount }); ``` ``` -------------------------------- ### createMercadopagoPaymentWorkflow Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Internal workflow for orchestrating payment creation, validation, and card saving. ```APIDOC ## createMercadopagoPaymentWorkflow ### Description Internal workflow that orchestrates payment creation, validation, and card saving. It validates the transaction amount matches the payment session, creates the payment in Mercado Pago, and optionally saves the card for authenticated customers. ### Usage ```typescript import { createMercadopagoPaymentWorkflow } from '@nicogorga/medusa-payment-mercadopago/workflows/mercadopago/workflows/create-payment' // Workflow input type interface CreatePaymentWorkflowInput { paymentSessionId: string; paymentData: { token: string; transaction_amount: number; installments: number; payment_method_id: string; payer: { email?: string; identification?: { type: string; number: string; }; } | { type: string; id: string; }; }; customerId?: string; // Medusa customer ID for card saving } // Workflow steps: // 1. get-payment-session - Fetches payment session from Medusa // 2. validateTransactionAmountStep - Ensures amounts match // 3. createPaymentStep - Creates payment in Mercado Pago // 4. get-customer - Fetches customer data if authenticated // 5. createPaymentMethodStep - Saves card (if customer exists, continues on failure) const { result } = await createMercadopagoPaymentWorkflow(scope).run({ input: { paymentSessionId: "payses_01HXYZ...", paymentData: { /* ... */ }, customerId: "cus_01HXYZ..." } }); ``` ``` -------------------------------- ### Define a Custom Workflow Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/workflows/README.md Define a custom workflow with multiple steps using the Medusa workflows SDK. Ensure all necessary imports are included. ```typescript import { createStep, createWorkflow, WorkflowResponse, StepResponse, } from "@medusajs/framework/workflows-sdk" const step1 = createStep("step-1", async () => { return new StepResponse(`Hello from step one!`) }) type WorkflowInput = { name: string } const step2 = createStep( "step-2", async ({ name }: WorkflowInput) => { return new StepResponse(`Hello ${name} from step two!`) } ) type WorkflowOutput = { message1: string message2: string } const helloWorldWorkflow = createWorkflow( "hello-world", (input: WorkflowInput) => { const greeting1 = step1() const greeting2 = step2(input) return new WorkflowResponse({ message1: greeting1, message2: greeting2 }) } ) export default helloWorldWorkflow ``` -------------------------------- ### Mercado Pago Webhook Handling Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Handles incoming webhook notifications from Mercado Pago for payment events. ```APIDOC ## Webhook Handling ### Description The plugin processes Mercado Pago webhook notifications for payment events. Webhooks should be configured in Mercado Pago to point to `/hooks/payment/mercadopago_mercadopago`. ### Webhook Payload Structure ```typescript interface MercadopagoWebhookPayload { action: string; // "payment.created" or "payment.updated" data: { id: string; // Mercado Pago payment ID }; } ``` ### Processing - The webhook handler validates signatures and processes events. - Supported actions: "payment.created", "payment.updated" - Returns `PaymentActions.SUCCESSFUL` for approved payments. - Returns `PaymentActions.AUTHORIZED` for authorized payments. ### Configuration #### Mercado Pago Dashboard - **Webhook URL**: `https://your-domain.com/hooks/payment/mercadopago_mercadopago` - **Events**: Pagos (payment.created, payment.updated) #### Local Development with ngrok 1. Run `ngrok http 9000` 2. Set webhook URL to: `https://{ngrok-id}.ngrok-free.app/hooks/payment/mercadopago_mercadopago` ``` -------------------------------- ### POST /store/mercadopago/payment Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Creates a payment in Mercado Pago using tokenized card data. It validates the transaction amount, creates the payment in Mercado Pago, and can save the card for authenticated customers. ```APIDOC ## POST /store/mercadopago/payment ### Description Creates a payment in Mercado Pago using tokenized card data from the Payment Brick. This endpoint validates the transaction amount against the Medusa payment session, creates the payment in Mercado Pago, and automatically saves the card for authenticated customers. ### Method POST ### Endpoint /store/mercadopago/payment ### Parameters #### Request Body - **paymentSessionId** (string) - Required - Medusa payment session ID - **paymentData** (object) - Required - Payment details - **token** (string) - Required - Card token from Payment Brick - **transaction_amount** (number) - Required - Amount in currency units - **installments** (number) - Required - Number of installments - **payment_method_id** (string) - Required - e.g., "visa", "master", "debvisa" - **payer** (object) - Optional - Payer information - **email** (string) - Optional - Payer's email - **identification** (object) - Optional - Payer's identification - **type** (string) - Required - e.g., "CI", "DNI", "CNPJ" - **number** (string) - Required - Payer's identification number - **type** (string) - Required if using existing customer - Type of customer reference - **id** (string) - Required if using existing customer - Mercado Pago customer ID ### Request Example ```json { "paymentSessionId": "payses_01HXYZ123456789ABCDEF", "paymentData": { "token": "ee9e1d5a9b76f3ec4a1e91c7c99f7e03", "transaction_amount": 150.00, "installments": 1, "payment_method_id": "visa", "payer": { "email": "customer@example.com", "identification": { "type": "CI", "number": "12345678" } } } } ``` ### Response #### Success Response (201) An empty object is returned on successful payment creation. #### Response Example ```json {} ``` #### Error Response (400) Returned on payment rejection. #### Response Example ```json { "type": "payment_authorization_error", "message": "Saldo insuficiente." } ``` ``` -------------------------------- ### Register Custom Notification Provider Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/providers/README.md Register a custom notification provider by specifying its resolve path and options. Ensure the provider is correctly configured with necessary channels and provider-specific options. ```javascript module.exports = defineConfig({ // ... modules: [ { resolve: "@medusajs/medusa/notification", options: { providers: [ { resolve: "@myorg/plugin-name/providers/my-notification", id: "my-notification", options: { channels: ["email"], // provider options... }, }, ], }, }, ], }) ``` -------------------------------- ### Manage Mercado Pago Account Holders Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Use these functions to create, update, and manage Mercado Pago customer accounts linked to Medusa customers. The `createAccountHolder` is called automatically on the first payment. ```typescript // createAccountHolder - Creates a Mercado Pago customer // Called automatically when customer makes first payment const accountHolder = await provider.createAccountHolder({ context: { customer: { email: "customer@example.com", first_name: "John", last_name: "Doe" }, idempotency_key: "unique-key" } }); // Returns: { id: "123456789-abcdef", data: { ... } } ``` ```typescript // updateAccountHolder - Updates customer info in Mercado Pago const updated = await provider.updateAccountHolder({ context: { account_holder: { data: { id: "123456789-abcdef" } }, customer: { email: "customer@example.com", first_name: "John", last_name: "Doe Updated", phone: "+59812345678" }, idempotency_key: "unique-key" } }); ``` -------------------------------- ### Execute Workflow in API Route Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/workflows/README.md Execute a custom workflow from an API route. The workflow is run with the input provided in the request query parameters. ```typescript import type { MedusaRequest, MedusaResponse, } from "@medusajs/framework" import myWorkflow from "../../../workflows/hello-world" export async function GET( req: MedusaRequest, res: MedusaResponse ) { const { result } = await myWorkflow(req.scope) .run({ input: { name: req.query.name as string, }, }) res.send(result) } ``` -------------------------------- ### Export Module Definition Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/modules/README.md Export the module definition from the `index.ts` file in the module's root directory. This specifies the module's name and its main service. ```typescript import BlogModuleService from "./service" import { Module } from "@medusajs/framework/utils" export const BLOG_MODULE = "blog" export default Module(BLOG_MODULE, { service: BlogModuleService, }) ``` -------------------------------- ### Payment Request Body Schema Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Defines the structure for the request body when creating a payment. Includes details for new or existing Mercado Pago payers. ```typescript // Request body validation schema interface PostStoreMercadopagoPayment { paymentSessionId: string; // Medusa payment session ID paymentData: { token: string; // Card token from Payment Brick transaction_amount: number; // Amount in currency units installments: number; // Number of installments payment_method_id: string; // e.g., "visa", "master", "debvisa" payer: { // Option 1: New payer email?: string; identification?: { type: string; // e.g., "CI", "DNI", "CNPJ" number: string; }; } | { // Option 2: Existing Mercado Pago customer type: string; id: string; }; }; } ``` -------------------------------- ### Use a Module in an API Route Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/modules/README.md Access and use a module's service within an API route by resolving it from the request scope using the module's defined identifier. ```typescript import { MedusaRequest, MedusaResponse } from "@medusajs/framework" import BlogModuleService from "../../../modules/blog/service" import { BLOG_MODULE } from "../../../modules/blog" export async function GET( req: MedusaRequest, res: MedusaResponse ): Promise { const blogModuleService: BlogModuleService = req.scope.resolve( BLOG_MODULE ) const posts = await blogModuleService.listPosts() res.json({ posts }) } ``` -------------------------------- ### Mercado Pago Payment Methods API Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Retrieves a list of available payment methods from Mercado Pago. ```APIDOC ## GET /mercadopago/payment-methods ### Description Retrieves a list of available payment methods from Mercado Pago. ### Method GET ### Endpoint /mercadopago/payment-methods ### Query Parameters - **provider_id** (string) - Required - Must be "pp_mercadopago_mercadopago" - **limit** (number) - Optional - Default: 50 - **offset** (number) - Optional - Default: 0 ### Response #### Success Response (200) - **paymentMethods** (array) - List of payment methods. - **id** (string) - The ID of the payment method. - **data** (object) - Additional data related to the payment method. - **id** (string) - Mercado Pago payment method ID. - **customer_id** (string) - Customer identifier. - **expiration_month** (number) - Expiration month. - **expiration_year** (number) - Expiration year. - **first_six_digits** (string) - First six digits of the card. - **last_four_digits** (string) - Last four digits of the card. - **payment_method** (object) - Details of the payment method. - **id** (string) - Payment method ID (e.g., "visa"). - **name** (string) - Payment method name (e.g., "Visa"). - **payment_type_id** (string) - Type of payment (e.g., "credit_card"). - **cardholder** (object) - Cardholder information. - **name** (string) - Cardholder's name. - **identification** (object) - Cardholder's identification. - **type** (string) - Identification type (e.g., "CI"). - **number** (string) - Identification number. - **issuer** (object) - Card issuer information. - **id** (number) - Issuer ID. - **name** (string) - Issuer name (e.g., "Visa"). ### Response Example ```json { "paymentMethods": [ { "id": "1234567890", "data": { "id": "1234567890", "customer_id": "123456789-abcdef", "expiration_month": 12, "expiration_year": 2028, "first_six_digits": "450995", "last_four_digits": "3704", "payment_method": { "id": "visa", "name": "Visa", "payment_type_id": "credit_card" }, "cardholder": { "name": "APRO", "identification": { "type": "CI", "number": "12345678" } }, "issuer": { "id": 1, "name": "Visa" } } } ] } ``` ``` -------------------------------- ### Mercadopago Webhook Payload Structure Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Defines the expected structure of webhook payloads received from Mercado Pago, indicating payment actions. ```typescript // Webhook payload structure from Mercado Pago interface MercadopagoWebhookPayload { action: string; // "payment.created" or "payment.updated" data: { id: string; // Mercado Pago payment ID }; } ``` -------------------------------- ### CreateMercadopagoPaymentWorkflow Input Type Source: https://context7.com/nicolasgorga/medusa-payment-mercadopago/llms.txt Defines the input structure for the createMercadopagoPaymentWorkflow, which orchestrates payment creation and card saving. ```typescript import { createMercadopagoPaymentWorkflow } from '@nicogorga/medusa-payment-mercadopago/workflows/mercadopago/workflows/create-payment' // Workflow input type interface CreatePaymentWorkflowInput { paymentSessionId: string; paymentData: { token: string; transaction_amount: number; installments: number; payment_method_id: string; payer: { email?: string; identification?: { type: string; number: string; }; } | { type: string; id: string; }; }; customerId?: string; // Medusa customer ID for card saving } // Workflow steps: // 1. get-payment-session - Fetches payment session from Medusa // 2. validateTransactionAmountStep - Ensures amounts match // 3. createPaymentStep - Creates payment in Mercado Pago // 4. get-customer - Fetches customer data if authenticated // 5. createPaymentMethodStep - Saves card (if customer exists, continues on failure) const { result } = await createMercadopagoPaymentWorkflow(scope).run({ input: { paymentSessionId: "payses_01HXYZ...", paymentData: { /* ... */ }, customerId: "cus_01HXYZ..." } }); ``` -------------------------------- ### Define a Module Link in TypeScript Source: https://github.com/nicolasgorga/medusa-payment-mercadopago/blob/master/src/links/README.md Use `defineLink` to associate data models from different modules. Ensure necessary modules are imported. ```typescript import BlogModule from "../modules/blog" import ProductModule from "@medusajs/medusa/product" import { defineLink } from "@medusajs/framework/utils" export default defineLink( ProductModule.linkable.product, BlogModule.linkable.post ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.