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.




33 comments:

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

    ReplyDelete
  2. 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
  3. 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
  4. 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
  5. site is move to www.djangocrew.com

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

    ReplyDelete
  7. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Devops Training in Bangalore
    Best Devops Training in pune
    Microsoft azure training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  8. I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone.
    Data science course in bangalore

    ReplyDelete
  9. Very nice post here and thanks for it .I always like and such a super contents of these post.
    Excellent and very cool idea and great content of different kinds of the valuable information's.

    Java training in Bangalore



    ReplyDelete
  10. Thanks For sharing Your information The Information Shared Is Very Valuable Please Keep updating Us Time Just Went On Redaing The Article Python Online Course Devops Online Course Data Science Online Course Aws Science Online Course

    ReplyDelete
  11. I went through your blog its really interesting and holds an informative content. Thanks for uploading such a wonderful blog.Green Pen | Digital payment integration | Online Educational Services | Web Data Extraction Services

    ReplyDelete

  12. I enjoy what you guys are usually up too sort of clever work and coverage! Keep up the wonderful works guys.
    python training in chennai |python course in chennai

    ReplyDelete
  13. Attractive, post. I just stumbled upon your weblog and wanted to say that I have liked browsing your blog posts. After all, I will surely subscribe to your feed, and I hope you will write again soon! 정보이용료 현금화

    ReplyDelete
  14. Payments Gateway in Qatar thus becoming an important tool in the progress of online transactions or another form of electronic transactions. There are always security concerns when a transaction is done online.

    ReplyDelete
  15. 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..
    java training in chennai

    java training in omr

    aws training in chennai

    aws training in omr

    python training in chennai

    python training in omr

    selenium training in chennai

    selenium training in omr

    ReplyDelete
  16. I read over your blog, and I found it inquisitive. Also, you may also find Django Development Company Interested.

    ReplyDelete
  17. Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuff like this.

    Python

    Data Science

    Selenium

    ETL Testing

    AWS

    ReplyDelete
  18. Reading this blog is really good, and it was very effective it delivers good informative content. I have shared this on my social media as well share these information with my friends. We have got good knowledge.
    Python course In Bangalore

    ReplyDelete
  19. Good informative content and it was worthy content to share with my friends and colleagues. Information was delivered perfectly with the simple sentence. This blog makes my day good. Keep up the good work.
    iOS Course in Bangalore

    ReplyDelete
  20. Good informative content and it was worthy content to share with my friends and colleagues. Information was delivered perfectly with the simple sentence. This blog makes my day good. Keep up the good work.
    Advance Excel training In Bangalore

    ReplyDelete
  21. Hello! This post couldn't be composed any better! Perusing this post helps me to remember my past flat mate! He constantly continued lecturing about this. I assuredly will send this data to him. Genuinely certain he'll have an incredible perused. Much obliged for sharing!
    Dot Net training In Bangalore

    ReplyDelete
  22. Howdy, I do figure your blog could be having internet browser similarity issues. At the point when I take a gander at your site in Safari, it looks fine however when opening in IE, it makes them cross-over issues. I only needed to give you a fast watch out! Besides that, great blog!
    C and C++ training In Bangalore

    ReplyDelete
  23. This post is so interactive and informative.keep update more information...
    Java Training in Tambaram
    java course in tambaram

    ReplyDelete
  24. It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing. White Label Payment Service Provider

    ReplyDelete