Home - Scripts - Website Development

  • 22 September 2025

Implementing PayPal Recurring Payment Integration in CodeIgniter 4

by Shailender K. 3 minute read 16 views

Businesses using recurring payment systems experienced a 35% increase in revenue and 40% higher customer retention within six months of implementation.

Key Points

  • 70% of companies reported faster payment processing after implementing recurring subscription systems.
  • Customer retention increased by 40% within three months using automated subscription management.
  • Revenue for software services grew 35% after integrating recurring subscription payments.

Implementing PayPal Recurring Payment Integration in CodeIgniter 4

Online payments have become a vital part of modern custom web development, especially for businesses engaged in E-commerce website projects. Recurring billing is especially crucial for subscription services like SaaS platforms, digital memberships, or online learning portals. Instead of asking users to pay manually each month, recurring payments automatically withdraw the specified amount, ensuring smooth transactions and enhancing customer experience.

This article explains PayPal integration for recurring payments in CodeIgniter development, utilizing the PayPal PHP SDK, MVC structure, and webhooks — with complete code examples.

What Are Recurring Payments?

Recurring payments, also called subscription payments, are automatic transactions in which a customer authorizes a business to withdraw funds on a regular schedule (weekly, monthly, or yearly).

Examples include:

  • Netflix monthly subscriptions.
  • SaaS platforms charge for premium plans.
  • Online learning portals bill students periodically.

Businesses looking to develop a subscription management system can trust PayPal integration for reliable and secure automated billing.

Why Use Webhooks in Recurring Payments?

When handling subscriptions, you need real-time updates from PayPal:

  • When a payment is completed.
  • When a subscription is canceled.
  • When a renewal fails.

This is where webhooks come into play. A webhook is a server-side listener that receives event notifications directly from PayPal. With webhooks, you can automatically update your database, making your payment gateway integration seamless and efficient.

MVC Structure in CodeIgniter Development

CodeIgniter follows the MVC (Model-View-Controller) pattern, which is a fundamental principle in professional custom web development.

  • Model → Manages database queries (e.g., storing subscription data).
  • View → Handles front-end display (e.g., PayPal subscription button).
  • Controller → Connects models and views, processes PayPal responses, and manages logic.

This approach keeps your project clean and organized, making it easier for teams to hire PHP developer talent to maintain or expand the project later.

Step 1: Prerequisites

  1. Create a PayPal Developer Account

  • Visit PayPal Developer Dashboard.
  • Create Sandbox buyer & merchant accounts.
  • Copy your Client ID and Client Secret.
  1. Install PayPal PHP SDK
    composer require paypal/rest-api-sdk-php

  2. Configure PayPal Credentials in .env

                                        PAYPAL_CLIENT_ID=your_client_id
PAYPAL_SECRET=your_client_secret
PAYPAL_MODE=sandbox
                                    

Step 2: PayPal Config File

This configuration file holds your credentials and determines whether you’re working in sandbox or live mode. Keeping credentials separate ensures flexibility when moving from testing to production.

                                        <?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Paypal extends BaseConfig
{
    public string $mode = 'sandbox'; // 'sandbox' or 'live'
    public string $sandboxClientId = 'Your_Sandbox_Client_ID';
    public string $sandboxClientSecret = 'Your_Sandbox_Client_SECRET';
    public string $liveClientId = '';
    public string $liveClientSecret = '';
    public string $currency = 'USD';
}
                                    

Step 3: Create Subscription View

The view is where customers interact with the PayPal subscription button. Here, we include PayPal’s JavaScript SDK, specify the plan ID, and handle responses like approval, cancellation, and errors.

This is a key part of e-commerce website development, as it ensures a smooth user experience.

app/Views/subscription/index.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">
      <div id="paypal-button-container"></div>
    </div>
    <script src="https://www.paypal.com/sdk/js?client-id=<?= esc(config('Paypal')->sandboxClientId) ?>&vault=true&intent=subscription"></script>
    <script>
    paypal.Buttons({
      createSubscription: function(data, actions) {
        return actions.subscription.create({
          plan_id: 'YOUR_PLAN_ID' // Replace with your PayPal Plan ID
        });
      },
      onApprove: function(data, actions) {
        fetch('/subscription/success', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
          },
          body: JSON.stringify({
            subscription_id: data.subscriptionID
          })
        })
        .then(response => response.json())
        .then(data => {
          window.location.href = '/subscription/complete';
        });
      },
      onCancel: function(data) {
        window.location.href = '/subscription/cancel';
      },
      onError: function(err) {
        console.error('An error occurred during subscription', err);
      }
    }).render('#paypal-button-container');
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"></script>
  </body>
