E-commerce (paypal) integration with Django

Reading Time : ~ .

E-commerce is integration is becoming almost essential for every web application nowadays. 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: Integrating PayPal with Django with REST API is somewhat easy and easy to understand. Paypal provides an 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, initialize 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 the 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 – Another 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 details 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 from the recurring payment that is created. Doing the direct payment without 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

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Sorl-thumbnail to generate thumbnails in django Rakesh babu Podishetty

Displaying and Customizing the images in django with sorl-thumbnail.

Continue Reading...
How to Document API Requests using Django Rest Swagger Swetha Naretla

Django Rest Swagger is used to Document your API for eg., Listing all Your project Rest API's in the browser with brief description about the ...

Continue Reading...
Extract data from PDF and all Microsoft Office files in python Ashwin Kumar

The quick way to get/extract text from PDFs in Python is with the Python library "slate". Slate is a Python package that simplifies the process ...

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