E-commerce (paypal) integration with Django

E-commerce is integration is becoming almost essential for every web application now a days. There are so many payment gateways to integrate with our application. Some of them are Amazon payments, Asiapay, BPAY, Brain Tree, PayPal ...etc. Out of these now in this we'll see how to integrate Paypal with our django Application.

Integrating Paypal with Django: Paypal provides two kinds of api for integrating any application with it. They are 1.PayPal REST api 2.PayPal CLASSIC api

1. Integrating with REST api: Integrting paypal with dajngo with REST api is some what easy and easy to understnad. Paypal provides a sdk for integrating PayPal with Django, that is 'paypal rest sdk'. For more about restsdk check this https://github.com/paypal/rest-api-sdk-python and https://developer.paypal.com/webapps/developer/docs/api/

2.Integrating Paypal with classic api: First intialise the paypal urls for endpoint and paypal connection as follows. End_url = 'https://api-3t.sandbox.paypal.com/nvp' PAYPAL_URL = 'https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=' Buyers use Express Checkout to pay you on PayPal's secure site and return to your site to complete the transaction.

1.Setting express checkout for transaction:

params = {
'USER' : 'xxxxxxxx', # Edit this to your API user name
'PWD' : 'xxxxxxxx', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'METHOD':'SetExpressCheckout',
'VERSION':86,
'PAYMENTREQUEST_0_PAYMENTACTION':'SALE',     # type of payment
'PAYMENTREQUEST_0_AMT':50,              # amount of transaction
'PAYMENTREQUEST_0_CURRENCYCODE':'USD',   
'cancelUrl':"xxxxxxxxxxxxx",    #For use if the consumer decides not to proceed with payment 
'returnUrl':"xxxxxxxxxxxx"   #For use if the consumer proceeds with payment
}

    params_string = urllib.urlencode(params)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read() #gets the response and parse it.
    response_dict = parse_qs(response)
    response_token = response_dict['TOKEN'][0]
    rurl = PAYPAL_URL+response_token #gather the response token and redirect to paypal to authorize the payment
    return HttpResponseRedirect(rurl)

2.Executing the express checkout payment

exparams = {
'USER' : 'xxxxxxx', # Edit this to your API user name
'PWD' : 'xxxxxx', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'VERSION':86,               
    
'METHOD':'DoExpressCheckoutPayment',
'TOKEN':'xxxx', #get the token from the request that is redirected
'PAYERID':payerid,      # customer's unique PayPal ID
'PAYMENTREQUEST_0_PAYMENTACTION':'SALE',    # payment type
'PAYMENTREQUEST_0_AMT':50,             # transaction amount
'PAYMENTREQUEST_0_CURRENCYCODE':'USD'
}
      
    params_string = urllib.urlencode(exparams)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
    return HttpResponse(response)

In response you will get the following details token,transactionid,receipientid, paymenttype, transaciontype.... etc., For more about the parameters to be sent and the response details please refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoExpressCheckoutPayment_API_Operation_NVP/ 3.Refunding the transaction:

params = {
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 

'VERSION':86,
'METHOD':'RefundTransaction',
'TRANSACTIONID':'60Y29533L12153911',    #ID of the transaction for which the refund is made 
'REFUNDTYPE':'Full'   
}
    params_string = urllib.urlencode(params)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
    return HttpResponse(response)

Gather the transactionid from the payment created.The refund can be done in 4 ways. They are

Type of refund you are making. It is one of the following values:

  • Full – Full refund (default).
  • Partial – Partial refund.
  • ExternalDispute – External dispute. (Value available since version 82.0)
  • Other – Other type of refund. (Value available since version 82.0)

Creating Recurring Payment: Using CLASSIC api we can create a recurring payment. A Recurring Payment Regularly scheduled payment of a consumer debt, such as an installment loan, which is payable monthly or yearly ..etc.,  For more about parameters to be sent and response details refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/RefundTransaction_API_Operation_NVP/ 1.Creating a Recurring Payment:

