### Install Mercado Pago SDK for Go Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md Install the SDK using the go get command. Ensure you have Go 1.23 or higher installed. ```bash go get github.com/mercadopago/sdk-go ``` -------------------------------- ### Install Mercado Pago SDK for Go Source: https://github.com/mercadopago/sdk-go.git/blob/main/README.md Install the Mercado Pago SDK for Go using the go install command. Ensure you have Go 1.23 or higher. ```sh go install github.com/mercadopago/sdk-go ``` -------------------------------- ### Install Git Hooks with pre-commit Source: https://github.com/mercadopago/sdk-go.git/blob/main/CONTRIBUTING.md Set up the git hook scripts for the SDK project by running this command within the project folder after installing pre-commit. ```shell $ pre-commit install ``` -------------------------------- ### Webhook Integration Example Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/10-additional-apis.md Example of how to handle incoming webhooks from Mercado Pago. ```APIDOC ## Webhook Integration ### Description Handles incoming webhook POST requests with JSON payloads to process events like payment creation or updates. ### Example Handler ```go package main import ( "encoding/json" "io/ioutil" "net/http" ) type WebhookPayment struct { ID int `json:"id"` Status string `json:"status"` } func webhookHandler(w http.ResponseWriter, r *http.Request) { body, _ := ioutil.ReadAll(r.Body) var payload map[string]interface{} json.Unmarshal(body, &payload) action := payload["action"].(string) if action == "payment.created" { data := payload["data"].(map[string]interface{}) paymentID := data["id"].(float64) // Handle payment creation } w.WriteHeader(http.StatusOK) } func main() { http.HandleFunc("/webhook", webhookHandler) http.ListenAndServe(":8080", nil) } ``` ``` -------------------------------- ### Check pre-commit Installation Source: https://github.com/mercadopago/sdk-go.git/blob/main/CONTRIBUTING.md Verify if the pre-commit tool is installed by running this command in your terminal. ```shell $ pre-commit --version pre-commit 2.17.0 ``` -------------------------------- ### Pre-Approval API - Get Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Subscription and recurring payment configuration. ```Go preapproval.NewClient(cfg).Get() ``` -------------------------------- ### Manage Customer Cards with Go SDK Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/05-customer-api.md This example shows how to create a customer, add a card to that customer, and then list all cards associated with the customer using the Mercado Pago Go SDK. Ensure you have your access token configured. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/customer" "github.com/mercadopago/sdk-go/pkg/customercard" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") custClient := customer.NewClient(cfg) cardClient := customercard.NewClient(cfg) // Create customer cust := customer.Request{ Email: "john@example.com", FirstName: "John", } custResp, _ := custClient.Create(context.Background(), cust) // Add card to customer card := customercard.Request{ Token: "card_token_123", } cardResp, _ := cardClient.Create(context.Background(), custResp.ID, card) fmt.Println("Card added to customer:", cardResp.ID) // List customer's cards cards, _ := cardClient.List(context.Background(), custResp.ID) fmt.Printf("Customer has %d cards\n", len(cards)) } ``` -------------------------------- ### Create Card Token and Save to Customer Profile Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/08-cardtoken-api.md This example shows how to generate a card token and then associate it with a customer profile for future use. This requires initializing both the card token and customer card clients. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/cardtoken" "github.com/mercadopago/sdk-go/pkg/customercard" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") tokenClient := cardtoken.NewClient(cfg) cardClient := customercard.NewClient(cfg) // Step 1: Create card token tokenReq := cardtoken.Request{ CardNumber: "4111111111111111", CardholderName: "John Doe", SecurityCode: "123", ExpirationMonth: 12, ExpirationYear: 2025, } ctx := context.Background() tokenResp, _ := tokenClient.Create(ctx, tokenReq) // Step 2: Save card to customer profile cardReq := customercard.Request{ Token: tokenResp.ID, } cardResp, _ := cardClient.Create(ctx, "customer-123", cardReq) fmt.Printf("Card saved to customer: %s\n", cardResp.ID) } ``` -------------------------------- ### List Payment Methods Source: https://github.com/mercadopago/sdk-go.git/blob/main/README.md Make API requests using the SDK packages. This example shows how to list payment methods using the paymentmethod package. Ensure errors are handled appropriately. ```go client := paymentmethod.NewClient(cfg) resources, err := client.List(context.Background()) ``` -------------------------------- ### Create an Order with Mercado Pago SDK Source: https://github.com/mercadopago/sdk-go.git/blob/main/README.md Example of creating an order with payment details using the Mercado Pago SDK for Go. Replace placeholders like {{ACCESS_TOKEN}}, {{CARD_TOKEN}}, and {{PAYER_EMAIL}} with your actual values. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/order" ) func main() { accessToken := "{{ACCESS_TOKEN}}" c, err := config.New(accessToken) if err != nil { fmt.Println(err) return } client := order.NewClient(c) request := order.Request{ Type: "online", TotalAmount: "1000.00", ExternalReference: "ext_ref_1234", Currency: "BRL", Transactions: &order.TransactionRequest{ Payments: []order.PaymentRequest{ { Amount: "1000.00", PaymentMethod: &order.PaymentMethodRequest{ ID: "master", Token: "{{CARD_TOKEN}}", Type: "credit_card", Installments: 1, }, }, }, }, Payer: &order.PayerRequest{ Email: "{{PAYER_EMAIL}}", }, } resource, err := client.Create(context.Background(), request) if err != nil { fmt.Println(err) return } fmt.Println(resource) } ``` -------------------------------- ### Complete OAuth Flow Example Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/09-oauth-api.md This snippet demonstrates the full OAuth 2.0 authorization code flow, including initiating the login, handling the callback, and exchanging the authorization code for access and refresh tokens. It also shows how to make API calls using the obtained access token. ```go package main import ( "context" "fmt" "log" "net/http" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/oauth" "github.com/google/uuid" ) var ( oauthClient oauth.Client clientID = "YOUR_CLIENT_ID" clientSecret = "YOUR_CLIENT_SECRET" // Used to create initial config redirectURI = "http://localhost:8080/oauth/callback" ) func init() { cfg, _ := config.New(clientSecret) oauthClient = oauth.NewClient(cfg) } // Step 1: Start OAuth flow func handleLogin(w http.ResponseWriter, r *http.Request) { state := uuid.New().String() // Store state in session for CSRF verification authURL := oauthClient.GetAuthorizationURL(clientID, redirectURI, state) http.Redirect(w, r, authURL, http.StatusFound) } // Step 2: Handle OAuth callback func handleOAuthCallback(w http.ResponseWriter, r *http.Request) { // Verify state parameter against session code := r.URL.Query().Get("code") if code == "" { http.Error(w, "No authorization code received", http.StatusBadRequest) return } // Exchange code for tokens ctx := context.Background() resp, err := oauthClient.Create(ctx, code, redirectURI) if err != nil { log.Printf("OAuth error: %v", err) http.Error(w, "Failed to obtain tokens", http.StatusInternalServerError) return } // Store tokens securely (e.g., in session, database) // Use resp.AccessToken to make API calls on behalf of seller // Use resp.RefreshToken to refresh credentials before expiration w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{"status": "authorized", "user_id": "%s"}`, resp.UserID) } // Step 3: Refresh expired credentials (background job or before API call) func refreshSellerCredentials(ctx context.Context, refreshToken string) (string, error) { resp, err := oauthClient.Refresh(ctx, refreshToken) if err != nil { return "", err } // Store new tokens return resp.AccessToken, nil } func main() { http.HandleFunc("/oauth/login", handleLogin) http.HandleFunc("/oauth/callback", handleOAuthCallback) log.Println("Starting server on :8080") http.ListenAndServe(":8080", nil) } ``` -------------------------------- ### Refund a Payment Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md This example demonstrates how to initiate a full refund for a specific payment ID. Replace 'YOUR_ACCESS_TOKEN' with your credentials and '12345' with the actual payment ID you wish to refund. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/refund" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := refund.NewClient(cfg) // Full refund ctx := context.Background() resp, err := client.Create(ctx, 12345) // Payment ID if err != nil { fmt.Println("Error:", err) return } fmt.Println("Refund created:", resp.ID) } ``` -------------------------------- ### Chargeback API - Get Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Manage payment disputes. ```Go chargeback.NewClient(cfg).Get() ``` -------------------------------- ### Invoice API - Get Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Subscription invoice management. ```Go invoice.NewClient(cfg).Get() ``` -------------------------------- ### Handle API Errors Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md This example demonstrates how to check for and handle API-specific errors returned by the SDK. It uses `errors.As` to differentiate between Mercado Pago API errors and other potential errors. ```go package main import ( "context" "errors" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/payment" "github.com/mercadopago/sdk-go/pkg/mperror" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := payment.NewClient(cfg) ctx := context.Background() resp, err := client.Get(ctx, 99999) if err != nil { // Check if it's an API error var mpErr *mperror.ResponseError if errors.As(err, &mpErr) { fmt.Printf("API error %d: %s\n", mpErr.StatusCode, mpErr.Message) } else { fmt.Printf("Other error: %v\n", err) } return } fmt.Printf("Payment: %d\n", resp.ID) } ``` -------------------------------- ### Get Customer by ID Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Retrieve an existing customer's profile using their unique ID. Requires a context and the customer's ID. ```Go resp, err := customer.NewClient(cfg).Get(ctx, id) ``` -------------------------------- ### Get Authenticated User Info Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Fetch information about the currently authenticated user. Requires a context. ```Go user.NewClient(cfg).Get(ctx) ``` -------------------------------- ### Create Preference - E-commerce Product Checkout Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/07-preference-api.md Example of creating a preference for a typical e-commerce product checkout. This includes defining items, payer email, and redirect URLs for success, failure, and pending states. ```APIDOC ## Create Preference - E-commerce Product Checkout ### Description This example demonstrates how to create a preference for an e-commerce product checkout. It includes specifying multiple items with their details, the payer's email, and defining success, failure, and pending URLs for the checkout process. The `ExternalReference` is also set for order tracking. ### Method POST ### Endpoint /v1/checkout/preferences ### Parameters #### Request Body - **Items** ([]ItemRequest) - Required - List of items to be included in the preference. - **ID** (string) - Required - Item identifier. - **Title** (string) - Required - Item title. - **UnitPrice** (float64) - Required - Price of a single unit of the item. - **Quantity** (int) - Required - Number of units of the item. - **PayerEmail** (string) - Optional - Email address of the payer. - **BackURLs** (BackURLsRequest) - Optional - Object containing redirect URLs. - **Success** (string) - Required - URL to redirect to on successful payment. - **Failure** (string) - Required - URL to redirect to on failed payment. - **Pending** (string) - Required - URL to redirect to if payment is pending. - **ExternalReference** (string) - Optional - An external identifier for the preference. ### Request Example ```json { "items": [ { "id": "1", "title": "Blue Shirt", "unit_price": 29.99, "quantity": 2 }, { "id": "2", "title": "Red Hat", "unit_price": 14.99, "quantity": 1 } ], "payer_email": "buyer@example.com", "back_urls": { "success": "https://example.com/checkout/success", "failure": "https://example.com/checkout/failure", "pending": "https://example.com/checkout/pending" }, "external_reference": "order-67890" } ``` ### Response #### Success Response (200) - **ID** (string) - Unique identifier for the preference. - **InitPoint** (string) - URL to initiate the checkout flow. #### Response Example ```json { "id": "123456789", "init_point": "https://www.mercadopago.com.ar/checkout/v1/payment/123456789" } ``` ``` -------------------------------- ### List Identification Types Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Get a list of valid identification document types. Requires a context. ```Go identificationtype.NewClient(cfg).List(ctx) ``` -------------------------------- ### Get Authorization URL Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/09-oauth-api.md Constructs the authorization URL to redirect sellers for OAuth authorization. Requires client ID, redirect URI, and a state parameter for security. ```go authURL := client.GetAuthorizationURL(clientID, redirectURI, state) // Redirect seller to authURL ``` -------------------------------- ### Search Payments by Date Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md This snippet shows how to search for payments within a specified date range. It configures the search request with start and end dates, limit, and offset, then prints the total number of payments found and details of each payment. ```go package main import ( "context" "fmt" "time" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/payment" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := payment.NewClient(cfg) req := payment.SearchRequest{ Range: "date_created", Begin: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), End: time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC).Unix(), Limit: 50, Offset: 0, } ctx := context.Background() resp, err := client.Search(ctx, req) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Found %d payments\n", resp.Paging.Total) for _, p := range resp.Results { fmt.Printf(" %d: %s (%.2f)\n", p.ID, p.Status, p.TransactionAmount) } } ``` -------------------------------- ### Configure SDK with Environment Variable Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md Illustrates how to retrieve the access token from an environment variable and use it to create a configuration for the SDK. ```go package main import ( "os" "github.com/mercadopago/sdk-go/pkg/config" ) func main() { token := os.Getenv("MERCADOPAGO_ACCESS_TOKEN") cfg, _ := config.New(token) // Use cfg } ``` -------------------------------- ### Configure SDK with Options Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Initialize the SDK configuration with a token and optional settings like CorporationID, IntegratorID, and PlatformID. This allows for customized API interactions. ```Go cfg, err := config.New("TOKEN", config.WithCorporationID("corp-id"), config.WithIntegratorID("int-id"), config.WithPlatformID("plat-id"), ) ``` -------------------------------- ### Initialize SDK Configuration Source: https://github.com/mercadopago/sdk-go.git/blob/main/README.md Initialize the SDK with your access token before making API requests. This sets up the configuration for subsequent operations. ```go accessToken := "{{ACCESS_TOKEN}}" cfg, err := config.New(accessToken) ``` -------------------------------- ### Get Customer Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/05-customer-api.md Retrieves the full profile of a customer identified by the given ID, including personal information, saved cards, and registered addresses. This method corresponds to the `Get` function in the customer client. ```APIDOC ## Get Customer ### Description Retrieves the full profile of a customer identified by the given ID, including personal information, saved cards, and registered addresses. ### Method GET ### Endpoint https://api.mercadopago.com/v1/customers/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Unique customer identifier ### Response #### Success Response (200) - **id** (string) - The unique identifier for the customer. - **email** (string) - The customer's email address. - **first_name** (string) - The customer's first name. - **last_name** (string) - The customer's last name. - **cards** (array) - A list of saved cards associated with the customer. #### Response Example ```json { "id": "customer-123", "email": "john@example.com", "first_name": "John", "last_name": "Doe", "cards": [] } ``` ``` -------------------------------- ### Get Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/03-order-api.md Retrieves an existing order by its unique identifier. ```APIDOC ## Get ### Description Retrieves an existing order by its unique identifier. ### Method GET ### Endpoint https://api.mercadopago.com/v1/orders/{orderID} ### Parameters #### Path Parameters - **orderID** (string) - Yes - Unique order identifier #### Query Parameters - None #### Request Body - **ctx** (context.Context) - Yes - Context for request cancellation and timeout ### Response #### Success Response (200) - `(*Response, error)` — The order object with current state. #### Response Example ```go ctx := context.Background() resp, err := client.Get(ctx, "order-123") if err != nil { fmt.Println("Error retrieving order:", err) return } fmt.Printf("Order status: %s, Total: %s\n", resp.Status, resp.TotalAmount) ``` ### Error Handling - `*mperror.ResponseError` on API failure (e.g., 404 if order not found). ``` -------------------------------- ### Get User Info Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Retrieves information about the currently authenticated user. ```APIDOC ## GET /users/me ### Description Retrieves information about the currently authenticated user. ### Method GET ### Endpoint /users/me ### Response #### Success Response (200) - **(object)** - User information. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Create Card Token and One-Time Payment Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/08-cardtoken-api.md This snippet demonstrates how to first create a card token and then use that token to create a one-time payment. Ensure you have the necessary configuration and clients initialized. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/cardtoken" "github.com/mercadopago/sdk-go/pkg/payment" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") tokenClient := cardtoken.NewClient(cfg) paymentClient := payment.NewClient(cfg) // Step 1: Create card token tokenReq := cardtoken.Request{ CardNumber: "4111111111111111", CardholderName: "John Doe", SecurityCode: "123", ExpirationMonth: 12, ExpirationYear: 2025, } ctx := context.Background() tokenResp, _ := tokenClient.Create(ctx, tokenReq) // Step 2: Create payment using the token paymentReq := payment.Request{ TransactionAmount: 100.00, Token: tokenResp.ID, Description: "Purchase of product", PaymentMethodID: tokenResp.PaymentMethod.ID, Payer: &payment.PayerRequest{ Email: "buyer@example.com", }, } paymentResp, _ := paymentClient.Create(ctx, paymentReq) fmt.Printf("Payment created: %d (%s)\n", paymentResp.ID, paymentResp.Status) } ``` -------------------------------- ### Get Customer Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Retrieves details for a specific customer using their ID. ```APIDOC ## GET /v1/customers/{id} ### Description Retrieves details for a specific customer. ### Method GET ### Endpoint /v1/customers/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the customer. ### Response #### Success Response (200) - **(object)** - Details of the requested customer. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Get Order Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Retrieves details for a specific order using its ID. ```APIDOC ## GET /v1/orders/{id} ### Description Retrieves details for a specific order. ### Method GET ### Endpoint /v1/orders/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the order. ### Response #### Success Response (200) - **(object)** - Details of the requested order. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Customer Card API - Get Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Manage customer saved cards. ```Go customercard.NewClient(cfg).Get() ``` -------------------------------- ### Create a New Config Object Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/01-configuration.md Initializes a new Config object with an access token and optional settings. Use this to set up the SDK for API interactions. ```go package main import ( "github.com/mercadopago/sdk-go/pkg/config" ) func main() { cfg, err := config.New("YOUR_ACCESS_TOKEN") if err != nil { panic(err) } // Use cfg with client constructors } ``` -------------------------------- ### Configure Sandbox Access Token Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md To test your integration without using real money, configure the SDK with a sandbox access token. This allows you to simulate payment flows in a safe environment. ```go cfg, _ := config.New("SANDBOX_ACCESS_TOKEN") ``` -------------------------------- ### Advanced Payment API - Get Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Marketplace split payments and disbursements. ```Go advancedpayment.NewClient(cfg).Get() ``` -------------------------------- ### Merchant Order API - Get Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Group payments and items into commercial transactions. ```Go merchantorder.NewClient(cfg).Get() ``` -------------------------------- ### Optional SDK Configuration Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md Configure the SDK with additional parameters like Corporation ID, Integrator ID, and Platform ID. ```go cfg, _ := config.New("YOUR_ACCESS_TOKEN", config.WithCorporationID("corp-123"), config.WithIntegratorID("integrator-456"), config.WithPlatformID("platform-789"), ) ``` -------------------------------- ### Create a Payment Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md Use the payment client to create a new payment. Requires transaction amount, description, payment method, token, and payer information. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/payment" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := payment.NewClient(cfg) // Create a payment req := payment.Request{ TransactionAmount: 100.00, Description: "Test payment", PaymentMethodID: "visa", Token: "card_token_123", Payer: &payment.PayerRequest{ Email: "buyer@example.com", }, } ctx := context.Background() resp, err := client.Create(ctx, req) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Payment %d: %s\n", resp.ID, resp.Status) } ``` -------------------------------- ### Get User Info Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/10-additional-apis.md Retrieves the account information of the authenticated MercadoPago user. ```APIDOC ## GET /users/me ### Description Retrieves the account information of the authenticated MercadoPago user. ### Method GET ### Endpoint https://api.mercadopago.com/users/me ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **ID** (string) - MercadoPago user ID - **Email** (string) - User's email address - **FirstName** (string) - User's first name - **LastName** (string) - User's last name - **CountryID** (string) - Country code (e.g., "BR", "AR", "MX") - **SiteID** (string) - Site identifier (e.g., "MLB" for Brazil, "MLA" for Argentina) - **CreatedDate** (string) - Account creation timestamp - **Nickname** (string) - User's nickname or username - **PhoneNumber** (string) - User's phone number - **Description** (string) - User's description or bio - **AccountStatus** (string) - Account status (e.g., "active", "suspended") #### Response Example { "example": "{\"id\":\"12345678\", \"email\":\"test@example.com\", \"first_name\":\"Test\", \"last_name\":\"User\", \"country_id\":\"BR\", \"site_id\":\"MLB\", \"created_date\":\"2023-01-01T10:00:00.000Z\", \"nickname\":\"testuser\", \"phone_number\":\"+5511987654321\", \"description\":\"A test user account\", \"account_status\":\"active\"}" } ``` -------------------------------- ### Pre-Approval API - Create Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Subscription and recurring payment configuration. ```Go preapproval.NewClient(cfg).Create() ``` -------------------------------- ### Point API - Get Payment Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Operations for Mercado Pago Point in-person payment devices. ```Go point.NewClient(cfg).GetPayment() ``` -------------------------------- ### Create an Order Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md Create a new order with payment details, payer information, and an external reference. This is useful for complex transactions. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/order" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := order.NewClient(cfg) req := order.Request{ Type: "online", TotalAmount: "1000.00", ExternalReference: "order-123", Currency: "BRL", Transactions: &order.TransactionRequest{ Payments: []order.PaymentRequest{ { Amount: "1000.00", PaymentMethod: &order.PaymentMethodRequest{ ID: "master", Token: "card_token_123", Type: "credit_card", }, }, }, }, Payer: &order.PayerRequest{ Email: "buyer@example.com", }, } ctx := context.Background() resp, err := client.Create(ctx, req) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Order created:", resp.ID) } ``` -------------------------------- ### Create Customer Client Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/05-customer-api.md Initializes a new client for the Customer API using your access token and configuration. This client is used for all subsequent customer-related operations. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/customer" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := customer.NewClient(cfg) // Use client to create, retrieve, update, or search customers } ``` -------------------------------- ### Payment Method Request Structure Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/11-types.md Identifies how a payer intends to pay, including ID, type, and installments. ```go type PaymentMethodRequest struct { ID string Type string Token string StatementDescriptor string Installments int FinancialInstitution string } ``` -------------------------------- ### Go PaymentMethodDetailsResponse Structure Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/04-payment-api.md Details about the payment method used in a transaction, including its ID, type, and installment cost. ```go type PaymentMethodDetailsResponse struct { ID string Type string InstallmentCost float64 } ``` -------------------------------- ### Create a Customer Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/12-quick-start.md Create a new customer profile with basic contact information. This allows for managing customer data and payment methods. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/customer" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := customer.NewClient(cfg) req := customer.Request{ Email: "john@example.com", FirstName: "John", LastName: "Doe", Phone: &customer.PhoneRequest{ AreaCode: "11", Number: "987654321", }, } ctx := context.Background() resp, err := client.Create(ctx, req) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Customer created:", resp.ID) } ``` -------------------------------- ### Configure Search Request with Filters Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Set up a search request with pagination parameters (Limit, Offset) and custom filters. Useful for querying resources like payments. ```Go search := paymentpackage.SearchRequest{ Limit: 50, Offset: 100, Filters: map[string]string{ "status": "approved", }, } ``` -------------------------------- ### Payment Method Configuration Request Structure Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/11-types.md Specifies payment method restrictions, defaults, and installment limits for an order. ```go type PaymentMethodConfigRequest struct { NotAllowedIDs []string NotAllowedTypes []string DefaultID string MaxInstallments int DefaultInstallments int } ``` -------------------------------- ### Get Payment Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/04-payment-api.md Retrieves a single payment by its unique numeric ID. Useful for checking the status of a specific transaction. ```APIDOC ## Get Payment ### Description Retrieves a single payment by its unique numeric ID. ### Method `GET` ### Endpoint `https://api.mercadopago.com/v1/payments/{id}` ### Parameters #### Path Parameters * **id** (int) - Required - Unique payment identifier. #### Query Parameters * None #### Request Body * None ### Response #### Success Response (200) * **ID** (int) - The unique identifier of the payment. * **Status** (string) - The current status of the payment. * **TransactionAmount** (float64) - The amount of the transaction. #### Response Example ```json { "id": 12345, "status": "approved", "transaction_amount": 100.00 } ``` ``` -------------------------------- ### Create OAuth Client Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/09-oauth-api.md Initializes a new OAuth API client using a configuration object. Ensure your config.Config includes the necessary access token and HTTP settings. ```go package main import ( "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/oauth" ) func main() { cfg, _ := config.New("YOUR_APPLICATION_ACCESS_TOKEN") client := oauth.NewClient(cfg) // Use client to manage OAuth flows } ``` -------------------------------- ### Get Refund Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/06-refund-api.md Retrieves a specific refund by its payment ID and refund ID. This operation allows you to fetch details of an existing refund. ```APIDOC ## GET /v1/payments/{id}/refunds/{refund_id} ### Description Retrieves a specific refund by its payment ID and refund ID. ### Method GET ### Endpoint `https://api.mercadopago.com/v1/payments/{id}/refunds/{refund_id}` ### Parameters #### Path Parameters - **id** (int) - Required - Unique payment identifier - **refund_id** (int) - Required - Unique refund identifier #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **ID** (int64) - Unique refund identifier assigned by the API - **PaymentID** (int64) - Associated payment identifier - **Amount** (float64) - Refund amount - **Metadata** (map[string]interface{}) - Custom metadata associated with the refund - **Source** (SourceResponse) - Source of the refund (API, MERCHANT, ADMIN, etc.) - **Reason** (string) - Reason for the refund - **Status** (string) - Refund status (e.g., "approved", "pending", "rejected") - **CreatedDate** (string) - Creation timestamp - **UpdatedDate** (string) - Last update timestamp - **Labels** ([]string) - Refund labels - **ReleaseDate** (string) - Release date for the refund funds - **ReceivingDate** (string) - Date when payer receives refund #### Response Example ```json { "ID": 123456, "PaymentID": 12345, "Amount": 50.00, "Metadata": {}, "Source": { "ID": "12345", "Type": "API" }, "Reason": "Item not received", "Status": "approved", "CreatedDate": "2023-10-27T10:00:00.000Z", "UpdatedDate": "2023-10-27T10:05:00.000Z", "Labels": [], "ReleaseDate": "2023-10-27T10:05:00.000Z", "ReceivingDate": "2023-10-27T10:10:00.000Z" } ``` ### Error Handling - `*mperror.ResponseError` on API failure (e.g., 404 if refund not found). ``` -------------------------------- ### Create Preference Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/07-preference-api.md Creates a new checkout preference with product and payment details. Returns a Response object containing the `init_point` URL for redirecting buyers to the MercadoPago checkout flow. ```APIDOC ## POST /checkout/preferences ### Description Creates a new checkout preference with information about a product or service and returns a `Response` containing the URL needed to start the payment flow. ### Method POST ### Endpoint https://api.mercadopago.com/checkout/preferences ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **request** (Request) - Required - Preference details including items, payer, and payment configuration ### Request Example ```json { "items": [ { "id": "1001", "title": "Laptop", "description": "High-performance laptop", "picture_url": "https://example.com/laptop.jpg", "category_id": "electronics", "quantity": 1, "unit_price": 1500.00 } ], "payer_email": "buyer@example.com", "back_urls": { "success": "https://example.com/success", "failure": "https://example.com/failure", "pending": "https://example.com/pending" }, "auto_return": "approved", "external_reference": "order-12345" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the preference. - **init_point** (string) - The URL to redirect the buyer to complete the checkout. - **items** (array) - List of items included in the preference. - **payer_email** (string) - The email of the payer. - **back_urls** (object) - URLs for success, failure, and pending payment. - **auto_return** (string) - Type of auto-return after payment. - **external_reference** (string) - An external reference ID for the preference. #### Response Example ```json { "id": "123456789", "init_point": "https://www.mercadopago.com/checkout/pay?pref_id=123456789", "items": [ { "id": "1001", "title": "Laptop", "description": "High-performance laptop", "picture_url": "https://example.com/laptop.jpg", "category_id": "electronics", "quantity": 1, "unit_price": 1500.00 } ], "payer_email": "buyer@example.com", "back_urls": { "success": "https://example.com/success", "failure": "https://example.com/failure", "pending": "https://example.com/pending" }, "auto_return": "approved", "external_reference": "order-12345" } ``` ``` -------------------------------- ### Create a Checkout Preference Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/07-preference-api.md Creates a new checkout preference with item, payer, and payment configurations. The response includes the `init_point` URL for redirecting buyers to the checkout flow. Handle potential API errors by checking the returned error. ```go pref := preference.Request{ Items: []preference.ItemRequest{ { ID: "1001", Title: "Laptop", Description: "High-performance laptop", PictureURL: "https://example.com/laptop.jpg", CategoryID: "electronics", Quantity: 1, UnitPrice: 1500.00, }, }, PayerEmail: "buyer@example.com", BackURLs: &preference.BackURLsRequest{ Success: "https://example.com/success", Failure: "https://example.com/failure", Pending: "https://example.com/pending", }, AutoReturn: "approved", ExternalReference: "order-12345", } ctx := context.Background() resp, err := client.Create(ctx, pref) if err != nil { fmt.Println("Error creating preference:", err) return } fmt.Println("Checkout URL:", resp.InitPoint) ``` -------------------------------- ### Get Customer Card Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/05-customer-api.md Retrieves the details of a specific card associated with a customer. Requires both the customer's ID and the card's ID. ```APIDOC ## Get Customer Card ### Description Retrieves the details of a specific card associated with a customer. ### Method GET (Assumed based on 'Get' operation and typical RESTful patterns for retrieving resources) ### Endpoint `/v1/customers/{customer_id}/cards/{card_id}` (Assumed based on common RESTful patterns) ### Parameters #### Path Parameters - **customer_id** (string) - Required - The ID of the customer. - **card_id** (string) - Required - The ID of the card to retrieve. ### Response #### Success Response (200) - **ID** (string) - The unique identifier of the card. - **type** (string) - The type of the card (e.g., 'credit', 'debit'). - **last_four_digits** (string) - The last four digits of the card number. - **expiration_month** (integer) - The expiration month of the card. - **expiration_year** (integer) - The expiration year of the card. #### Response Example ```json { "ID": "existing_card_id", "type": "credit", "last_four_digits": "1111", "expiration_month": 12, "expiration_year": 2025 } ``` ``` -------------------------------- ### Get Preference Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/07-preference-api.md Retrieves an existing checkout preference by its unique identifier. Returns the preference object, including details about items, payer, and payment status. ```APIDOC ## GET /checkout/preferences/{id} ### Description Retrieves an existing checkout preference by its unique identifier. ### Method GET ### Endpoint https://api.mercadopago.com/checkout/preferences/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Unique preference identifier #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **id** (string) - The unique identifier for the preference. - **init_point** (string) - The URL to redirect the buyer to complete the checkout. - **items** (array) - List of items included in the preference. - **payer_email** (string) - The email of the payer. - **back_urls** (object) - URLs for success, failure, and pending payment. - **auto_return** (string) - Type of auto-return after payment. - **external_reference** (string) - An external reference ID for the preference. #### Response Example ```json { "id": "123456789", "init_point": "https://www.mercadopago.com/checkout/pay?pref_id=123456789", "items": [ { "id": "1001", "title": "Laptop", "description": "High-performance laptop", "picture_url": "https://example.com/laptop.jpg", "category_id": "electronics", "quantity": 1, "unit_price": 1500.00 } ], "payer_email": "buyer@example.com", "back_urls": { "success": "https://example.com/success", "failure": "https://example.com/failure", "pending": "https://example.com/pending" }, "auto_return": "approved", "external_reference": "order-12345" } ``` ``` -------------------------------- ### Create Checkout Preference Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Generate a checkout session for buyers to complete their purchase. Requires a context and preference data. ```Go resp, err := preference.NewClient(cfg).Create(ctx, request) ``` -------------------------------- ### List Payment Methods Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/10-additional-apis.md Retrieves all available payment methods for the authenticated account. Requires context and the paymentmethod client. ```go package main import ( "context" "fmt" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/paymentmethod" ) func main() { cfg, _ := config.New("YOUR_ACCESS_TOKEN") client := paymentmethod.NewClient(cfg) ctx := context.Background() methods, err := client.List(ctx) if err != nil { fmt.Println("Error listing payment methods:", err) return } for _, method := range methods { fmt.Printf("Payment Method: %s (%s)\n", method.Name, method.ID) fmt.Printf(" Type: %s\n", method.Type) fmt.Printf(" Min Amount: %.2f\n", method.MinAmount) fmt.Printf(" Max Amount: %.2f\n", method.MaxAmount) } } ``` -------------------------------- ### Pre-Approval API - Pause Source: https://github.com/mercadopago/sdk-go.git/blob/main/_autodocs/00-index.md Subscription and recurring payment configuration. ```Go preapproval.NewClient(cfg).Pause() ```