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.




Tuesday, November 10, 2015

Django override save method

Django override save method (two ways)



1)
 class Blog(models.Model):
  name = models.CharField(max_length=100)
  tagline = models.TextField()

  def save(self, *args, **kwargs):
    do_something()
   # Call the "real" save() method in the base class 'models.Model'
    super(Blog, self).save(*args, **kwargs) <-----
    do_something_else()

 is equal to

2)
  class Blog(models.Model):
   name = models.CharField(max_length=100)
   tagline = models.TextField()

   def save(self, *args, **kwargs):
     do_something()
    # Call the "real" save() method in the base class 'models.Model'.
     models.Model.save(self, *args, **kwargs) <----- Note: self
     do_something_else()