pawaPay SDK offers secure, user-friendly mobile money integration for PHP, ideal for African e-commerce.

posted 7 min read

pawaPay Payment SDK: Streamline Your Payment Processes in PHP

In the fast-paced world of e-commerce and online transactions, efficiency, security, and simplicity are paramount. Integrating payment solutions can often be a complex and time-consuming process, especially when dealing with multiple payment methods across different regions. The pawaPay Payment SDK emerges as a robust solution, specially tailored for PHP applications, aiming to streamline the integration of pawaPay's Mobile Money payment solutions. This lightweight, easy-to-use SDK encapsulates powerful functionalities into a developer-friendly package, enabling seamless payment processes within your applications.

What is pawaPay?

pawaPay is a mobile money payment platform designed to empower businesses to seamlessly send and receive payments across various African countries using mobile wallets. With over 300 million mobile money users in Africa, pawaPay taps into this expansive ecosystem, providing rapid settlements, eliminating chargebacks, and ensuring secure transaction processing—all accessible from a unified dashboard. pawaPay offers integrations with all major mobile money operators, delivering a scalable and efficient solution for businesses aiming to leverage the burgeoning mobile money market in Africa.

Why Mobile Money in Africa?

Mobile money has revolutionized financial transactions in Africa, where traditional banking infrastructure is limited. It allows users to perform financial transactions using their mobile phones, without needing a bank account. This has significantly increased financial inclusion and has become the preferred method of payment for many Africans. By integrating mobile money into your applications, you open your business to a vast and growing market.

Introducing the pawaPay Payment SDK

The pawaPay Payment SDK is a secure and straightforward way to integrate pawaPay's mobile money payment services into PHP applications. By handling the complexities of direct API calls and providing a set of easy-to-implement methods, this SDK allows developers to efficiently process payments without needing deep expertise in payment systems.

Key Benefits

  • Simplified Integration: Reduce development time with an SDK that abstracts complex API interactions.
  • Enhanced Security: Leverage built-in security features adhering to the latest standards.
  • Comprehensive Functionality: Access a wide range of payment operations through simple methods.

Key Features of the pawaPay Payment SDK

Easy to Use

With comprehensive documentation and ready-to-use code snippets, integrating the pawaPay SDK into your existing PHP projects is straightforward. The SDK reduces the complexity involved in coding for mobile money payment systems, allowing you to focus on other critical aspects of your application.

Security at Its Core

Built with security as a priority, the SDK adheres to the latest standards in data encryption, validations, and other security protocols to ensure that all transactions are protected against fraud and breaches.

Comprehensive Payment Functions

Whether you're looking to initiate deposits, manage payouts, process refunds, or check transaction statuses, the SDK covers all bases, providing you with the tools you need to manage various mobile money payment operations efficiently.

Cross-Network Compatibility

The SDK supports integration with all major mobile money operators in Africa, ensuring that your application can process payments regardless of the user's mobile money provider.

System Requirements

Before you begin, ensure that your environment meets the following system requirements:

  • PHP Version: 8.0 or higher
  • Composer: PHP dependency manager installed
  • cURL: Required for making HTTP requests
  • OpenSSL: For secure HTTPS connections
  • JSON Extension: Enabled in PHP for working with JSON data
  • SSL Certification: A valid SSL certificate on your server
  • Web Server: Apache 2.4, LiteSpeed V8.1, or any modern server capable of running PHP

Installation and Setup

Step 1: Install the SDK via Composer

Begin by installing the SDK using Composer:

composer require katorymnd/pawa-pay-integration

Step 2: Configure Your API Keys

After installation, you need to configure your API keys provided by pawaPay. You can set them in your application's environment variables.

require_once 'vendor/autoload.php';

use Dotenv\Dotenv;
use Katorymnd\PawaPayIntegration\Api\ApiClient;
use Katorymnd\PawaPayIntegration\Utils\Helpers;
use Katorymnd\PawaPayIntegration\Utils\Validator;
use Katorymnd\PawaPayIntegration\Utils\FailureCodeHelper;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Whoops\Run;
use Whoops\Handler\PrettyPageHandler;

// Initialize Whoops error handler for development
$whoops = new Run();
$whoops->pushHandler(new PrettyPageHandler());
$whoops->register();

// Load the environment variables from the .env file
$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();


// Set the environment and SSL verification based on the production status
$environment = getenv('ENVIRONMENT') ?: 'sandbox'; // Default to sandbox if not specified
$sslVerify = $environment === 'production';  // SSL verification true in production

// Dynamically construct the API token key
$apiTokenKey = 'PAWAPAY_' . strtoupper($environment) . '_API_TOKEN';

// Get the API token based on the environment
$apiToken = $_ENV[$apiTokenKey] ?? null;


if (!$apiToken) {
    echo json_encode([
        'success' => false,
        'errorMessage' => 'API token not found for the selected environment.'
    ]);
    exit;
}

// Initialize Monolog for logging
$log = new Logger('pawaPayLogger');
$log->pushHandler(new StreamHandler(__DIR__ . '/../logs/payment_success.log', \Monolog\Level::Info));
$log->pushHandler(new StreamHandler(__DIR__ . '/../logs/payment_failed.log', \Monolog\Level::Error));

// Create a new instance of the API client with SSL verification control
$pawaPayClient = new ApiClient($apiToken, $environment, $sslVerify);

Replace 'YOUR_PAWAPAY_API_KEY' with your actual API key provided by pawaPay in your '.env file.

Using the SDK

Initiating a Payment

To initiate a payment, you can use the initiateDeposit method. Here's how:





