### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/preapproval.md Demonstrates creating, getting, updating, and searching for preapprovals using the SDK. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Create an ad-hoc subscription without a predefined plan preapproval_result = sdk.preapproval().create({ "reason": "Custom Service Subscription", "auto_recurring": { "frequency": 1, "frequency_type": "weeks", "transaction_amount": 50.00, "currency_id": "USD" }, "payer_email": "subscriber@example.com", "back_url": "https://example.com/subscription", "notification_url": "https://example.com/webhooks/preapproval", "external_id": "CUSTOM-SUB-001" }) if preapproval_result["status"] == 201: preapproval = preapproval_result["response"] preapproval_id = preapproval["id"] print(f"Preapproval created: {preapproval_id}") # Get the preapproval get_result = sdk.preapproval().get(preapproval_id) if get_result["status"] == 200: preapp = get_result["response"] print(f"Status: {preapp['status']}") # Update the preapproval update_result = sdk.preapproval().update(preapproval_id, { "status": "paused" }) # Search for preapprovals search_result = sdk.preapproval().search({ "status": "active" }) if search_result["status"] == 200: preapprovals = search_result["response"] print(f"Found {len(preapprovals)} active preapprovals") ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/customer.md Full example demonstrating SDK usage for customer operations. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") ``` -------------------------------- ### Full Example: Plan Management Workflow Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/plan.md A comprehensive example showcasing the workflow of creating, getting, updating, and searching for plans using the Plan class. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Create a subscription plan plan_result = sdk.plan().create({ "reason": "Yearly Premium Plan", "auto_recurring": { "frequency": 12, "frequency_type": "months", "transaction_amount": 1200.00, "currency_id": "USD" }, "back_url": "https://example.com/subscription", "notification_url": "https://example.com/webhooks" }) if plan_result["status"] == 201: plan = plan_result["response"] plan_id = plan["id"] print(f"Plan created: {plan_id}") # Get the plan get_result = sdk.plan().get(plan_id) if get_result["status"] == 200: plan = get_result["response"] print(f"Plan: {plan['reason']}") print(f"Amount: {plan['auto_recurring']['transaction_amount']}") # Update the plan update_result = sdk.plan().update(plan_id, { "auto_recurring": { "transaction_amount": 1400.00 } }) # Search for plans search_result = sdk.plan().search() if search_result["status"] == 200: plans = search_result["response"] print(f"Found {len(plans)} plans") ``` -------------------------------- ### create() example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/preference.md Example of creating a checkout preference with items, payer information, and redirect URLs. ```python result = sdk.preference().create({ "items": [ { "title": "Laptop", "quantity": 1, "unit_price": 999.99, "description": "High-performance laptop", "picture_url": "https://example.com/laptop.jpg" } ], "payer": { "name": "John Doe", "email": "john@example.com", "phone": { "number": "5511999999999" } }, "back_urls": { "success": "https://example.com/success", "failure": "https://example.com/failure", "pending": "https://example.com/pending" }, "auto_return": "approved", "external_reference": "ORDER-123", "notification_url": "https://example.com/webhooks/checkout" }) if result["status"] == 201: preference = result["response"] checkout_url = preference["init_point"] print(f"Redirect buyer to: {checkout_url}") ``` -------------------------------- ### Full SDK Initialization Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/sdk.md A comprehensive example demonstrating SDK initialization and import statements. ```python import mercadopago from mercadopago.config import RequestOptions # Initialize SDK sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/payment-methods.md A comprehensive example demonstrating how to initialize the SDK, retrieve all payment methods, display active ones, and organize them by type. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Get all available payment methods result = sdk.payment_methods().list_all() if result["status"] == 200: payment_methods = result["response"] # Display available payment methods print("Available payment methods:") for method in payment_methods: if method["status"] == "active": print(f" - {method['id']}: {method['name']}") print(f" Type: {method['type']}") if "thumbnail" in method: print(f" Logo: {method['thumbnail']}") # Organize by type for UI grouping grouped = {} for method in payment_methods: method_type = method.get("type", "other") if method_type not in grouped: grouped[method_type] = [] grouped[method_type].append(method) print("\nPayment Methods by Type:") for method_type, methods in grouped.items(): print(f"\n{method_type.upper()}:") for m in methods: print(f" - {m['name']} ({m['id']})") ``` -------------------------------- ### Create Plan Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/plan.md Example demonstrating how to create a new subscription plan using the Plan class. ```python result = sdk.plan().create({ "reason": "Monthly Premium Subscription", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 99.99, "currency_id": "BRL", "free_trial_frequency": 0 }, "back_url": "https://example.com/plan_signup", "billing_day": 15, "notification_url": "https://example.com/webhooks/plan" }) if result["status"] == 201: plan = result["response"] plan_id = plan["id"] print(f"Plan created: {plan_id}") ``` -------------------------------- ### Full Example: Getting and using identification types Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/identification-type.md A comprehensive example showing how to initialize the SDK, retrieve all identification types, display them, create a mapping, and use a type in customer creation. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Get all identification types result = sdk.identification_type().list_all() if result["status"] == 200: identification_types = result["response"] # Display available types for a form print("Available identification types:") for id_type in identification_types: print(f" - {id_type['id']}: {id_type['name']}") print(f" Length: {id_type['min_length']} to {id_type['max_length']} characters") # Create a mapping for form UI type_mapping = {itype['id']: itype['name'] for itype in identification_types} # Use in customer creation customer_result = sdk.customer().create({ "email": "user@example.com", "first_name": "John", "identification": { "type": "CPF", # Valid from identification_types "number": "12345678901" } }) ``` -------------------------------- ### Full Configuration Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/configuration.md A comprehensive example showing how to load and validate the access token, create an SDK instance with custom defaults for connection timeout, retries, custom headers, and integrator ID, and how to override options for specific calls like idempotency. ```python import mercadopago from mercadopago.config import RequestOptions import os from dotenv import load_dotenv load_dotenv() # Load and validate configuration access_token = os.getenv("MERCADOPAGO_ACCESS_TOKEN") if not access_token: raise ValueError("MERCADOPAGO_ACCESS_TOKEN environment variable not set") # Create SDK with custom defaults sdk = mercadopago.SDK( access_token=access_token, request_options=RequestOptions( connection_timeout=30.0, max_retries=5, custom_headers={ "X-Custom-App": "my-app" }, integrator_id="my-platform" ) ) # Override for sensitive calls (e.g., compliance-required idempotency) compliance_opts = RequestOptions( custom_headers={ "x-idempotency-key": "generated-uuid-here" } ) # Use SDK payment = sdk.payment().create(payment_data) refund = sdk.refund().create(payment_id, request_options=compliance_opts) ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/request-options.md A comprehensive example showing the initialization of the SDK and the creation of a payment using default RequestOptions. ```python from mercadopago.config import RequestOptions import mercadopago # Create SDK with default options sdk = mercadopago.SDK("DEFAULT_TOKEN") # Create a payment with default options payment = sdk.payment().create({ "transaction_amount": 100, "payment_method_id": "visa", "token": "CARD_TOKEN", "payer": {"email": "user@example.com"} }) ``` -------------------------------- ### get() Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/customer.md Retrieves a customer by their ID. ```python result = sdk.customer().get("CUST-123") if result["status"] == 200: customer = result["response"] print(customer["email"]) ``` -------------------------------- ### Example Usage of list_all() Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/payment-methods.md Example of how to call the list_all method and process the results. ```python result = sdk.payment_methods().list_all() if result["status"] == 200: methods = result["response"] for method in methods: print(f"{method['id']}: {method['name']} ({method['type']})") ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/preference.md Initializes the Mercado Pago SDK with an access token. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") ``` -------------------------------- ### SDK Initialization Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/sdk.md Example of how to initialize the SDK with an access token and optionally override default request options. ```python import mercadopago # Initialize with access token sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Override default request options from mercadopago.config import RequestOptions opts = RequestOptions(connection_timeout=30.0, max_retries=5) sdk_with_options = mercadopago.SDK( "YOUR_ACCESS_TOKEN", request_options=opts ) ``` -------------------------------- ### Full Subscription Management Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/subscription.md A comprehensive example demonstrating the creation, retrieval, pausing, resuming, and searching of subscriptions using the SDK. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Assuming a plan exists with ID "PLAN-MONTHLY" # and a card token was created # Create a subscription sub_result = sdk.subscription().create({ "preapproval_plan_id": "PLAN-MONTHLY", "payer_email": "user@example.com", "card_token_id": "CARD_TOKEN_XYZ", "reason": "Monthly subscription" }) if sub_result["status"] == 201: subscription = sub_result["response"] sub_id = subscription["id"] print(f"Subscription created: {sub_id}") # Retrieve the subscription get_result = sdk.subscription().get(sub_id) if get_result["status"] == 200: sub = get_result["response"] print(f"Status: {sub['status']}") # Pause the subscription pause_result = sdk.subscription().update(sub_id, { "status": "paused" }) if pause_result["status"] == 200: print("Subscription paused") # Resume the subscription resume_result = sdk.subscription().update(sub_id, { "status": "active" }) # Search for subscriptions search_result = sdk.subscription().search({ "status": "active" }) if search_result["status"] == 200: active_subs = search_result["response"] print(f"Found {len(active_subs)} active subscriptions") ``` -------------------------------- ### Subscription Create Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/subscription.md Example of creating a subscription using the create method. ```python result = sdk.subscription().create({ "preapproval_plan_id": "PLAN-123", "payer_email": "subscriber@example.com", "card_token_id": "CARD_TOKEN_ABC" }) ``` -------------------------------- ### create() Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/customer.md Creates a new customer record. ```python result = sdk.customer().create({ "email": "newcustomer@example.com", "first_name": "John", "last_name": "Smith", "identification": { "type": "CPF", "number": "12345678901" }, "phone": { "country_code": "55", "area_code": "11", "number": "912345678" }, "address": { "street_name": "Av. Paulista", "street_number": 1000, "zip_code": "01311-100", "city_name": "São Paulo", "state_name": "SP" } }) ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/user.md A comprehensive example demonstrating how to retrieve and display authenticated user information. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Get authenticated user information result = sdk.user().get() if result["status"] == 200: user = result["response"] print("User Information") print("=" * 40) print(f"ID: {user['id']}") print(f"Email: {user['email']}") print(f"Name: {user['first_name']} {user['last_name']}") print(f"Country: {user['country_id']}") print(f"Site: {user['site_id']}") print(f"Account Status: {user['status']}") print(f"Member since: {user['created_at']}") print(f"Email verified: {user['verified_email']}") # Use this information to verify credentials or display profile if user["status"] == "active": print("\n✓ Account is active and ready to process payments") else: print("\n⚠ Account status issue detected") else: error = result["response"] print(f"Error retrieving user: {error}") ``` -------------------------------- ### Full Payment Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/payment.md A comprehensive example demonstrating payment creation, retrieval, and search using the Mercado Pago SDK. ```python import mercadopago # Initialize SDK sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Create a payment payment_result = sdk.payment().create({ "transaction_amount": 99.99, "token": "9c6f8e3e-8e3e-4e3e-8e3e-8e3e8e3e8e3e", "description": "Widget sale", "payment_method_id": "visa", "installments": 3, "payer": { "email": "customer@example.com", "first_name": "Jane", "last_name": "Doe" }, "external_reference": "SALE-2024-001" }) if payment_result["status"] == 201: payment = payment_result["response"] payment_id = payment["id"] print(f"Payment created: {payment_id}") # Retrieve the payment later fetch_result = sdk.payment().get(payment_id) if fetch_result["status"] == 200: latest_payment = fetch_result["response"] print(f"Status: {latest_payment['status']}") # Search for payments search_result = sdk.payment().search({ "external_reference": "SALE-2024-001" }) if search_result["status"] == 200: matching = search_result["response"] print(f"Found {len(matching)} payments") else: print(f"Error creating payment: {payment_result['response']}") ``` -------------------------------- ### Update Payment Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/payment.md An example of how to update an existing payment using the SDK. ```python result = sdk.payment().update(12345, { "status": "cancelled" } ) if result["status"] == 200: payment = result["response"] print(f"Payment status: {payment['status']}") ``` -------------------------------- ### Order Creation Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/order.md Example of creating an order with basic details like external reference, items, and payer information. ```python result = sdk.order().create({ "external_reference": "ORDER123", "items": [ { "title": "Product A", "quantity": 1, "unit_price": 50.0 } ], "payer": { "email": "buyer@example.com" } }) ``` -------------------------------- ### Full Order Management Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/order.md A comprehensive example demonstrating the creation of an order, adding a transaction, and processing the order using the Python SDK. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Create an order create_result = sdk.order().create({ "external_reference": "ORD-001", "items": [ { "title": "Laptop", "quantity": 1, "unit_price": 999.99 } ], "payer": { "email": "customer@example.com" } }) if create_result["status"] == 201: order = create_result["response"] order_id = order["id"] print(f"Created order: {order_id}") # Add a transaction to the order txn_result = sdk.order().create_transaction(order_id, { "amount": 999.99, "payment_method_id": "visa", "token": "CARD_TOKEN_123" }) # Process the order process_result = sdk.order().process(order_id) if process_result["status"] == 200: print("Order processed successfully") ``` -------------------------------- ### Subscription Update Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/subscription.md Example of updating a subscription to pause it. ```python result = sdk.subscription().update("SUB-123", { "status": "paused" }) ``` -------------------------------- ### RequestOptions Usage Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/request-options.md Example demonstrating how to create and override RequestOptions instances, and how to use them in a resource call. ```python from mercadopago.config import RequestOptions # Create with defaults opts = RequestOptions() # Override specific options opts = RequestOptions( access_token="OVERRIDE_TOKEN", connection_timeout=30.0, max_retries=5, custom_headers={"x-idempotency-key": "unique-id-123"} ) # Use as override in resource call result = sdk.payment().create(payment_data, request_options=opts) ``` -------------------------------- ### Full Refund Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/refund.md A comprehensive example demonstrating the creation of a payment, followed by a full refund, a partial refund, and listing all refunds for that payment. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Create a payment first payment_result = sdk.payment().create({ "transaction_amount": 100.0, "payment_method_id": "visa", "token": "CARD_TOKEN_123", "payer": {"email": "user@example.com"} }) if payment_result["status"] == 201: payment = payment_result["response"] payment_id = payment["id"] print(f"Payment created: {payment_id}") # Full refund refund_full = sdk.refund().create(payment_id) if refund_full["status"] == 200: print(f"Full refund created: {refund_full['response']['id']}") # Partial refund (alternative scenario) refund_partial = sdk.refund().create(payment_id, { "amount": 25.0 }) if refund_partial["status"] == 200: print(f"Partial refund of $25 created") # List all refunds for the payment list_result = sdk.refund().list_all(payment_id) if list_result["status"] == 200: refunds = list_result["response"] print(f"Payment has {len(refunds)} refunds") total_refunded = sum(r["amount"] for r in refunds) print(f"Total refunded: ${total_refunded}") ``` -------------------------------- ### update() Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/customer.md Updates an existing customer. ```python result = sdk.customer().update("CUST-123", { "email": "newemail@example.com", "default_source": "CARD-ID-456" }) ``` -------------------------------- ### search() Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/customer.md Searches customers matching the given filters. ```python result = sdk.customer().search({ "email": "customer@example.com" }) ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/advanced-payment.md Example demonstrating the creation, retrieval, update, capture, and cancellation of an advanced payment using the Mercado Pago Python SDK. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Create a marketplace split payment split_result = sdk.advanced_payment().create({ "disbursements": [ { "collector_id": "SELLER1_ID", "amount": 600.00, "external_reference": "SPLIT-SELLER1" }, { "collector_id": "SELLER2_ID", "amount": 400.00, "external_reference": "SPLIT-SELLER2" } ], "payer": { "email": "buyer@example.com" }, "description": "Marketplace order split", "external_reference": "MARKETPLACE-ORD-789" }) if split_result["status"] == 201: payment = split_result["response"] payment_id = payment["id"] print(f"Advanced payment created: {payment_id}") # Get the payment get_result = sdk.advanced_payment().get(payment_id) if get_result["status"] == 200: adv_payment = get_result["response"] print(f"Status: {adv_payment['status']}") # Update the payment update_result = sdk.advanced_payment().update(payment_id, { "description": "Updated description" }) # Capture the payment capture_result = sdk.advanced_payment().capture(payment_id) # Cancel the payment cancel_result = sdk.advanced_payment().cancel(payment_id) ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/disbursement-refund.md Demonstrates how to use the DisbursementRefund class to refund disbursements. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Assuming an advanced payment with ID "ADV-PAY-123" exists # with disbursements to sellers # Refund all disbursements at once refund_all_result = sdk.disbursement_refund().create_all("ADV-PAY-123", { "reason": "Customer requested full refund" }) if refund_all_result["status"] == 201: print("All disbursements refunded") # Refund a specific disbursement by amount refund_single_result = sdk.disbursement_refund().create( "ADV-PAY-123", "DISBURSEMENT-001", 150.50 ) if refund_single_result["status"] == 201: refund = refund_single_result["response"] print(f"Disbursement refund created: {refund['id']}") # Refund a disbursement with custom details refund_custom_result = sdk.disbursement_refund().save( "ADV-PAY-123", "DISBURSEMENT-002", { "amount": 200.00, "reason": "Partial refund - damaged items", "external_reference": "REFUND-CUSTOM-001" } ) # List all refunds for the advanced payment list_result = sdk.disbursement_refund().list_all("ADV-PAY-123") if list_result["status"] == 200: refunds = list_result["response"] print(f"Total refunds: {len(refunds)}") for refund in refunds: print(f" Refund {refund['id']}: ${refund['amount']}") ``` -------------------------------- ### Get Authenticated User Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/endpoints.md Example of how to get the authenticated user's profile using the SDK. ```python sdk.user().get(request_options) ``` -------------------------------- ### Order Get Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/order.md Example of retrieving an order by its ID and printing its status if the request was successful. ```python result = sdk.order().get("ORDER-ID-123") if result["status"] == 200: order = result["response"] print(order["status"]) ``` -------------------------------- ### Internal GET Method Source: https://github.com/mercadopago/sdk-python/blob/master/docs/core/mp_base.html Example of the internal _get method used for making GET requests. It handles request options, headers, and calls the http_client's get method. ```python def _get(self, uri, filters=None, request_options=None): if filters is not None and not isinstance(filters, dict): raise ValueError("Filters must be a Dictionary") request_options = self.__check_request_options(request_options) headers = self.__check_headers( request_options, {"Content-type": self.__config.mime_json}) return self.__http_client.get( url=self.__config.api_base_url + uri, params=filters, headers=headers, timeout=request_options.connection_timeout, maxretries=request_options.max_retries, ) ``` -------------------------------- ### Account Configuration Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/configuration.md Demonstrates how to initialize the SDK with different access tokens for multiple accounts, including per-request overrides. ```python # Account 1 sdk_account1 = mercadopago.SDK(os.getenv("ACCOUNT1_TOKEN")) # Account 2 sdk_account2 = mercadopago.SDK(os.getenv("ACCOUNT2_TOKEN")) # Or with per-request override from mercadopago.config import RequestOptions sdk = mercadopago.SDK(os.getenv("DEFAULT_TOKEN")) opts_alt = RequestOptions(access_token=os.getenv("ALTERNATE_TOKEN")) result = sdk.payment().create(data, request_options=opts_alt) ``` -------------------------------- ### Full Example: Creating, getting, updating, and searching merchant orders Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/merchant-order.md Demonstrates the usage of the MerchantOrder class methods to manage merchant orders. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Create a merchant order order_result = sdk.merchant_order().create({ "items": [ { "id": "ITEM-001", "title": "Product A", "quantity": 2, "unit_price": 50.00 } ], "external_reference": "MERCHANT-ORDER-001" }) if order_result["status"] == 201: order = order_result["response"] order_id = order["id"] print(f"Merchant order created: {order_id}") # Get the merchant order get_result = sdk.merchant_order().get(order_id) if get_result["status"] == 200: mo = get_result["response"] print(f"Total: {mo['total_amount']}") print(f"Payments: {len(mo['payments'])}") # Update the merchant order update_result = sdk.merchant_order().update(order_id, { "shipments": [ { "id": "SHIP-001", "status": "ready_to_ship" } ] }) # Search for merchant orders search_result = sdk.merchant_order().search({ "external_reference": "MERCHANT-ORDER-001" }) if search_result["status"] == 200: orders = search_result["response"] print(f"Found {len(orders)} merchant orders") ``` -------------------------------- ### SDK Initialization and Usage Source: https://github.com/mercadopago/sdk-python/blob/master/docs/index.html Example of initializing the SDK and using its methods to interact with Mercado Pago APIs. ```python from mercadopago.sdk import SDK # Initialize the SDK with your access token sdk = SDK("YOUR_ACCESS_TOKEN") # Example: Get payment methods payment_methods = sdk.payment_methods() print(payment_methods) # Example: Create a payment # payment_data = { # "transaction_amount": 100.00, # "token": "a_token_from_your_frontend", # "description": "Test payment", # "payer": { # "email": "test_user@example.com" # } # } # payment = sdk.payment.create(payment_data) # print(payment) ``` -------------------------------- ### InvalidWebhookSignatureError Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/webhook-validator.md Example of how to catch and handle InvalidWebhookSignatureError. ```python try: WebhookSignatureValidator.validate(x_sig, x_req_id, data_id, secret) except InvalidWebhookSignatureError as e: print(f"Validation failed: {e.reason.value}") print(f"Request ID: {e.request_id}") print(f"Timestamp: {e.timestamp}") ``` -------------------------------- ### get Method Source: https://github.com/mercadopago/sdk-python/blob/master/docs/http/http_client.html Makes a GET request to the API. ```python def get(self, url, headers, params=None, timeout=None, maxretries=None): """Makes a GET request to the API""" return self.request( "GET", url=url, headers=headers, params=params, timeout=timeout, maxretries=maxretries, ) ``` -------------------------------- ### Django Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/webhook-validator.md An example of how to integrate webhook validation into a Django application. ```python from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from mercadopago.webhook import WebhookSignatureValidator, InvalidWebhookSignatureError import json SECRET = "your-webhook-secret" @csrf_exempt @require_http_methods(["POST"]) def handle_mercadopago_webhook(request): # Extract headers x_signature = request.META.get("HTTP_X_SIGNATURE") x_request_id = request.META.get("HTTP_X_REQUEST_ID") # Extract query parameter data_id = request.GET.get("data.id") # Validate try: WebhookSignatureValidator.validate( x_signature=x_signature, x_request_id=x_request_id, data_id=data_id, secret=SECRET, tolerance_seconds=600 ) except InvalidWebhookSignatureError as e: return JsonResponse({"error": str(e)}, status=401) # Parse and handle try: payload = json.loads(request.body) event_type = payload.get("type") if event_type == "payment": # Update payment status in database pass return JsonResponse({"status": "received"}) except Exception as e: return JsonResponse({"error": str(e)}, status=500) ``` -------------------------------- ### SDK Initialization and Configuration Source: https://github.com/mercadopago/sdk-python/blob/master/docs/config/index.html This snippet shows how to initialize the SDK with various configuration parameters and demonstrates the validation of these parameters. ```python def __init__(self, access_token=None, connection_timeout=None, custom_headers=None, max_retries=None, corporation_id=None, integrator_id=None, platform_id=None): ValueError: Param max_retries must be an Integer if access_token is not None: self.access_token = access_token if connection_timeout is not None: self.connection_timeout = connection_timeout if custom_headers is not None: self.custom_headers = custom_headers if max_retries is not None: self.max_retries = max_retries if corporation_id is not None: self.corporation_id = corporation_id if integrator_id is not None: self.integrator_id = integrator_id if platform_id is not None: self.platform_id = platform_id self.__config = Config() def get_headers(self): """ Sets the attribute values of headers """ headers = {"Authorization": "Bearer " + self.__access_token, "x-product-id": self.__config.product_id, "x-tracking-id": self.__config.tracking_id, "x-idempotency-key": str(uuid.uuid4().int), "User-Agent": self.__config.user_agent, "Accept": self.__config.mime_json} if self.__corporation_id is not None: headers["x-corporation-id"] = self.__corporation_id if self.__integrator_id is not None: headers["x-integrator-id"] = self.__integrator_id if self.__platform_id is not None: headers["x-platform-id"] = self.__platform_id if self.__custom_headers is not None: headers.update(self.__custom_headers) return headers @property def access_token(self): """ Sets the attribute value and validates access_token """ return self.__access_token @access_token.setter def access_token(self, value): if not isinstance(value, str): raise ValueError("Param access_token must be a String") self.__access_token = value @property def connection_timeout(self): """ Sets the attribute value and validates connection timeout """ return self.__connection_timeout @connection_timeout.setter def connection_timeout(self, value): if not isinstance(value, float): raise ValueError("Param connection_timeout must be a Float") self.__connection_timeout = value @property def corporation_id(self): """ Sets the attribute value and validates corporation id """ return self.__corporation_id @corporation_id.setter def corporation_id(self, value): if not isinstance(value, str): raise ValueError("Param corporation_id must be a String") self.__corporation_id = value @property def custom_headers(self): """ Sets the attribute value and validates custom headers """ return self.__custom_headers @custom_headers.setter def custom_headers(self, value): if not isinstance(value, dict): raise ValueError("Param custom_headers must be a Dictionary") self.__custom_headers = value @property def integrator_id(self): """ Sets the attribute value and validates integrator id """ return self.__integrator_id @integrator_id.setter def integrator_id(self, value): if not isinstance(value, str): raise ValueError("Param integrator_id must be a String") self.__integrator_id = value @property def max_retries(self): """ Sets the attribute value and validates max retries """ return self.__max_retries @max_retries.setter def max_retries(self, value): if not isinstance(value, int): raise ValueError("Param max_retries must be an Integer") self.__max_retries = value @property def platform_id(self): """ Sets the attribute value and validates platform id """ return self.__platform_id @platform_id.setter def platform_id(self, value): if not isinstance(value, str): raise ValueError("Param platform_id must be a String") self.__platform_id = value ``` -------------------------------- ### Module: core/__init__.py Source: https://github.com/mercadopago/sdk-python/blob/master/docs/core/index.html Module: core/__init__.py ```python from mercadopago.core.mp_base import MPBase __all__ = ( 'MPBase', ) ``` -------------------------------- ### create_transaction() Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/order.md Example of how to use the create_transaction method to add a payment transaction to an order. ```python result = sdk.order().create_transaction("ORDER-123", { "amount": 50.0, "payment_method_id": "visa", "token": "CARD_TOKEN" }) ``` -------------------------------- ### Advanced Setup Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/INDEX.md Shows how to configure the SDK with advanced options like timeout, retries, custom headers, and integrator ID. ```python from mercadopago.config import RequestOptions opts = RequestOptions( access_token="YOUR_TOKEN", connection_timeout=30.0, max_retries=5, custom_headers={"X-Custom": "value"}, integrator_id="my-platform" ) sdk = mercadopago.SDK("DEFAULT_TOKEN", request_options=opts) ``` -------------------------------- ### Loading token from environment Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/configuration.md Loads the access token from the MERCADOPAGO_ACCESS_TOKEN environment variable and initializes the SDK. ```python import os import mercadopago # Load token from environment access_token = os.environ.get("MERCADOPAGO_ACCESS_TOKEN") if not access_token: raise ValueError("MERCADOPAGO_ACCESS_TOKEN not set") sdk = mercadopago.SDK(access_token) ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/webhook-validator.md A complete example demonstrating how to set up a Flask application to receive and validate Mercado Pago webhooks. ```python from flask import Flask, request from mercadopago.webhook import WebhookSignatureValidator, InvalidWebhookSignatureError app = Flask(__name__) SECRET = "your-webhook-secret-from-mercado-pago" @app.route("/webhooks/mercadopago", methods=["POST"]) def handle_webhook(): # Extract headers x_signature = request.headers.get("x-signature") x_request_id = request.headers.get("x-request-id") # Extract data.id from query string data_id = request.args.get("data.id") # Validate signature try: WebhookSignatureValidator.validate( x_signature=x_signature, x_request_id=x_request_id, data_id=data_id, secret=SECRET, tolerance_seconds=300 # Allow 5-minute clock drift ) except InvalidWebhookSignatureError as e: print(f"Invalid webhook signature: {e.reason.value}") if e.request_id: print(f"Request ID: {e.request_id}") return {"error": "Invalid signature"}, 401 # Process webhook payload = request.get_json() event_type = payload.get("type") resource_id = payload.get("data", {}).get("id") print(f"Processing webhook: {event_type} for resource {resource_id}") # Handle different event types if event_type == "payment": handle_payment_event(payload) elif event_type == "plan": handle_plan_event(payload) elif event_type == "subscription": handle_subscription_event(payload) return {"status": "ok"}, 200 def handle_payment_event(payload): payment_id = payload["data"]["id"] print(f"Payment event for ID: {payment_id}") # Fetch full payment details and update your database # sdk = mercadopago.SDK(access_token) # result = sdk.payment().get(payment_id) def handle_plan_event(payload): print(f"Plan event: {payload}") def handle_subscription_event(payload): print(f"Subscription event: {payload}") if __name__ == "__main__": app.run(debug=False, port=8000) ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/card-token.md Demonstrates tokenizing card data, retrieving token details, and creating a payment using the token. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Tokenize card data from your server token_result = sdk.card_token().create({ "card_number": "4235647728025682", "expiration_month": 3, "expiration_year": 26, "security_code": "852", "cardholder": { "name": "Jane Smith", "identification": { "type": "DNI", "number": "27123456" } } }) if token_result["status"] == 201: token = token_result["response"] card_token = token["id"] print(f"Card tokenized: {card_token}") # Retrieve token details get_result = sdk.card_token().get(card_token) if get_result["status"] == 200: token_info = get_result["response"] print(f"Token: {token_info['id']}") print(f"Last four digits: {token_info['last_four_digits']}") print(f"Cardholder: {token_info['cardholder']['name']}") # Create payment using the token payment_result = sdk.payment().create({ "transaction_amount": 99.99, "token": card_token, "description": "One-time payment", "payment_method_id": "visa", "installments": 1, "payer": { "email": "customer@example.com" } }) if payment_result["status"] == 201: payment = payment_result["response"] print(f"Payment created with token: {payment['id']}") ``` -------------------------------- ### Module mercadopago.resources Source: https://github.com/mercadopago/sdk-python/blob/master/docs/resources/index.html Module: resources/__init__.py ```python """ Module: resources/__init__.py """ from mercadopago.config.request_options import RequestOptions from mercadopago.http.http_client import HttpClient from mercadopago.resources.advanced_payment import AdvancedPayment from mercadopago.resources.card import Card from mercadopago.resources.card_token import CardToken from mercadopago.resources.customer import Customer from mercadopago.resources.disbursement_refund import DisbursementRefund ``` -------------------------------- ### Request Options Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/OVERVIEW.md Example of overriding SDK-level defaults using RequestOptions. ```python from mercadopago.config import RequestOptions opts = RequestOptions( access_token='OVERRIDE_TOKEN', connection_timeout=30.0, max_retries=5, custom_headers={'X-Custom': 'value'} ) result = sdk.payment().create(payment_data, request_options=opts) ``` -------------------------------- ### Loading token from .env file Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/configuration.md Loads the access token from a .env file using python-dotenv and initializes the SDK. ```bash # .env MERCADOPAGO_ACCESS_TOKEN=MP_TEST_abc123def456... ``` ```python from dotenv import load_dotenv import os load_dotenv() sdk = mercadopago.SDK(os.getenv("MERCADOPAGO_ACCESS_TOKEN")) ``` -------------------------------- ### Module: http/__init__.py Source: https://github.com/mercadopago/sdk-python/blob/master/docs/http/index.html Module: http/__init__.py ```python """ Module: http/__init__.py """ from mercadopago.http.http_client import HttpClient __all__ = ( 'HttpClient', ) ``` -------------------------------- ### Full Example Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/chargeback.md Demonstrates searching for open chargebacks and then retrieving detailed information for each. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # Search for chargebacks search_result = sdk.chargeback().search({ "status": "open" }) if search_result["status"] == 200: chargebacks = search_result["response"] print(f"Found {len(chargebacks)} open chargebacks") for cb in chargebacks: print(f"Chargeback {cb['id']} on payment {cb['payment_id']}") # Get detailed chargeback info detail_result = sdk.chargeback().get(cb['id']) if detail_result["status"] == 200: detail = detail_result["response"] print(f" Amount: {detail['amount']}") print(f" Status: {detail['status']}") print(f" Reason: {detail['reason_code']}") ``` -------------------------------- ### Multi-account support Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/configuration.md Demonstrates how to manage multiple MercadoPago accounts by creating separate SDK instances. ```python import mercadopago ``` -------------------------------- ### Get Preference Source: https://github.com/mercadopago/sdk-python/blob/master/docs/resources/preference.html Method to retrieve a specific preference by its ID. It constructs the GET request URI using the provided preference_id. ```python def get(self, preference_id, request_options=None): """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/get/) # pylint: disable=line-too-long Args: preference_id (str): The Preference ID request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None. Returns: dict: Preference find response """ return self._get(uri="/checkout/preferences/" + str(preference_id), request_options=request_options) ``` -------------------------------- ### Create Preapproval Source: https://github.com/mercadopago/sdk-python/blob/master/docs/resources/preapproval.html Creates a new preapproval. Includes a link to the API reference for more details. ```python def create(self, preapproval_object, request_options=None): """[Click here for more info](https://www.mercadopago.com/developers/en/reference/subscriptions/_preapproval/post/) # pylint: disable=line-too-long Args: preapproval_object (dict): PreApproval to be created request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None. Raises: ValueError: Param preapproval_object must be a Dictionary Returns: dict: PreApproval creation response """ if not isinstance(preapproval_object, dict): raise ValueError("Param preapproval_object must be a Dictionary") return self._post(uri="/preapproval", data=preapproval_object, request_options=request_options) ``` -------------------------------- ### Plan Get Method Signature Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/plan.md Signature for the get method of the Plan class, used to retrieve a plan by its ID. ```python plan.get( plan_id: int | str, request_options: RequestOptions = None ) -> dict ``` -------------------------------- ### Example of retrieving and processing identification types Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/identification-type.md Example demonstrating how to retrieve all available identification types and iterate through them to display their details. ```python result = sdk.identification_type().list_all() if result["status"] == 200: types = result["response"] for id_type in types: print(f"{id_type['id']}: {id_type['name']} (min: {id_type['min_length']}, max: {id_type['max_length']})") ``` -------------------------------- ### Create Resource Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/INDEX.md Example of creating a new resource, such as a customer. ```python result = sdk.customer().create({ "email": "user@example.com", "first_name": "John" }) ``` -------------------------------- ### Preapproval Resource Factory Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/sdk.md Example of creating a PreApproval resource. ```python sdk.preapproval(request_options: RequestOptions = None) -> PreApproval ``` -------------------------------- ### Subscription Get Method Signature Source: https://github.com/mercadopago/sdk-python/blob/master/_autodocs/api-reference/subscription.md Signature for the get method of the Subscription class, used to retrieve a specific subscription by its ID. ```python subscription.get( subscription_id: int | str, request_options: RequestOptions = None ) -> dict ```