</html>
                                    

Step 4: Subscription Controller

The controller processes actions after the user interacts with PayPal. It handles success, cancellation, and completion routes. You can also expand it to connect with your database model to update subscription statuses.

This forms the backbone of your subscription management system, ensuring transactions are stored and managed properly.

app/Controllers/Subscription.php

                                        <?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\Client;
class Subscription extends Controller
{
    private $paypalConfig;
    private $client;

    public function __construct()
    {
        $this->paypalConfig = config('Paypal');
        $this->client = new Client();
    }

    public function index()
    {
        return view('subscription/index');
    }

    public function success()
    {
        $subscriptionId = $this->request->getVar('subscription_id');
        // Example: Save subscription in DB
        // $userModel->update(session('user_id'), [
        //     'paypal_subscription_id' => $subscriptionId,
        //     'status' => 'active'
        // ]);
        return $this->response->setJSON(['status' => 'success']);
    }

    public function complete()
    {
        return 'Subscription successful!';
    }
    public function cancel()
    {
        return 'Subscription was cancelled.';
    }
}
                                    

Step 5: Routes Setup

In CodeIgniter, routes determine how URLs map to controllers. Defining proper routes ensures your PayPal integration works seamlessly by directing PayPal responses to the correct methods.

app/Config/Routes.php

                                        $routes->get('subscription', 'Subscription::index');
$routes->post('subscription/success', 'Subscription::success');
$routes->get('subscription/complete', 'Subscription::complete');
$routes->get('subscription/cancel', 'Subscription::cancel');
$routes->post('paypal/webhook', 'Webhook::handle');
                                    

Step 6: Webhook Controller

Webhooks are vital for real-time updates. They allow PayPal to inform your system about subscription events such as successful payments or cancellations.

By implementing webhook handling, your subscription management system will always be up to date, even if the customer never returns to your website after subscribing.

This is particularly useful in custom web development projects where automation is key.

app/Controllers/Webhook.php

                                        <?php namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\Client;

class Webhook extends Controller
{
    private $paypalConfig;
    private $client;

    public function __construct()
    {
        $this->paypalConfig = config('Paypal');
        $this->client = new Client();
    }
    private function getAccessToken()
    {
        $clientId = $this->paypalConfig->sandboxClientId;
        $clientSecret = $this->paypalConfig->sandboxClientSecret;
        $response = $this->client->request('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', [
            'auth' => [$clientId, $clientSecret],
            'form_params' => ['grant_type' => 'client_credentials']
        ]);
        $body = json_decode($response->getBody(), true);
        return $body['access_token'];
    }
    public function handle()
    {
        $event = $this->request->getJSON(true);
        $eventType = $event['event_type'];
        switch ($eventType) {
            case 'PAYMENT.SALE.COMPLETED':
                $subscriptionId = $event['resource']['billing_agreement_id'];
                // Update DB: mark subscription as active
                break;
            case 'BILLING.SUBSCRIPTION.CANCELLED':
                $subscriptionId = $event['resource']['id'];
                // Update DB: mark subscription as cancelled
                break;
            // Add more event types as needed
        }
        return $this->response->setStatusCode(200);
    }
}
                                    

Final Words

By following these steps, you’ve successfully implemented PayPal integration for recurring payments in CodeIgniter 4. This solution supports:

  • Payment gateway integration for secure transactions.
  • A reliable subscription management system.
  • Scalable architecture for E-commerce website development.

If your business needs expert assistance, you can hire PHP developer teams experienced in CodeIgniter development and custom web development to tailor advanced solutions for your project.

This ensures your application is production-ready for handling recurring payments with PayPal.

Tech Stack & Version

Frontend

  • HTML5
  • CSS3
  • Bootstrap 5
  • JavaScript
  • PayPal JavaScript SDK

Backend

  • CodeIgniter 4
  • PHP Framework
  • PayPal PHP SDK
  • MySQL
  • MariaDB

Deployment

  • DigitalOcean
  • AWS
img

©2025Digittrix Infotech Private Limited , All rights reserved.