46. Payment preference and user charge

Now, we will add the functionality to charge the user. We will follow the guidance provided in the Mercado Pago API documentation.

We will start by pasting the following code into our api_mercadopago.py file:

api_mercadopago.py
import mercadopago

public_key = "APP_USR-8e9c2811-1d99-4346-b8a0-9118201f7216"
access_token = "APP_USR-1378561128003766-083016-a08284dad9da4451cc196354af9f6722-1968090813"

#configure your credentials
sdk = mercadopago.SDK(access_token) #? validating access token

# Create items in the preference. preference = personalized charge for clients
preference_data = {
    "items": [
        {
            "title": "Mi producto",
            "quantity": 1,
            "unit_price": 75.56
        },
        {
            "title": "Mi producto2",
            "quantity": 2,
            "unit_price": 96.56
        }
    ], #? links that will be loaded
    "back_urls": {
        "success": "http://localhost:8000/mercadopago/success/",
        "failure": "http://localhost:8000/mercadopago/failure/",
        "pending": "http://localhost:8000/mercadopago/pending/"
    },
}

# Create a preference
preference_response = sdk.preference().create(preference_data) #? creating request with various informations about the payment
link = preference_response["response"]["init_point"]
payment_id = preference_response["response"]["id"] #? obtaining the payment id to treat it

Here's a explanation of the updated code:

  • Import Library: import mercadopago

    • Imports the Mercado Pago SDK to handle payment processing.

  • API Credentials:

    • public_key = "APP_USR-8e9c2811-1d99-4346-b8a0-9118201f7216"

    • access_token = "APP_USR-1378561128003766-083016-a08284dad9da4451cc196354af9f6722-1968090813"

    • Defines the public key and access token for Mercado Pago authentication.

  • Configure SDK: sdk = mercadopago.SDK(access_token)

    • Initializes the Mercado Pago SDK using the access token.

  • Preference Data:

    • preference_data: Dictionary containing payment details and URLs.

      • "items": List of items in the order, with each item including:

        • "title": Product name.

        • "quantity": Number of units.

        • "unit_price": Price per unit.

      • "back_urls": Dictionary of URLs to redirect users based on payment status:

        • "success": URL for successful payments.

        • "failure": URL for failed payments.

        • "pending": URL for pending payments.

  • Create Preference: preference_response = sdk.preference().create(preference_data)

    • Sends a request to Mercado Pago to create a payment preference with the provided preference_data.

  • Extract Response Data:

    • link = preference_response["response"]["init_point"]: Retrieves the URL to redirect the user for payment.

    • payment_id = preference_response["response"]["id"]: Retrieves the unique ID for the created payment preference for further processing.

The dictionary returned in preference_response contains information about the payment, as shown below:

output
{'status': 201, 'response': {'additional_info': '', 'auto_return': '', 'back_urls': {'failure': '', 'pending': '', 'success': ''}, 'binary_mode': False, 'client_id': '1378561128003766', 'collector_id': 1968090813, 'coupon_code': None, 'coupon_labels': None, 'date_created': '2024-08-30T19:17:24.859-04:00', 'date_of_expiration': None, 'expiration_date_from': None, 'expiration_date_to': None, 'expires': False, 'external_reference': '', 'id': '1968090813-569d7a93-43e4-4d12-8a56-737ca73e38da', 'init_point': 'https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=1968090813-569d7a93-43e4-4d12-8a56-737ca73e38da', 'internal_metadata': None, 'items': [{'id': '', 'category_id': '', 'currency_id': 'BRL', 'description': '', 'title': 'Mi producto', 'quantity': 1, 'unit_price': 75.56}, {'id': '', 'category_id': '', 'currency_id': 'BRL', 'description': '', 'title': 'Mi producto2', 'quantity': 2, 'unit_price': 96.56}], 'marketplace': 'NONE', 'marketplace_fee': 0, 'metadata': {}, 'notification_url': None, 'operation_type': 'regular_payment', 'payer': {'phone': {'area_code': '', 'number': ''}, 'address': {'zip_code': '', 'street_name': '', 'street_number': None}, 'email': '', 'identification': {'number': '', 'type': ''}, 'name': '', 'surname': '', 'date_created': None, 'last_purchase': None}, 'payment_methods': {'default_card_id': None, 'default_payment_method_id': None, 'excluded_payment_methods': [{'id': ''}], 'excluded_payment_types': [{'id': ''}], 'installments': None, 'default_installments': None}, 'processing_modes': None, 'product_id': None, 'redirect_urls': {'failure': '', 'pending': '', 'success': ''}, 'sandbox_init_point': 'https://sandbox.mercadopago.com.br/checkout/v1/redirect?pref_id=1968090813-569d7a93-43e4-4d12-8a56-737ca73e38da', 'site_id': 'MLB', 'shipments': {'default_shipping_method': None, 'receiver_address': {'zip_code': '', 'street_name': '', 'street_number': None, 'floor': '', 'apartment': '', 'city_name': None, 'state_name': None, 'country_name': None}}, 'total_amount': None, 'last_updated': None, 'financing_group': ''}}

The key we are primarily interested in is 'init_point', which contains a URL for the payment page that the user will access.

Note that the payment details exhibited on the page are the ones contained in the preference_data dictionary.

Also, note we still need to finish some modifications for the payment system to be fully operational.

Last updated