Integrating the payment gateway

The checkout process will work as follows:

  1. Add items to the shopping cart
  2. Check out the shopping cart
  3. Enter credit card details and pay

We are going to create a new application to manage payments. Create a new application in your project using the following command:

python manage.py startapp payment

Edit the settings.py file of your project and add the new application to the INSTALLED_APPS setting as follows:

INSTALLED_APPS = [
# ...
'payment.apps.PaymentConfig',
]

The payment application is now active.

After clients place an order, we need to redirect them to the payment process. Edit the views.py file of the orders application and include the following imports:

from django.urls import reverse
from django.shortcuts import render, redirect

In the same file, replace the following lines of the order_create view:

# launch asynchronous task 
order_created.delay(order.id)
return render(request,
'orders/order/created.html',
locals())

Replace them with the following:

# launch asynchronous task
order_created.delay(order.id)
# set the order in the session
request.session['order_id'] = order.id
# redirect for payment
return redirect(reverse('payment:process'))

With this code, after successfully creating an order, we set the order ID in the current session using the order_id session key. Then, we redirect the user to the payment:process URL, which we are going to implement later.

Remember that you need to run Celery in order for the order_created task to be queued and executed.

Every time an order is created in Braintree, a unique transaction identifier is generated. We will add a new field to the Order model of the orders application to store the transaction ID. This will allow us to link each order with its related Braintree transaction.

Edit the models.py file of the orders application and add the following field to the Order model:

class Order(models.Model):
# ...
braintree_id = models.CharField(max_length=150, blank=True)

Let's sync this field with the database. Use the following command to generate migrations:

python manage.py makemigrations

You will see the following output:

Migrations for 'orders':
orders/migrations/0002_order_braintree_id.py
- Add field braintree_id to order

Apply the migration to the database with the following command:

python manage.py migrate

You will see output that ends with the following line:

Applying orders.0002_order_braintree_id... OK

The model changes are now synced with the database. Now you are able to store the Braintree transaction ID for each order. Let's integrate the payment gateway.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset