PayPal Integration Django Client-Side

Paypal is a well-known online payment service. Even if there are other viable competitors today, Paypal is a significant participant in the market with a good reputation and millions of consumers’ trust.

The quickest approach to integrate PayPal Checkout is through a client-side integration. The latter’s sett up and executing payments does not necessitate the use of a web server. On the other hand, the PayPal Checkout button allows you to set up and complete payments immediately from your browser.

Alternatively, PayPal supports server-side integration for advanced payment options, including authorization and capture, recurring billing, and issuing refunds.

This blog article will show you how to use the PayPal API to integrate a client-side payment gateway in Django.

What is a PayPal client integration, and how does it work?

In a PayPal client-side integration, the following is a typical flow of events.

  • The buyer clicks a PayPal button
  • Then, to set up the payment, the PayPal button uses the PayPal API
  • The controller initiates the browser’s checkout process

You must first set up your development environment before you can start working on your checkout integration.

Setting up the project

The starting point is to set up your development environment before you can integrate the PayPal Checkout process. Then you can proceed to create sandbox accounts to test your web and mobile apps after receiving a token that allows you to access protected REST API services.

PayPal provides the script to allow you to start your integration alongside well-written documentation. Please take a few moments to familiarize yourself with the commented sections, which we’ll go over one by one. It is the backbone of this article.

So, first and foremost, let’s set up our project. To create the initial project files, type the following instructions into your command prompt.

The first step is creating a directory for our project and creating a virtual environment for our project.

mkdir django-paypal && cd django-paypal

virtualenv .
create a virtual environment
create a virtual environment

The second step will involve activating the virtual environment, as shown.

source bin/activate
activate virtual environment
activate virtual environment

The third step is installing the latest version of Django using pip.

pip install django
pip install Django
pip install Django

The fourth step will entail creating a Django project called PayPal and creating an app called paypal_integration.

django-admin startproject paypal

cd paypal

python manage.py startapp paypal_integration

create Django project and app
create Django project and app

Add the base app in the installed apps of the project’s settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # custom apps
    'paypal',
    'paypal_integration',
]

In the base app directory, create a views.py file and add the following code.

from django.shortcuts import render

from django.shortcuts import render
def index(request):
  return render(request,'paypal/index.html')

Inside the root app folder, create the ‘templates’ folder. Next, create a new folder called ‘paypal inside the templates folder (strange Django conventions, right?).

Create an index.html template in the ‘paypal’ folder and paste the following code into it:

<div id="paypal-button"></div>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
  paypal.Button.render({
    // Configure environment
    env: 'sandbox',
    client: {
      sandbox: 'AdXvy8WyvD0pnFtfW2lXRE4Va4WlKWuqWL7S3c0wOEVJsQHGNLBQl_NMzIQt0o31rdeVp_03nT5MEWLo',
      production: 'demo_production_client_id'
    },
    // Customize button (optional)
    locale: 'en_US',
    style: {
      size: 'small',
      color: 'gold',
      shape: 'pill',
    },

    // Enable Pay Now checkout flow (optional)
    commit: true,

    // Set up a payment
    payment: function(data, actions) {
      return actions.payment.create({
        transactions: [{
          amount: {
            total: '25.50',
            currency: 'USD'
          }
        }]
      });
    },
    // Execute the payment
    onAuthorize: function(data, actions) {
      return actions.payment.execute().then(function() {
        // Show a confirmation message to the buyer
        window.alert('Thank you for your purchase!');
      });
    }
  }, '#paypal-button');

</script>

Now, for both the app and the project, add the views to the urlpatterns. Then, replace the code in your base app’s urls.py with this:

from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
]

Also, replace the following code in the project’s urls.py file:

from django.contrib import admin
from django.urls import path, include


urlpatterns = [
path('admin/', admin.site.urls),
path('', include('paypal_integration.urls'))
]

PayPal commerce Integration

To get started with your PayPal integration, follow these four steps:

  • Sign up for a PayPal account
  • Make a REST API application
  • Take a look at your API credentials
  • To test, create sandbox accounts
  • Sign up for a PayPal account

You’ll need a PayPal account to get started. However, there are two types of accounts. As a result, you can pick any one of the two types of accounts that comprise :

Developer account

The simplest way to get started is to create a developer account. In registering a developer account, the required details include your country of residence and email address. The only limitation is that the developer account can only permit calls to the sandbox (test) API calls.

When you need your live API credentials, you will have to create a merchant account. Check the next sub-heading to get more details about the merchant account.

