47. Treating payment errors and connecting with views

Now, we will connect the Mercado Pago payment system to our views and handle potential errors that may arise during the payment process.

First, to obtain the necessary information from the views, we'll encapsulate our payment system code inside a function called create_payment. This function will take as its parameters the desired data we want to obtain from the view functions. We can then call the create_payment function within the view functions, passing the required data.

create_payment
import mercadopago

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

def create_payment(items_ordered, link) :
    #configure your credentials
    sdk = mercadopago.SDK(access_token) #? validating access token

    #? items the user is purchasing
    items = []
    for item in items_ordered :
        quantity = int(item.quantity)
        product_name = item.itemstock.product.name
        unit_price = float(item.itemstock.product.price)
        items.append({
            "title": product_name, 
            "quantity": quantity, 
            "unit_price": unit_price
            })

    # Create items in the preference. preference = personalized charge for clients
    preference_data = {
        "items": items, 
        "back_urls": { #? links that will be loaded
            "success": link,
            "failure": link,
            "pending": link
        },
    }

    # 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
    print(link, payment_id)

Here’s a explanation of the updated create_payment function:

  • Import Library: import mercadopago

    • Imports the Mercado Pago SDK for handling payment processing.

  • API Credentials:

    • public_key and access_token are predefined variables for authentication with Mercado Pago. The access_token is used to initialize the SDK.

  • Function Definition: def create_payment(items_ordered, link)

    • Defines a function to create a payment preference and return relevant payment information.

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

    • Configures the Mercado Pago SDK with the provided access token.

  • Prepare Items:

    • Initializes an empty list items.

    • Iterates through items_ordered to construct a list of items:

      • quantity: Number of units of the item.

      • product_name: Name of the product.

      • unit_price: Price per unit of the product.

    • Appends a dictionary with the item details to the items list.

  • Preference Data:

    • preference_data: Dictionary defining the payment preference.

      • "items": List of items to be purchased.

      • "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 preference_data.

  • Extract Response Data:

    • link = preference_response["response"]["init_point"]: Retrieves the URL to redirect users to start the payment process.

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

  • Output: print(link, payment_id)

    • Prints the payment link and ID for debugging or logging purposes.

In the views.py file, we will import the newly created create_payment function.

views.py
from .api_mercadopago import create_payment #? needs to put the point so it searches on the same folder

Important Note: When importing from a file in the same folder, prefix the import statement with a '.' so that Python searches for the file within the same directory instead of the main project folder.

Next, we'll call the create_payment function in the error-checking condition. This way, if no errors are detected when confirming the order, the payment system will be executed.

views.py\finish_order
        if error :
            addresses = Adres.objects.filter(client=order.client) #? filters all adresses associated with the client
            context = {"error" : error, "order" : order, "addresses" : addresses}
            return render(request,"checkout.html", context)
        else :
            #? make payment
            items_ordered = OrderedItem.objects.filter(order=order)
            link = ""
            create_payment(items_ordered, link)
            return redirect("store")
    else :
        return redirect("store")

Now, when the user confirms the order, a link will appear in the terminal console. Clicking this link will take the user to the payment page with the appropriate price.

Last updated