Saturday, November 14, 2015

Braintree payment gateway integration with Django


                       Braintree  payment gateway integration with Django

Introduction

Here Im going to tell you How to integrate the Braintree payment gateway with Django based application. I really thankful to Braintree support team because when i start to integrate i feel really hard. i have successfully completed the project and here i'm put the Github link for demo project.

Workflow Diagram 




Integration

Step 1 :  Create Sandbox account with  Barintree  :- Create sandox account

Step 2 :  Setup Client

Step 3 : Setup Server

Step 5 : Have fun .... with Brain tree

BrainTree Integration with Django Project

Create the Sandbox account with  braintree , they will provide the merchant id, private and public key
Install braintree in your env using pip ( pip install braintree ).

Add the keys and merchant id with project settings

settings.py

BRAINTREE_MERCHANT = 'dznq5k44zc3qrycm'
BRAINTREE_PUBLIC_KEY = 'ttkr358rbpfnjvgn'
BRAINTREE_PRIVATE_KEY = 'dcfa177a5f71e00370323f17221e6cea'

Configure the Braintree with this above credentials

Views.py

from django.conf import settings

import braintree
braintree.Configuration.configure(braintree.Environment.Sandbox,
 merchant_id=settings.BRAINTREE_MERCHANT,
 public_key=settings.BRAINTREE_PUBLIC_KEY,
 private_key=settings.BRAINTREE_PRIVATE_KEY)

Genrate a client token in server side and render to the client side for processing payment method nonce.

Views.py

@login_required
@csrf_exempt
def checkout(request):
rg = request.POST.get
amount =  request.POST.get('prise') // when user click the subscription for payment
user = Staff.objects.get(id=request.user.id)
a_customer_id = ''
if not user.customer_id:
result = braintree.Customer.create({
   "first_name": user.first_name,
   "last_name": user.last_name,
   "company": "Braintree",
   "email": user.email,
   "phone": "312.555.1234",
   "fax": "614.555.5678",
   "website": "www.example.com"
})
if result.is_success:
user.customer_id = result.customer.id
user.save()
a_customer_id = user.customer_id
else:
a_customer_id = user.customer_id
if not user.client_token:
client_token = client_token = braintree.ClientToken.generate({
   "customer_id": a_customer_id
})
user.client_token = client_token
user.save()
else:
client_token = user.client_token

varibles ={'amount':amount,'client_token':client_token}
return render(request, 'checkout.html',varibles)

Setup Client 

checkout.html

<div class="form-style-5">
    {{amount}}
<input type='hidden' id='client_token' value='{{client_token}}'> // client token from server side
<form id="checkout" method="post" action="/payment">
    <div id="payment-form">
       <input type='hidden' name='amount' value='{{amount}}'> // amount
       <input type='text' name='amount' value='{{amount}}' readonly>
    </div>
    <input type="submit" value="Subcribe"> // Submit Button
</form>

</div>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>

var clientToken = document.getElementById('client_token').value;
// creating payment method nonse

braintree.setup(clientToken, "dropin", {
  container: "payment-form"
});
</script>

How the Client look ?




When the user click on the submit button it will post the payment method nonce to server side.


Create Transcation

@login_required
@csrf_exempt
def payment(request):
if request.POST:
if request.POST.get("payment_method_nonce"):
                        // payment method nonce from client side.
nonce_from_the_client =  request.POST.get("payment_method_nonce")
staff = Staff.objects.get(id=request.user.id)
sub = Subscription()
sub.staff = staff
sub.payment_nonce = nonce_from_the_client
sub.amount = request.POST.get("amount")
sub.save()
result = braintree.Transaction.sale({
   "amount": sub.amount,
   "payment_method_nonce": sub.payment_nonce
})
transaction_id =  result.transaction.id
sub.txnid = transaction_id
sub.save()
message = ''
if result.is_success: // transaction success or not
sub.result = True
sub.save()
message =  'Transaction successfully completed'+' : '+ transaction_id
varibles ={'message':message}
return render(request, 'success.html',varibles)
else:
message = 'Error Transaction Faild'

varibles ={'message':message,}
return render(request, 'checkout.html',varibles)
else:
message = 'No transaction'

varibles ={'message':message,}
return render(request, 'checkout.html',varibles)

Transaction Results in my braintree account




Demo Project i have pushed in to the github , you can download and check it yourself.

Project codebraintree payment gateway demo project

                                                            Thank you.




15 comments:

  1. Finding the time and actual effort to create a superb article like this is great thing. I’ll learn many new stuff right here! Good luck for the next post buddy..
    Fresher Jobs
    Fresher Opening

    ReplyDelete
  2. wow!!!! this is amazing and very wonderful oppurtunity for me and really everyone..Vmware Training in Chennai

    ReplyDelete
  3. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..
    SAP Training in Chennai
    SAP ABAP Training in Chennai
    SAP FICO Training in Chennai

    ReplyDelete
  4. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with
    excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us.
    Informatica Training in Chennai

    ReplyDelete
  5. wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

    informatica training in chennai


    ReplyDelete
  6. site is move to www.djangocrew.com

    ReplyDelete
  7. Just read your website. Good one. I liked it. Keep going. you are a best writer your site is very useful and informative thanks for sharing!

    Herbal Shampoo
    Dandruff Treatment
    Antifungal Cream
    Vitiligo Medicines

    ReplyDelete
  8. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..
    Wooden Temple for Home
    Tanjore Painting
    Pooja Mandir

    ReplyDelete
  9. This is a great article, I have been always to read something with specific tips! I will have to work on the time for scheduling my learning.
    Antifungal Cream
    Vitiligo Medicines
    Herbal Tonic

    ReplyDelete
  10. I was wondering if there is a way to implement Bank transactions using braintree. Iam in India

    ReplyDelete
  11. Really you have done great job,There are may person searching about that now they will find enough resources by your post
    python training institute in marathahalli
    python training institute in btm
    Python training course in Chennai

    ReplyDelete
  12. I like your blog, I read this blog please update more content on python, further check it once at python online training

    ReplyDelete