49. Obtaining payment data from webhook

Now, we will retrieve the payment information from the webhook link that is called at the end of the payment process.

First, we will create a new view function called finalize_payment, which will handle the page the user is directed to after completing a payment.

Remember, since we've created a new view function, we also need to define a URL associated with it in the urls.py file.

urls.py
path('finilizepayment/',finalize_payment, name="finalize_payment"),

We don't need to pass any parameters related to the order/payment because the Mercado Pago API sends the data observed in the webhook directly within the request to the finalize_payment view function.

The webhook was crucial for understanding the format and specific data that will be sent via the request to the URL.

To ensure that the data is passed into the request, we need to provide the finalize_payment link to the finish_order function, where the payment is being processed. To accomplish this, we will import the reverse function from Django at the top of our views.py file.

from django.urls import reverse

The reverse function retrieves the name of the URL defined in the urls.py file and returns the relative path of that URL (excluding other details like the domain). To obtain the absolute link, we will use this function.

In this case, we'll call the reverse function inside our finish_order view, replacing the webhook link variable with the URL of the finalize_payment function.

views.py\finish_order
            #? make payment
            items_ordered = OrderedItem.objects.filter(order=order)
            link = request.build_absolute_uri(reverse("finalize_payment"))

Now, we will create the finalize_payment view function. For now, this function will simply print the data obtained from the request and then redirect the user to the store page.

views.py
def finalize_payment(request) :
    print(request.GET.dict())
    return redirect("store")

Now, when performing a successful test purchase as described in the previous chapter, the dictionary containing the purchase data (as seen in the webhook) will be displayed in the terminal. This confirms that we have successfully obtained the desired data.

Note: Do not confuse preference_id with payment_id; we are using preference_id as our payment_id.
Inside our admin page, you can observe the preference_id (displayed as Payment id) for each payment.

Last updated