nyanumba-codes / pesapal
"Laravel Integration Package for Pesapal "
Requires
- php: >=8.0
- guzzlehttp/guzzle: ^7.9
- illuminate/support: ^11.38
This package is auto-updated.
Last update: 2025-01-18 00:45:43 UTC
README
A Laravel package that simplifies integration with the Pesapal payment gateway. This package allows developers to easily handle Pesapal's functionalities such as IPN (Instant Payment Notifications) registration, processing payments, and managing callbacks. Designed to work seamlessly with Laravel projects, including those using Livewire.
Features
- Secure handling of Pesapal API keys.
- IPN registration and callback URL configuration.
- Support for dynamic configuration per client.
- Laravel's route helper support for cleaner implementation.
- Easy-to-use methods for payment processing.
- Fully compatible with Livewire applications.
Installation
Install the package via Composer:
composer require nyanumba-codes/pesapal
Publish the configuration file (Optional):
php artisan vendor:publish --tag="pesapal-config"
The configuration file config/pesapal.php
will be created. Update it with your Pesapal credentials (Already done for you).
Configuration
Add the following variables to your .env
file:
PESAPAL_CONSUMER_KEY=your-consumer-key PESAPAL_CONSUMER_SECRET=your-consumer-secret PESAPAL_CURRENCY=KES PESAPAL_MERCHANT_NAME=your-merchant-name PESAPAL_IPN_URL="${APP_URL}/api/pesapal/ipn" PESAPAL_CALLBACK_URL="${APP_URL}/api/pesapal/callback" PESAPAL_ENV=sandbox
Update the config/pesapal.php
file if you need to customize default settings.
Usage
1. Registering an IPN
IPN stands for Instant Payment Notification. When a payment is made against a transaction, Pesapal will trigger an IPN call to the notification URL related to this transaction. This notification URL is usually located on your servers. These notifications allows you to be alerted in real time whenever there is a status change for any transaction.
Use the Pesapal
class to register an IPN:
use NyanumbaCodes\Pesapal\Pesapal; $pesapal = new Pesapal(); $ipnId = $pesapal->registerIpnUrl();
Depending on the IPN URL that you set up in your .env
file, the URL will be registered accordingly.
2. Get Registered IPNs
This endpoint allows you to fetch all registered IPN URLs for a particular Pesapal merchant account.
use NyanumbaCodes\Pesapal\Pesapal; $pesapal = new Pesapal(); $ipnId = $pesapal->getIpnList();
3. Making a Payment (Submit Order Request)
To initiate a payment:
$amount = 100; $description = 'Order No. 1234'; $notification_id = '123xxx-xxxxxxxx-xxx....' $billing_address = [ "email_address" => auth()->user()->email, "phone_number" => "", "country_code" => "KE", "first_name" => "", "middle_name" => "", "last_name" => "", "line_1" => "", "line_2" => "", "city" => "", "state" => "", "postal_code" => "", "zip_code" => "" ]; $response = $pesapal->submitOrderRequest($amount, $description, $billing_address, $notification_id); return redirect()->away($response['redirect_url']);
Please Note that the $notification_id
represents an IPN URL which Pesapal will send notifications to after payments have been processed.
You are required to register all IPN URLs after which a corresponding notification_id
will be generated. Please refer to the IPN URL registration endpoint in the Pesapal API 3.0 documentation.
4. Handling Callbacks
Define callback routes in your routes/api.php
:
Route::post('pesapal/callback', [PaymentController::class, 'handleCallback'])->name('pesapal.callback');
Create the PaymentController
controller as defined in the routes:
php artisan make:controller PaymentController
In your controller create the function handleCallback()
:
public function handleCallback(Request $request) { // Process callback data /** * Maybe you have saved the data into the Database */ }
5. Get Transaction Status
Once Pesapal redirect your customer to your callback URL and triggers your IPN URL, you need to check the status of the payment using the OrderTrackingId
.
use NyanumbaCodes\Pesapal\Pesapal; $pesapal = new Pesapal(); $response = $pesapal->getTransactionStatus($orderTrackingId);
This tracking ID is a unique order ID taht is generated by Pesapal from the data received in the initial response of the Submitted Order Request when making the payment.
Here is a Sample of the Response:
{ "order_tracking_id": "b945e4af-80a5-4ec1-8706-e03f8332fb04", "merchant_reference": "TEST1515111119", "redirect_url": "https://cybqa.pesapal.com/pesapaliframe/PesapalIframe3/Index/?OrderTrackingId=b945e4af-80a5-4ec1-8706-e03f8332fb04", "error": null, "status": "200" }
From that point it would have been best to store this data into the database so that you may query to check the status of the transaction.
6. Recurring Payments
In the process of making a payment there are extra options that this package has allowed you to add. These are the account_number
and subscription_details
.
account_number
: Customer's identification number known to your system. This can be an invoice number or an account number.subscription_details
: Customer Subscription Object You can pass subscription data to Pesapal allowing a user to setup recurring payment.
The following is a sample of a subscription_details
object in PHP
$subscription_details = [ 'start_date'=>'dd-mm-yyyy', 'end_date'=>'dd-mm-yyyy', 'frequency'=>'DAILY', ];
frequency
: The period billed to the account is set out in the user contract. For instance, if users subscribe to a monthly service. Accepted values include DAILY
, WEEKLY
, MONTHLY
or YEARLY
7. Refund Request
The refund request function allows you to refund a charge that has previously been processed but not yet refunded. Funds will be refunded to the credit / debit card or mobile money wallet that was originally charged.
use NyanumbaCodes\Pesapal\Pesapal; $pesapal = new Pesapal(); $response = $pesapal->refundRequest($confirmation_code, $amount, $username, $remarks);
$confirmation_code
: This refers to payment confirmation code that was returned by the processor$amount
: Amount to be refunded.$username
: Identity of the user who has initiated the refund$remarks
: A brief description on the reason for the refund
8. Order Cancellation
The Order Cancellation Function enables you to revoke a previously placed order request that remains incomplete on our end. This API facilitates the cancellation of orders that have encountered failures or are pending transactions.
use NyanumbaCodes\Pesapal\Pesapal; $pesapal = new Pesapal(); $response = $pesapal->orderCancellation($trackingId);
$trackingId
: This refers to the original Pesapal Order tracking ID that was returned after submitting your order request earlier during the initial submit order request api call. It is similar to the one used to get the transaction status.
Testing
You can test the package in multiple environments:
- Base Laravel Application: Create a controller and use the
Pesapal
class directly to process payments and handle callbacks. - Livewire: Create a Livewire component, inject the
Pesapal
class, and bind payment functionality to Livewire actions. - Inertia: Use Inertia to create Vue or React components and interact with the
Pesapal
class via API routes or Laravel controllers.
Ensure you have a valid Pesapal account and sandbox credentials for testing.
Security
- Credentials are encrypted in the database using Laravel's
Crypt
facade. - Ensure
APP_KEY
in your.env
is set and secure.
Contributions
Contributions, issues, and feature requests are welcome! Feel free to fork the repository and submit pull requests.
License
This package is open-sourced software licensed under the MIT license.
- Author: Steve Nyanumba
- Website: stevenyanumba.com
- YouTube Channel: Nyanumba Codes