Merchant account

A merchant account requires a few additional procedures, but it comes with a lot more features. In addition, the merchant account is very vital because it allows you to have live API credentials.

PayPal offers a variety of options to merchants, many of which can be customized from within your PayPal account. As a result, your PayPal account profile stores a lot of details. These include your organization’s account details, financial information, and selling preferences.

The following are some of the critical things you can handle in your merchant account:

  1. Create and manage your account – There are a few things to think about before you receive your first PayPal payment.
  1. Give a third-API party’s credentials specific permissions – You can grant a third-API party’s credentials individual permissions if you’re utilizing a shopping cart solution or another third-party wants to execute transactions on your behalf.
  1. Customize your PayPal checkout pages to make them stand out.
  2. In addition, you also have a say on how these pages are operated. All of these are made possible using your account profile.
  3. Obtain historical account information -You can get a copy of your transaction logs.

Further, the following introductory payment information may be helpful to new merchants.

Capture and Authorization

Authorization and capture, or Auth/Capture, is a term used to describe the process of accepting direct credit card payments. It allows you to authorize the availability of funds for a transaction but postpone the fund’s capture.

It is convenient for retailers with a slow order fulfillment procedure.

Due to order modifications that occur after the initial order is placed, such as taxes, shipping, or gratuity, Auth/Capture also allows merchants to adjust the original authorization amount. PayPal Express Checkout authorization and capture will be of great importance in ensuring that you get more in-depth information about authorization and capture.

Handling Recurring Payments

PayPal Recurring Payments allows you to bill a customer regularly for a set amount of money. To comprehend this correctly, you need to learn more about the PayPal Express Checkout recurring payments.

Also, you can use reference transactions to set up another type of recurring payment to handle payments for varying amounts of money on varying schedules.

How to create reference transactions

A reference transaction is a financial transaction that can be used to generate subsequent transactions. For example, a buyer purchases an item on your site, and you initiate another transaction using the PayPal transaction ID or reference transaction ID later.

You can also handle recurrent payments for varying amounts of money on varying schedules using reference transactions and billing agreements.

Refunds

A transaction can be refunded in whole or in part if the refund is provided within 180 days of payment. Or after 180 days. Otherwise, the refund process is different.

Reporting

PayPal offers a variety of reports to assist you in running your business. And as you may already know, reporting is at the core of any businesses’ success.

How to create a Developer account

Keenly follow the following steps that will guarantee a successful developer account:

  • Go to the Dashboard
  • Select the option Sign Up
  • Enter your home country, email address, and password.
  • Choose the option to create an account.
sign up for a developer account
sign up for a developer account

To convert your Developer account to a Merchant account, follow these steps:

  • Go to the Dashboard and log in.
  • Choose My Account.
  • Select Upgrade from the Business Account menu and fill out the online form.

image name: upgrade developer account
upgrade developer account

Creating sandbox accounts

After you’ve obtained your API credentials, you’ll need to create test buyer and merchant accounts to replicate transactions in the PayPal Sandbox.

What exactly is a PayPal sandbox?

The PayPal sandbox is a test version of the live PayPal environment, where you can test transactions and make sure your integration is working correctly before going live.

Now you can use the PayPal developer API. Log in from the top left (create one if you don’t already have an account).

To create sandbox test accounts, follow these steps:

  • Go to the Dashboard and log in
  • Then, select Accounts from the sandbox menu
  • Choose the option to create an account
create PayPal test accounts
create PayPal test accounts

To update your sandbox accounts’ default settings, go to:

  • Select Account under Manage Accounts, then click on View/Edit
  • Make your changes after selecting Edit.
  • Select Save when you’re finished.

To access the sandbox, follow these steps:

  • Click here, then log in with your test buyer or seller’s email and password.
  • Open the Sandbox Accounts link after logging in.
  • Now, the integration and testing phase requires two Sandbox accounts.

As a result, all you need to do is, click the blue “new account” button in the accounts area of your website.

You can switch between your test buyer and seller accounts as you integrate to ensure that transactions are performing as intended before going live.

A popup window will appear. At the bottom of the page, click the link to create a customer account.

image name: create a sandbox account as personal or buyer
create a sandbox account as personal or buyer

We’ll now require a personal account for sending payments and a business account for receiving them. So, using the same create a custom account link, merge the two accounts into one. Then, fill in the email and password boxes, and don’t forget to balance it out!

Developing a REST API App

To obtain your API credentials, you must first create a REST API app. Note that the app is a collection of saved configurations used to authenticate requests to PayPal APIs.