// Initialize the API client
$pawaPayClient = new ApiClient($apiToken, $environment, $sslVerify);

// Generate a unique transaction ID (UUID v4)
$transactionId = Helpers::generateUniqueId();

// Define payment details
$amount = '1000'; // Payment amount in KES (Kenyan Shilling)
$currency = 'KES'; // Currency code
$correspondent = 'MPESA_KEN'; // Correspondent ID for the MPESA network
$recipientMsisdn = '254712345678'; // Recipient's phone number

// Custom transaction description
$description = 'Payment for invoice -1234';

// Optional metadata for the transaction
$metadata = [
    'order_id' => '1234',
    'customer_id' => '5678',
];

// Step 1: Validate the amount
$validatedAmount = Validator::symfonyValidateAmount($amount);

// Step 2: Validate the description
$validatedDescription = Validator::validateStatementDescription($description);

// Step 3: Validate metadata if provided
if (!empty($metadata)) {
    Validator::validateMetadataItemCount($metadata);
}

// Step 4: Initiate the payment
$response = $pawaPayClient->initiatePayment(
    $transactionId,
    $validatedAmount,
    $currency,
    $correspondent,
    $recipientMsisdn,
    $validatedDescription,
    $metadata
);

// Step 5: Check if the response is successful
if ($response['status'] === 200) {
    // Payment was initiated successfully
    $log->info('Payment initiated successfully', [
        'transactionId' => $transactionId,
        'response' => $response['response'],
    ]);
    echo "Payment initiation successful. Transaction ID: $transactionId";
} else {
    // Payment initiation failed; handle the error
    $log->error('Payment initiation failed', [
        'transactionId' => $transactionId,
        'error' => $response->getErrorMessage(),
    ]);
    echo "Payment initiation failed. Error: " . $response->getErrorMessage();
}


In this example, we initiate a payment of 1000 KES to a recipient on the MPESA network. We check if the response is successful and handle it accordingly.

Checking Transaction Status

To check the status of a transaction:


 // Proceed to check the transaction status
        $statusResponse = $pawaPayClient->checkTransactionStatus($transactionId, 'deposit');

        if ($statusResponse['status'] === 200) {
            $depositInfo = $statusResponse['response'][0]; // Get the deposit info
            $depositStatus = $depositInfo['status'];

Replace 'TRANSACTION_ID_RECEIVED' with the transaction ID you received when initiating the payment.

Handling Errors

The SDK is designed to handle errors gracefully. Here's how you might handle exceptions:

try {
     $response = $pawaPayClient->initiateDeposit(
        $depositId,
        $validatedAmount,
        $currency,
        $mno,
        $payerMsisdn,
        $validatedDescription,
        $metadata
    );

    // Process response
} catch (Exception $e) {
    // Log error details
    error_log('Payment initiation error: ' . $e->getMessage());
    // Inform the user
    echo "An error occurred while processing your payment. Please try again.";
}

Using try-catch blocks allows you to catch exceptions thrown by the SDK and handle them appropriately.

Best Practices

  • Secure API Keys: Never expose your API keys in your code repositories. Use environment variables or secure configuration files.
  • Validate User Input: Always validate and sanitize user input to prevent injection attacks.
  • Error Logging: Implement robust error logging to aid in troubleshooting.
  • Transaction Monitoring: Regularly monitor transactions to detect any suspicious activity.

Use Cases

E-commerce Platforms

Integrate seamless payment solutions that cater to both sellers and buyers. With pawaPay, customers can pay using their preferred mobile money provider, increasing conversion rates.

Marketplaces

Facilitate secure and reliable transactions between multiple parties with ease. The SDK supports splitting payments and managing payouts to different vendors.

Donation Platforms

Allow donors to contribute easily via mobile money, broadening your reach to users without traditional banking services.

Conclusion

The pawaPay Payment SDK for PHP simplifies the integration of mobile money payment solutions, enabling businesses to tap into the vast African market easily. By abstracting the complexities of payment processing and providing robust security features, the SDK allows developers to focus on building great applications while ensuring seamless and secure transactions.

Whether you're an e-commerce platform, a subscription service, or a marketplace, integrating pawaPay can significantly enhance your payment processing capabilities, reduce development time, and provide a better user experience.

Get Started Today

Visit the pawaPay Payment SDK GitHub Repository to access the SDK, documentation, and examples. Start integrating and unlock new opportunities in the African mobile money ecosystem.

References

 


If you read this far, tweet to the author to show them you care. Tweet a Thanks
This looks like a great solution for businesses looking to enter the African mobile money ecosystem! I’m curious, how does the SDK handle handling different currencies from multiple regions? Can you easily switch between them during transactions?
yes, depending on what your `mnoCorrespondents` your pawaPay merchant account assigns you. The logic is that depending on the user's chosen country, the SDK will retrieve the corresponding local currency acceptable by pawaPay accordingly.

I created a small demonstration in the form of a donation page  `https://katorymnd.com/donate`  choose `mobile money`  and select different countries and you will observe what the  SDK does, it's in production mode, so don't hit  `confirmation` unless you intend to.

More Posts

Streamline WhatsApp bot development with WhatsApp API PHP SDK

Whapi Cloud API - Nov 28

Learn how to build a user-friendly, conversational Telegram bot with python

Astra Bertelli - Apr 30

Program does not contain a static 'main' method suitable for an entry point

Rafael Borges Batist - Feb 23

Tips and Tricks in article formatting for Coderlegion

James Dayal - Feb 9

Enhancing User Experience in Next.js: Adding a Seamless Loading Indicator

George Isiguzo - Jun 4
chevron_left