A payment gateway integration is kind of a necessity in all of the websites, whether it be e-commerce or a website where you are trying to give user more features based upon your varying service plans. And from a personal point of view Braintree is one of the best payment gateway that i came across while working on a project, www.wikipro.us based on Django framework of Python.

Benefits of Braintree

Braintree supports:

  • PayPal
  • Credit and Debit Cards
  • Bitcoin
  • Apple Pay
  • Android Pay
  • Venmo

And as Braintree itself is a Paypal service, so you can also expect a hassle-free support of Paypal in Braintree.

But as i started working on the integration i realised that there is not clear picture of how to implement this. So it took me more than 7 hours to implement it. So here is a guide showing how to integrate Braintree into your Django project.

Let’s kick off

Initial step is to sign up for a regular and a sandbox account. To test the integration we’ll use the sandbox account and its API keys.

Installing the Braintree

pip install braintree

We will be handling the following parts in our integration- Settings, Views and Templates.

Setting API keys and ID

Add the following lines in your Settings file

if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'):    BRAINTREE_PRODUCTION = Falseelse:    BRAINTREE_PRODUCTION = TrueRAINTREE_MERCHANT_ID = “your_merchant_id”BRAINTREE_PUBLIC_KEY = “your_public_key”BRAINTREE_PRIVATE_KEY = “your_private_key”

Preparing the View File for Braintree

@login_requireddef checkout_page(request):    #generate all other required data that you may need on the #checkout page and add them to context.    if settings.BRAINTREE_PRODUCTION:        braintree_env = braintree.Environment.Production    else:        braintree_env = braintree.Environment.Sandbox    # Configure Braintree    braintree.Configuration.configure(        braintree_env,        merchant_id=settings.BRAINTREE_MERCHANT_ID,        public_key=settings.BRAINTREE_PUBLIC_KEY,        private_key=settings.BRAINTREE_PRIVATE_KEY,    )     try:        braintree_client_token = braintree.ClientToken.generate({ "customer_id": user.id })    except:        braintree_client_token = braintree.ClientToken.generate({})    context = {'braintree_client_token': braintree_client_token}    return render(request, 'checkout.html', context)

In thee above code you can see that we have created a client_token. This token interacts with Braintree’s scripts to finally build the payment nonce. We will have that script in our checkout template page.

Also in the above code you can see that i have two different versions for generating client_token. This is a feature provided by Braintree that picks up the card of user on the basis of customer id if user has made any payment in past, thus saving the time. And if the user is first time on the page then it just goes to except part without having any argument in it.

Preparing the Payment Form

Add this line in the head of checkout template page.

<script src="https://js.braintreegateway.com/web/dropin/1.18.0/js/dropin.min.js"></script>

Then we will need a form to display the Braintree form which will include all the required input fields.

<form autocomplete="off">  {% if braintree_error %}    <div class="alert alert-danger fade in">        <button class="close" data-dismiss="alert">&times;</button

AD

50% OFF

$
Over copies sold
> {{ braintree_error|safe }} </div> {% endif %} <div class="braintree-notifications"></div> <div id="braintree-dropin"></div> <input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block" type="button" value="Pay now!" /></form>

Then in bottom add the script that will displaying the drop-in UI of Braintree-

<script>    var braintree_client_token = "{{ braintree_client_token }}";    var button = document.querySelector('#submit-button');    braintree.dropin.create({      authorization: braintree_client_token,      container: '#braintree-dropin',      card: {        cardholderName: {            required: false        }      }    }, function (createErr, instance) {        button.addEventListener('click', function () {            instance.requestPaymentMethod(function (err, payload) {                $.ajax({                    type: 'POST',                    url: '{% url "payment" %}',                    data: {'paymentMethodNonce': payload.nonce,                            'csrfmiddlewaretoken': '{{ csrf_token }}'}                }).done(function (result) {                   //do accordingly                });            });        });    });</script>

In the code you can see that we have used the client_token(that we generated in our view file) to build the payment nonce.

Now we will be heading back to the view file to add one more function that will handle the payment.

View function to handle payment

@login_requireddef payment(request):    nonce_from_the_client = request.POST['paymentMethodNonce']    customer_kwargs = {        "first_name": request.user.first_name,        "last_name": request.user.last_name,        "email": request.user.email,    }    customer_create = braintree.Customer.create(customer_kwargs)    customer_id = customer_create.customer.id    result = braintree.Transaction.sale({        "amount": "10.00",        "payment_method_nonce": nonce_from_the_client,        "options": {            "submit_for_settlement": True        }    })    print(result)    return HttpResponse('Ok')

Also add all the URLs accordingly in your urls.py file so all the urls that we have used can work without any hinderance.

Also you can test your integration with the following test data provided by Braintree:

  • Card number: 4111 1111 1111 1111
  • Expiry: 09/20
  • CVV: 400
  • Postal Code: 40000

That’s it

So that’s all for now regarding the Braintree and Django. Also you can get all kind of help required from the official documentation of Braintree as it remains updated, https://developers.braintreepayments.com/

Also don’t forget to write test cases for your integration.

Cheers!

Credit: 

Abhineet Srivastava from Medium