Your account can have several apps linked to it.

To make a REST API app, follow these steps:

  • Go to the Dashboard and log in
  • Choose the Create App option
  • Enter a name for your app, such as ‘Codeunderscored App.’
  • Choose the Create App option

To create a rest API app, click on the following link. The resultant page should appear as follows.

create a rest API app
create a rest API app

We’ll use the PayPal API to build our app right now. So click the blue “create app” button after opening this link.

Give your app a unique name and link it to your previously created business sandbox account. As you can see in the image, we created an app called “Codeunderscored Rest Paypal App” and linked it to our bank account.

create a new rest API app: codeunderscored Rest App
create a new rest API app: codeunderscored Rest App

How to get your API credentials

You’ll get the client ID and secret key after successfully creating the REST API app. Note that you’ll need a Client ID and Secret to make API calls and carry out process transactions in the sandbox and live environments. As a result, to obtain your sandbox API credentials, follow these steps:

  • Go to the Dashboard and log in.
  • Select your REST API app from the list under My Apps & Credentials.
  • Take note of your Client ID.
  • To see the system-generated secret for your Client ID, select “Show” under Secret.
  • To connect the gateway, we only need the client ID.

Integrating the system

To add PayPal buttons to your app, click here. Subsequently, copy the code inside the script tags as shown in the image below. We will then add it to the script tags in the index.html template.

annotated PayPal script for client-side Integration
annotated PayPal script for client-side integration

Verifying our connection

Start the server and connect to port 8000. This is how it will appear.

 chekout with paypal
checkout with PayPal

Subsequently, select PayPal from the drop-down menu or Card button if you want.

A popup will appear, prompting you to enter your email address and password, as shown in the diagram below.

 popup requesting for your paypal email address and password
popup requesting for your PayPal email address and password

Then, a new popup will appear requesting you to make the payment. In the first attempt, we will select the option PayPal as shown below. And click on “Pay Now” to complete the payment.

a prompt will appear requesting you to make payment
a prompt will appear requesting you to make payment

On our second attempt to make payment, we will choose to pay with Visa instead of using PayPal.

choosing to pay with Visa
choosing to pay with Visa

Upon successful payment in both cases, a success message will pop up to indicate completion of the payment, like in our demo below.

successful payment through Paypal
successful payment through Paypal

That’s it. You may see the transaction analysis by logging into your business sandbox account here.

Congratulations!! You’ve successfully incorporated a client-side payment gateway in your Django app.

Complete Code for reference

<div id="paypal-button"></div>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
  paypal.Button.render({
    // Configure environment
    env: 'sandbox',
    client: {
      sandbox: 'AdXvy8WyvD0pnFtfW2lXRE4Va4WlKWuqWL7S3c0wOEVJsQHGNLBQl_NMzIQt0o31rdeVp_03nT5MEWLo',
      production: 'demo_production_client_id'
    },
    // Customize button (optional)
    locale: 'en_US',
    style: {
      size: 'small',
      color: 'gold',
      shape: 'pill',
    },

    // Enable Pay Now checkout flow (optional)
    commit: true,

    // Set up a payment
    payment: function(data, actions) {
      return actions.payment.create({
        transactions: [{
          amount: {
            total: '25.50',
            currency: 'USD'
          }
        }]
      });
    },
    // Execute the payment
    onAuthorize: function(data, actions) {
      return actions.payment.execute().then(function() {
        // Show a confirmation message to the buyer
        window.alert('Thank you for your purchase!');
      });
    }
  }, '#paypal-button');

</script>
"""
Django settings for paypal project.

Generated by 'django-admin startproject' using Django 3.2.9.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-q1fwzo-*n&mk+=f2p(^&g5y0g4g5slmqu2bpjfk#cuah23acq!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # custom apps
    'paypal',
    'paypal_integration',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'paypal.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'paypal.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Conclusion

PayPal is one of the big names in handling online payments. As a result, many people are always trying or already integrating it. The two core ways of integrating PayPal into your site is either client-side or server-side. According to this article, client-side integration is simple and is almost entirely handled by PayPal.

All you have to do is pass in some JavaScript code on your front-end application. That will require your PayPal client ID to trigger the payment.

On the other hand, server-side integrations are more suitable if you handle complex payments and need more control from your end.

The client-side integration that we have covered herein will come in handy when you need to integrate with minimal mistakes and especially when you need it quickly.

Go ahead and try PayPal clients-side integration. We would love to hear about your experience.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *