Date: 2024-11-18 || Views: 291
An essential guide for beginners to get the SDK up and running smoothly.
Integrating a secure and efficient payment system is crucial for any modern PHP application. The Pesapal PHP SDK offers a seamless way to incorporate Pesapal's payment solutions into your projects. This guide will walk you through the installation and setup process, ensuring you're ready to start accepting payments with minimal hassle.
Before you begin, ensure you have the following:
Composer is a dependency manager for PHP that simplifies package installation. If you haven't installed Composer yet, download it from the official website or run the following command in your terminal:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"
Move the composer.phar
file to a directory that's in your system's PATH:
mv composer.phar /usr/local/bin/composer
If you're starting a new project, create a directory for it:
mkdir pesapal-integration
cd pesapal-integration
Use Composer to install the Pesapal SDK:
composer require katorymnd/pesapal-php-sdk
This command downloads the SDK and its dependencies into your project's vendor
directory.
In your PHP script, include Composer's autoloader to access the SDK classes:
require_once __DIR__ . '/vendor/autoload.php';
Sign up for a merchant account on the Pesapal Dashboard to get your:
These credentials are essential for authenticating your API requests.
Create an instance of the Pesapal client using your credentials:
// Initialize PesapalConfig and PesapalClient
$configPath = __DIR__ . '/../pesapal_dynamic.json';
$config = new PesapalConfig($consumerKey, $consumerSecret, $configPath);
$environment = 'sandbox';
$sslVerify = false; // Enable SSL verification for production
$clientApi = new PesapalClient($config, $environment, $sslVerify);
Prepare the payment information:
// Prepare order data
$orderData = [
"id" => $merchantReference,
"currency" => $data['currency'],
"amount" => (float) $data['amount'],
"description" => $data['description'],
"callback_url" => "https://www.example.com/payment-callback",
"notification_id" => $notificationId,
"branch" => "Katorymnd Freelancer",
"payment_method" => "card", // Restrict payment option to CARD only
"billing_address" => []
];
// Map the billing details from $data['billing_details'] to the expected keys in $orderData['billing_address']
$billingDetails = $data['billing_details'];
// Ensure country code is uppercase
$countryCode = isset($billingDetails['country']) ? strtoupper($billingDetails['country']) : '';
$orderData['billing_address'] = array_merge($orderData['billing_address'], [
"country_code" => $countryCode,
"first_name" => isset($billingDetails['first_name']) ? $billingDetails['first_name'] : '',
"middle_name" => '', // Assuming no middle name is provided
"last_name" => isset($billingDetails['last_name']) ? $billingDetails['last_name'] : '',
"line_1" => isset($billingDetails['address_line1']) ? $billingDetails['address_line1'] : '',
"line_2" => isset($billingDetails['address_line2']) ? $billingDetails['address_line2'] : '',
"city" => isset($billingDetails['city']) ? $billingDetails['city'] : '',
"state" => isset($billingDetails['state']) ? $billingDetails['state'] : '',
"postal_code" => isset($billingDetails['postal_code']) ? $billingDetails['postal_code'] : ''
]);
// Include contact information provided
if (!empty($data['email_address'])) {
$orderData['billing_address']['email_address'] = $data['email_address'];
}
if (!empty($data['phone_number'])) {
// Use libphonenumber to parse and format the phone number into national format
$phoneUtil = PhoneNumberUtil::getInstance();
try {
// Parse the phone number in international format
$numberProto = $phoneUtil->parse($data['phone_number'], null);
// Format the number into national format (without country code)
$nationalNumber = $phoneUtil->format($numberProto, PhoneNumberFormat::NATIONAL);
// Remove any spaces, dashes, or parentheses
$nationalNumber = preg_replace('/[\s()-]/', '', $nationalNumber);
$orderData['billing_address']['phone_number'] = $nationalNumber;
} catch (NumberParseException $e) {
// Log the error
$log->error('Phone number parsing failed', [
'error' => $e->getMessage(),
'phone_number' => $data['phone_number']
]);
// Return an error response
throw new PesapalException('Invalid phone number format.');
}
}
Request a payment URL from Pesapal:
// Obtain a valid access token
$accessToken = $clientApi->getAccessToken();
if (!$accessToken) {
throw new PesapalException('Failed to obtain access token');
}
// Submit order request to Pesapal
$response = $clientApi->submitOrderRequest($orderData);
//The response will have all the details including the payment link which you can use in the iframe
You can either redirect the user to the payment page or embed it using an iframe.
Redirect:
header('Location: ' . $iframeSrc);
exit;
Set up an endpoint to handle Instant Payment Notifications (IPN) from Pesapal:
// callback.php
$pesapal->listenIPN(function($notification) {
// Verify the payment status
$transactionStatus = $notification->status;
$transactionReference = $notification->reference;
$trackingId = $notification->tracking_id;
// Update your order records accordingly
});
Ensure your callback_url
(from Step 7) points to this script.
Perform test transactions using the Pesapal demo environment to ensure everything works as expected. Check that:
You've successfully installed and set up the Pesapal PHP SDK in your application. With this integration, you can now offer a secure and efficient payment option to your users. For further customization and advanced features, explore the SDK's comprehensive documentation.
$environment
variable to 'production'
and update your credentials.Discover Katorymnd's extensive web design services in Uganda, from bespoke...
Explore advanced features of the Pesapal PHP SDK: recurring payments,...
Discover how AI is revolutionizing web development, from automated coding...
Here is how I helped my clients reach their goals. Click on the portfolio websites.
A VS Code extension to manage and synchronize your remote and local files efficiently, supporting FTP, SFTP, SSH, WebDAV, and Google Drive connections.
A WordPress plugin that introduces a dynamic and interactive layer to your site, allowing users to express their feelings and thoughts on your content through a variety of reaction options.
The pawaPay SDK provides seamless mobile money integration into your PHP applications, enabling smooth transaction processing with powerful API features.
© Copyright 2025 - Katorymnd Web Solutions - All Rights Reserved. Registered with Uganda Registration Services Bureau.