Implement PayPal Payment Gateway in CodeIgniter

by Shailender K. 3 minute read 4 views

PayPal integration in CodeIgniter enables businesses to accept secure online payments. Developers can easily create donation forms, success and cancel pages, and facilitate smooth transactions worldwide.

Key Points

  • PayPal has more than 430 million active accounts, allowing businesses to access a large customer base.
  • Available in over 200 global markets, PayPal facilitates cross-border payments in 25 currencies.
  • Businesses using PayPal see up to 82% higher checkout conversion rates compared to other payment gateways.

Introduction

Adding a secure payment gateway is an essential step in modern web development. Among all options, PayPal remains one of the most trusted and widely used online payment platforms globally. It enables businesses and developers to provide seamless and secure transactions effortlessly.

This guide walks you through integrating PayPal Checkout into CodeIgniter 4 by creating a simple donation system. You will learn to set up the PayPal SDK, configure environment variables, define routes and controllers, and build a user-friendly frontend using Bootstrap 5.3 and jQuery 3.7.

This tutorial is ideal for developers, businesses investing in custom web development, or anyone looking to add secure payment features to their CodeIgniter projects.

Prerequisite: Create a PayPal Developer Account

Before starting with CodeIgniter:

  1. Visit the PayPal Developer Dashboard and log in (or create a free account).
  2. Go to Sandbox → Accounts to create test accounts (one buyer, one merchant).
  3. Navigate to My Apps & Credentials → Create App under Sandbox.
  4. Copy your:
  • Client ID
  • Client Secret

These credentials are important for secure PayPal API integration. Always start with Sandbox for safe testing before moving to Live mode.

Step 1: Install PayPal PHP SDK

Run the following Composer command inside your CodeIgniter 4 project root:

                                        composer require paypal/rest-api-sdk-php
                                    

Why?

The PayPal SDK makes integration easier by handling authentication, API requests, and error management. This removes the need for manual cURL/HTTP code and is a common method used when businesses hire PHP developers for advanced payment solutions.

Step 2: Configure PayPal Credentials

Store your PayPal credentials in the .env file for security:

                                        PAYPAL_CLIENT_ID=your_client_id
PAYPAL_SECRET=your_client_secret
PAYPAL_MODE=sandbox   # change to 'live' in production
                                    

Using environment variables is best practice in web app development, helping keep your keys safe from accidental exposure.

Step 3: Define Routes

Open app/Config/Routes.php and add the following routes:

                                        $routes->get('donate', 'PaypalController::donate');
$routes->post('paypal/payment', 'PaypalController::payment');
$routes->get('paypal/success', 'PaypalController::success');
$routes->get('paypal/cancel', 'PaypalController::cancel');
                                    

These routes define the donation form, payment request, and success/cancel callbacks.

Step 4: Create PayPal Controller

Create a new file app/Controllers/PaypalController.php:

                                        namespace App\Controllers;

use App\Controllers\BaseController;

class PaypalController extends BaseController
{
    public function donate()
    {
        return view('paypal_donate');
    }

    public function payment()
    {
        $clientId = env('PAYPAL_CLIENT_ID');
        $clientSecret = env('PAYPAL_SECRET');
        $mode = env('PAYPAL_MODE'); // sandbox or live

        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential($clientId, $clientSecret)
        );

        $payer = new \PayPal\Api\Payer();
        $payer->setPaymentMethod("paypal");

        $amountValue = $this->request->getPost('amount');

        if ($amountValue < 1) {
            return redirect()->back()->with('error', 'Invalid donation amount.');
        }

        $amount = new \PayPal\Api\Amount();
        $amount->setCurrency("USD")->setTotal($amountValue);

        $transaction = new \PayPal\Api\Transaction();
        $transaction->setAmount($amount)
                    ->setDescription("Donation via PayPal");

        $redirectUrls = new \PayPal\Api\RedirectUrls();
        $redirectUrls->setReturnUrl(base_url('paypal/success'))
                     ->setCancelUrl(base_url('paypal/cancel'));

        $payment = new \PayPal\Api\Payment();
        $payment->setIntent("sale")
                ->setPayer($payer)
                ->setRedirectUrls($redirectUrls)
                ->setTransactions([$transaction]);

        try {
            $payment->create($apiContext);
            return redirect()->to($payment->getApprovalLink());
        } catch (\Exception $ex) {
            return redirect()->back()->with('error', $ex->getMessage());
        }
    }

    public function success()
    {
        return view('paypal_success');
    }

    public function cancel()
    {
        return view('paypal_cancel');
    }
}
                                    

This controller manages donation input, sets up PayPal Checkout, and redirects users appropriately.

Step 5: Create Donation Form

Create app/Views/paypal_donate.php:

                                        <!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Donate with PayPal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">
      <h2 class="mb-4 text-center">Make a Donation with PayPal</h2>
      <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger">
          <?= session()->getFlashdata('error') ?>
        </div>
      <?php endif; ?>
      <form method="POST" action="<?= base_url('paypal/payment'); ?>">
        <div class="mb-3">
          <label for="donation_amount" class="form-label">Donation Amount (USD)</label>
          <input type="number" class="form-control" id="donation_amount" name="amount" min="1" required>
        </div>
        <button type="submit" class="btn btn-primary w-100 mb-3">
          Donate with PayPal
        </button>
      </form>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"></script>
  </body>
</html>
                                    

Step 6: Create Success & Cancel Views

app/Views/paypal_success.php

                                        <h2>Payment Successful!</h2>
<p>Thank you for your generous donation through PayPal.</p>
                                    

app/Views/paypal_cancel.php

                                        <h2>Payment Cancelled</h2>
<p>Your PayPal transaction was cancelled. Please try again.</p>
                                    

Testing the Integration

  1. Visit: http://yourdomain.test/donate
  2. Enter a donation amount and submit.
  3. You’ll be redirected to PayPal’s Sandbox Checkout page.
  4. Log in using your Sandbox Buyer Account to complete the transaction.
  5. You’ll be redirected to the success or cancellation page based on the outcome.

Final Words

This feature is essential for businesses involved in custom web development or web app development because it allows them to accept secure payments worldwide.

For advanced setups like subscription billing, webhooks for payment verification, or enterprise-level integrations, you might think about hiring professional PHP developers or partnering with a web development firm.

Tech Stack & Version

 

Frontend

  • HTML5
  • CSS3
  • JavaScript

Backend

  • CodeIgniter 4
  • PayPal PHP SDK
  • MySQL

Backend

  • AWS
  • DigitalOcean
  • Linode
img

©2025Digittrix Infotech Private Limited , All rights reserved.