params = {
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'METHOD':'SetExpressCheckout',
'VERSION':86,
'L_BILLINGTYPE0':'RecurringPayments',    #The type of billing agreement
'L_BILLINGAGREEMENTDESCRIPTION0':'FitnessMembership',    #The description of the billing agreement
'cancelUrl':"http://localhost:8000/paycanret/",    #For use if the consumer decides not to proceed with payment 
'returnUrl':"http://localhost:8000/payauthret/"   #For use if the consumer proceeds with payment
}

    params_string = urllib.urlencode(params)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
    response_dict = parse_qs(response)
    response_token = response_dict['TOKEN'][0]
    rurl = PAYPAL_URL+response_token
    return HttpResponseRedirect(rurl)

2.Creating the profile after authentication:

    recparams = {
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
'METHOD':'CreateRecurringPaymentsProfile',
'VERSION':86,
'TOKEN':request.GET.get('token'),
'PAYERID':payerid,
'PROFILESTARTDATE':datetime.datetime.now(),    #Billing date start, in UTC/GMT format
'DESC':'FitnessMembership',    #Profile description - same as billing agreement description
'BILLINGPERIOD':'Day',    #Period of time between billings
'BILLINGFREQUENCY':1,    #Frequency of charges 
'AMT':1,    #The amount the buyer will pay in a payment period
'CURRENCYCODE':'USD'    #The currency, e.g. US dollars
    

}
    
    
    
    params_string = urllib.urlencode(recparams)
    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', params_string).read()
      
    return HttpResponse(response)

This will create the recurring payment profile and do the payment as the billing frequency and billing period you provided. For more about parameters to be sent and response detials refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/ 3.Cancelling the Recurring profile:

form_fields = {
        "METHOD": "ManageRecurringPaymentsProfileStatus",
        "PROFILEID": "I-GRYD2P8AL3UX", # put your subscription ID here
        "ACTION": "cancel",
        'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
        "VERSION": 86
}

    

    form_data = urllib.urlencode(form_fields)

    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', form_data).read()
    
    return HttpResponse(response)

get the profile id form the recurring payment that is created. Doing the direct payment with out redirecting to the paypal account with the user card:

nvp_params = {
            # 3 Token Credentials
'USER' : 'teja-facilitator_api1.micropyramid.com', # Edit this to your API user name
'PWD' : '1383300993', # Edit this to your API password
'SIGNATURE' : 'AFcWxV21C7fd0v3bYYYRCpSSRl31A0ltbCXAvF44j6B.kUqG3MePFr40', 
        "VERSION": 86,

            # API Version and Operation

            'METHOD' : 'DoDirectPayment',

            # API specifics for DoDirectPayment
            'PAYMENTACTION' : 'Sale',
            'IPADDRESS' : client_address,
            'AMT' : '1',
            'CREDITCARDTYPE' : 'MasterCard',
            'ACCT' : '5490940605734691',
            'EXPDATE' : 112018,
            'CVV2' : '123',
        
            'FIRSTNAME' : 'chaitanya',
            'LASTNAME' : 'kattineni',
            'STREET' : '1 Main St',
            'CITY' : 'San Jose',
            'STATE' : 'CA',
            'ZIP' : '95131',
            'COUNTRYCODE' : 'US'
        }
    
    form_data = urllib.urlencode(nvp_params)

    response = urllib.urlopen('https://api-3t.sandbox.paypal.com/nvp', form_data).read()
    
    return HttpResponse(response)

It will return the details regarding the transaction done. For more about parameters to be sent and response details refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoDirectPayment_API_Operation_NVP/  

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Latest Comments
Related Articles
Basics of Django messages framework Divya Sri

In any web application we need to display notification messages to the end user after processing a form or some other types of his requests. ...

Continue Reading...
How to Create initial django migrations for existing DB schema. Chaitanya Kattineni

Django provides the comfort database migrations from its version 1.8, with which we can avoid the usage of third party packages like south. Adding migrations ...

Continue Reading...
Django Generic many to many field implementation Vamsi Popuri

Django application has a GM2MField that combines the features of the standard Django "ManyToManyField" and "GenericForeignKey".

Installation:
pip install django-gm2m

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties