Installing Pesapal Sdk: Kickstart Your Payment Integration | Katorymnd Freelancer

Installing Pesapal Sdk: Kickstart Your Payment Integration

Date: 2024-11-18 || Views: 3,583

Kickstart Your Payment Integration: Installing and Setting Up the Pesapal SDK

An essential guide for beginners to get the SDK up and running smoothly.


Introduction

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.

Prerequisites

Before you begin, ensure you have the following:

Step 1: Install Composer (If Not Already Installed)

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

 

Step 2: Create a New PHP Project (Optional)

If you're starting a new project, create a directory for it:

mkdir pesapal-integration
cd pesapal-integration

Step 3: Install the Pesapal PHP SDK

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.

Step 4: Include the Autoloader

In your PHP script, include Composer's autoloader to access the SDK classes:

require_once __DIR__ . '/vendor/autoload.php';

 

Step 5: Obtain Pesapal API Credentials

Sign up for a merchant account on the Pesapal Dashboard to get your:

  1. Consumer Key
  2. Consumer Secret

These credentials are essential for authenticating your API requests.

Step 6: Initialize the Pesapal SDK

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);

 

Step 7: Set Up Payment Details

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.');

        }

    }

 

 

Step 8: Generate the Payment URL

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

 

Step 9: Redirect the User or Embed the Payment Page

You can either redirect the user to the payment page or embed it using an iframe.

Redirect:

header('Location: ' . $iframeSrc);
exit;

Step 10: Handle Payment Notifications

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.

Step 11: Test the Integration

Perform test transactions using the Pesapal demo environment to ensure everything works as expected. Check that:

  1. Payments are processed correctly.
  2. IPN notifications update your system.
  3. Error handling works properly.

Conclusion

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.

Next Steps

  1. Explore Advanced Features: Delve into recurring payments, refunds, and detailed transaction queries.
  2. Move to Production: Once satisfied with testing, switch the $environment variable to 'production' and update your credentials.
  3. Stay Updated: Keep an eye on the Pesapal SDK GitHub Repository for updates and new features.

Additional Resources

  1. Pesapal SDK Documentation: Detailed guides and API references.
  2. Submit an Issue: Report bugs or request features.


Learn how rich snippets can boost your site's SERP visibility....


Discover how long tail keywords can boost SEO and conversions....


Explore Katorymnd's web design innovations in Uganda, showcasing custom solutions,...


Glimpses of Greatness Crafted by Katorymnd

Dive into the journeys of clients I've empowered.
Click any project below to explore the results - each one a story of transformation.

pawaPay Java SDK - Payment Integration

pawaPay Java SDK: Seamless enterprise mobile money integration for Java applications. Features robust typing, thread-safe execution, and reliable transaction handling.

pawaPay Python SDK - Payment Integration

pawaPay Python SDK: Seamless enterprise mobile money integration for Python applications. Features robust typing and asynchronous transaction handling.

pawaPay Node.js SDK, Payments

pawaPay Node.js SDK: Enterprise mobile money integration for Node.js & TypeScript. Strictly typed, async wrapper with simple domain-based licensing.

Clean My Mind - A Quiet Release

A privacy-first web ritual, no signup, say one sentence and let it go. Built with vanilla JavaScript, local-only storage, and focused on presence rather than analytics.