PHPackages                             levizwannah/pesapal-sdk-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. levizwannah/pesapal-sdk-php

ActiveLibrary[Payment Processing](/categories/payments)

levizwannah/pesapal-sdk-php
===========================

Pesapal V3 SDK for PHP

v1.1.2.1(2y ago)028MITPHP

Since Jan 5Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/levizwannah/pesapal-sdk-php)[ Packagist](https://packagist.org/packages/levizwannah/pesapal-sdk-php)[ RSS](/packages/levizwannah-pesapal-sdk-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (1)Versions (6)Used By (0)

Pesapal SDK for PHP
===================

[](#pesapal-sdk-for-php)

A fluent, elegant, and extensible PHP SDK for integrating with **Pesapal API 3.0**. Designed with SOLID principles to provide a clean and intuitive developer experience.

Features
--------

[](#features)

- **Fluent Interface**: Chain methods for a readable and expressive syntax.
- **Automatic Token Management**: Handled internally; you never have to worry about expiring tokens.
- **Environment Switching**: Seamless toggle between Sandbox and Live environments.
- **Object-Oriented**: Uses `OrderData` and `BillingAddress` objects to structure your data.
- **PSR-Compliant**: Built for modern PHP applications.

---

Installation
------------

[](#installation)

Install via Composer:

```
composer require levizwannah/pesapal-sdk-php
```

---

Configuration
-------------

[](#configuration)

Initialize the SDK with your credentials. You can pass these directly or load them from your environment variables.

```
use LeviZwannah\PesapalSdk\Pesapal;

$config = [
    'env' => 'sandbox', // or 'live'
    'key' => 'YOUR_CONSUMER_KEY',
    'secret' => 'YOUR_CONSUMER_SECRET',
];

// Create a new instance
$pesapal = Pesapal::new($config);
```

> **Note:** when `env` is set to `sandbox`, the SDK automatically uses the test URLs. For production, set it to `live`.

---

Usage Guide
-----------

[](#usage-guide)

### 1. Registering an IPN URL (One-time Setup)

[](#1-registering-an-ipn-url-one-time-setup)

Pesapal API 3.0 **requires** you to register an Instant Payment Notification (IPN) URL. You must do this *before* placing any orders. You only need to do this once (or whenever your URL changes).

```
try {
    $pesapal->registerIpn("https://your-domain.com/ipn-callback", "POST");

    // Check if successful
    if($pesapal->accepted()){
        $ipnId = $pesapal->response()->ipn_id;
        echo "IPN Registered. ID: " . $ipnId;
        // SAVE THIS ID! You need it for every order.
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

### 2. Processing a Payment

[](#2-processing-a-payment)

The SDK uses a fluent builder pattern for orders.

#### Step A: Customer Billing Details

[](#step-a-customer-billing-details)

```
use LeviZwannah\PesapalSdk\BillingAddress;

$billing = (new BillingAddress())
    ->email("john.doe@example.com")
    ->phone("0722000000")
    ->firstName("John")
    ->lastName("Doe")
    ->countryCode("KE");
   // ->city, ->street, etc. are also available
```

#### Step B: Order Details

[](#step-b-order-details)

```
use LeviZwannah\PesapalSdk\OrderData;

$order = (new OrderData())
    ->id("ORD-" . time()) // Your unique Order ID
    ->amount(100.00)
    ->currency("KES")
    ->description("Payment for Order #1234")
    ->callback("https://your-domain.com/payment-callback") // Where user is returned
    ->ipnId($savedIpnId) // The ID you got from Step 1
    ->billingAddress($billing);
```

#### Step C: Submit the Order

[](#step-c-submit-the-order)

```
try {
    $response = $pesapal->order($order);

    if ($pesapal->accepted()) {
        // Success! Redirect the user to Pesapal
        $redirectUrl = $response->response()->redirect_url;
        $orderTrackingId = $response->response()->order_tracking_id;

        // redirect($redirectUrl);
    } else {
        // Handle errors
        $error = $pesapal->error();
        echo "Failed: " . $error->message;
    }

} catch (Exception $e) {
    // Handle SDK or Network errors
    var_dump($e->getMessage());
}
```

---

### 3. Handling the Callback (User Redirect)

[](#3-handling-the-callback-user-redirect)

When the user returns to your website, Pesapal appends `OrderTrackingId` and `OrderMerchantReference` to your callback URL. verify the transaction status immediately.

```
$trackingId = $_GET['OrderTrackingId'];
$merchantRef = $_GET['OrderMerchantReference'];

$pesapal->status($trackingId);

if ($pesapal->response()->payment_status_description == 'Completed') {
    // Payment Successful!
    // Give value to the user
} elseif ($pesapal->response()->payment_status_description == 'Failed') {
    // Payment Failed
}
```

---

### 4. Handling IPN (Server-to-Server)

[](#4-handling-ipn-server-to-server)

Pesapal will hit your registered IPN URL asynchronously to update the status. You **must** acknowledge this request.

```
// In your IPN script (e.g., ipn.php)

// 1. Get the data
$trackingId = $_GET['OrderTrackingId'];
$notificationType = $_GET['OrderNotificationType'];

// 2. Verify status from Pesapal (Security Best Practice)
$pesapal->status($trackingId);
$status = $pesapal->response()->payment_status_description;

// 3. Update your database
if ($status == 'Completed') {
    // Mark order as paid in DB
}

// 4. Acknowledge receipt to Pesapal
// This sends the required JSON response: {"status": 200, ...}
$pesapal->received();
```

---

SDK Architecture &amp; Extensibility
------------------------------------

[](#sdk-architecture--extensibility)

This SDK is built with **SOLID** principles to ensure it is easy to maintain and extend.

### Fluent Data Objects

[](#fluent-data-objects)

Both `OrderData` and `BillingAddress` use the `PropertyTrait`. This allows you to set any property as a method call or a direct property access.

```
// Method call (Fluent)
$order->amount(500);

// Direct Access
$order->amount = 500;
```

### The `Pesapal` Class

[](#the-pesapal-class)

The main `LeviZwannah\PesapalSdk\Pesapal` class acts as a facade for the API. It handles:

- **Authentication**: It automatically requests and caches the Bearer Token. you never need to call `token()` manually unless debugging.
- **HTTP Client**: Uses Guzzle internally for robust HTTP handling.

### Response Handling

[](#response-handling)

Every API request updates the `$pesapal->response` public property.

- `$pesapal->response()`: Returns the raw object from Pesapal.
- `$pesapal->accepted()`: Returns `true` if the API HTTP status was 200.
- `$pesapal->error()`: Helper to get error details if a request failed.

License
-------

[](#license)

MIT License. Free to use and modify.

###  Health Score

32

—

LowBetter than 71% of packages

Maintenance56

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~109 days

Total

5

Last Release

784d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/792dbf4e6a5f6dac197f6567f0300fb08b82c7fbc21675f580a50741296f782c?d=identicon)[levizwannah](/maintainers/levizwannah)

---

Top Contributors

[![levizwannah](https://avatars.githubusercontent.com/u/56189552?v=4)](https://github.com/levizwannah "levizwannah (10 commits)")

---

Tags

pesapalpesapal-phppesapal-sdk-phpphp

### Embed Badge

![Health badge](/badges/levizwannah-pesapal-sdk-php/health.svg)

```
[![Health](https://phpackages.com/badges/levizwannah-pesapal-sdk-php/health.svg)](https://phpackages.com/packages/levizwannah-pesapal-sdk-php)
```

###  Alternatives

[chargebee/chargebee-php

ChargeBee API client implementation for PHP

768.0M9](/packages/chargebee-chargebee-php)[imdhemy/google-play-billing

Google Play Billing

491.3M5](/packages/imdhemy-google-play-billing)[bitpay/sdk

Complete version of the PHP library for the new cryptographically secure BitPay API

42337.5k4](/packages/bitpay-sdk)[buckaroo/sdk

Buckaroo payment SDK

12189.1k9](/packages/buckaroo-sdk)[contica/facturador-electronico-cr

Un facturador de código libre para integrar facturación electrónica en Costa Rica a un proyecto PHP

2128.8k](/packages/contica-facturador-electronico-cr)[karson/mpesa-php-sdk

172.2k](/packages/karson-mpesa-php-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
