BURST DARK LOGO
Get a Free Quote

Integrating M-Pesa into Your Website Using PHP: Step-by-Step Guide (Part 2)

In our previous post, "How to Integrate M-Pesa into Your Website," we explored the fundamentals of incorporating this popular mobile payment platform into your online platform. We discussed setting up your business on the M-Pesa G2 Portal, obtaining API credentials, and going live with your M-Pesa integration. Now, in Part 2 of our series, we'll delve deeper into integrating M-Pesa with PHP, and we'll provide you with step-by-step instructions to make the process seamless.

Mpesa API Integration: Step-by-Step Guide to Integrating Lipa na Mpesa Online

Prerequisites

Before you begin with the PHP integration, ensure you have completed the following steps covered in Part 1 of this series:

  1. Obtained M-Pesa API Credentials: You should have received your API credentials, including the Live App's Secret Code and Consumer Keys.
  2. M-Pesa Paybill or BuyGoods Number: Your business should have a valid Paybill or BuyGoods number.

If you haven't completed these initial steps, we recommend you start with our previous post and come back to this advanced PHP integration guide once you have the necessary prerequisites.

Integrating M-Pesa with PHP: Step-by-Step Guide

Once you have your M-Pesa API credentials and a valid Paybill or BuyGoods number, you're ready to dive into PHP integration. Here's how you can do it:

Step 1: Setting Up Your PHP Environment

Ensure that your web server supports PHP. You should have PHP version 7 or higher installed. Most web hosting providers already include PHP by default.

Step 2: Choose Your Integration Approach

You have two integration approaches, one of which we'll discuss in this guide:

  • Custom Integration: If you prefer more control over your integration, you can build your custom solution. This approach is more flexible but requires more development effort.
  • Using the Safaricom Daraja API Library: This library simplifies the integration process and provides predefined functions and methods for working with M-Pesa. It's an excellent choice for developers who want an efficient solution. To use the Daraja library, follow the instructions below:

Step 3: Get the Safaricom Daraja API Library

  • Visit the Safaricom Daraja API Documentation: Before you start, visit the official Safaricom Daraja API documentation to get an understanding of the library's capabilities and functions.
  • Download the Library: Access the Safaricom Daraja API library by visiting our official repository on GitHub, Burst-Digital Daraja API Repository. Download the library files and include them in your PHP project.
  • Include the Library in Your Project: After downloading the library, include it in your PHP project by copying the necessary files to your project directory.

Step 4: Writing the PHP Code with the Safaricom Daraja API

Now, let's provide an example of how to initiate an M-Pesa payment request using the Safaricom Daraja API. Please note that we'll use arbitrary values as placeholders for your actual credentials. Make sure to replace these with your real credentials before implementing this in a live environment.

PHP
// Include the Daraja API Library
require_once('path/to/Daraja.php');

// Initialize Daraja with your credentials
$daraja = new Daraja([
    'consumerKey' => 'your-consumer-key',
    'consumerSecret' => 'your-consumer-secret',
    'shortcode' => 'your-shortcode',
    'lipaNaMpesaOnlinePasskey' => 'your-passkey',
    'lipaNaMpesaOnlineShortcode' => 'your-lipa-na-mpesa-shortcode',
]);

// Construct the payment request
$lipaNaMpesa = $daraja->lipaNaMpesaOnline([
    'BusinessShortCode' => 'your-business-shortcode',
    'Amount' => '1000', // Specify the amount to be paid
    'PartyA' => '2547xxxxxxx', // Customer's phone number
    'PartyB' => 'your-paybill-number',
    'PhoneNumber' => '2547xxxxxxx', // Customer's phone number
    'CallBackURL' => 'https://your-callback-url.com', // Replace with your callback URL
    'AccountReference' => 'your-account-reference',
    'TransactionDesc' => 'Payment for Order 123',
    'TransactionType' => 'CustomerPayBillOnline',
]);

// Send the request
$response = $daraja->execute($lipaNaMpesa);

// Handle the response
if ($response->getResponseCode() === '0') {
    // Payment request was successful
    $checkoutRequestID = $response->getCheckoutRequestID();
    $responseDescription = $response->getResponseDescription();
    // You can now redirect the customer to the payment page or display a success message.
} else {
    // Payment request failed
    $errorCode = $response->getResponseCode();
    $errorMessage = $response->getResponseDescription();
    // Handle the error as needed.
}

In this step, we've initialized the Daraja API with your credentials, constructed the payment request, sent the request, and handled the response. If the response code is '0', it means the payment request was successful, and you can proceed accordingly. If not, you should handle any errors that occur.

This step allows you to kickstart M-Pesa payments from your PHP application seamlessly.

Step 5: Handling M-PESA Callbacks

One of the crucial parts of integrating M-Pesa with your PHP application is handling callbacks. Callbacks are essential to ensure that your application receives transaction details and updates in real-time.

To handle callbacks, follow these steps:

Step 5.1: Create a Callback Handling Script

You should create a new PHP file dedicated to handling callbacks. Let's name it mpesa_callback.php. This file will receive transaction data from M-Pesa and process it.

Step 5.2: Verify the Callback

When M-Pesa sends a callback to your URL, you must first verify the authenticity of the callback to ensure it's from a legitimate source. Here's a basic example of how you can verify the callback using the Daraja API:

PHP
// Include the Daraja API Library
require_once('path/to/Daraja.php');

// Initialize Daraja with your credentials
$daraja = new Daraja([
    'consumerKey' => 'your-consumer-key',
    'consumerSecret' => 'your-consumer-secret',
]);

// Get the callback data
$callbackData = file_get_contents('php://input');

// Verify the callback
$verified = $daraja->verifyCallback($callbackData);

if ($verified) {
    // The callback is valid; you can proceed to process the transaction.
} else {
    // The callback is not valid; ignore it or log the issue for investigation.
}

Step 5.3: Process the Callback Data

Once you've verified the callback, you can proceed to process the transaction data. Extract relevant information, update your database, and perform any necessary actions based on the transaction's status. Here's a simplified example:

PHP
// Decode the callback data
$transaction = json_decode($callbackData);

// Extract information
$transactionType = $transaction->TransactionType;
$transactionAmount = $transaction->TransAmount;
$phoneNumber = $transaction->PhoneNumber;
// ...other relevant data

// Update your database or trigger actions accordingly
// Example: Update the order status if it's a payment confirmation
if ($transactionType === 'Completed') {
    // Update the order in your system
}

Step 5.4: Send a Response to M-Pesa

After processing the callback data, it's a good practice to send a response back to M-Pesa to acknowledge that you've received and handled the callback. This response should be in the format of a 200 OK status.

Here's how you can send a response:

PHP
// Send a response
header('HTTP/1.1 200 OK');

That's it! You've now successfully set up callback handling in your PHP application. The mpesa_callback.php script will handle incoming M-Pesa transaction updates and ensure that your application remains up-to-date with payment statuses.

Step 6: Testing Your M-Pesa Integration

Before deploying your M-Pesa integration to a live environment, it's essential to thoroughly test it to ensure that everything works as expected. Safaricom provides a sandbox environment for testing purposes. Here's how to test your M-Pesa integration:

Step 6.1: Obtain Sandbox Credentials

To access the sandbox, you'll need to request sandbox credentials from Safaricom. These credentials are different from your live credentials and are used exclusively for the sandbox environment. You can usually obtain them by contacting Safaricom's developer support or via their developer portal.

Step 6.2: Configure Your Integration for the Sandbox

Update your PHP code to use the sandbox credentials you've obtained for testing. Modify your Daraja initialization as follows:

PHP
$daraja = new Daraja([
    'consumerKey' => 'sandbox-consumer-key',
    'consumerSecret' => 'sandbox-consumer-secret',
    'shortcode' => 'sandbox-shortcode',
    'lipaNaMpesaOnlinePasskey' => 'sandbox-passkey',
    'lipaNaMpesaOnlineShortcode' => 'sandbox-lipa-na-mpesa-shortcode',
]);

Step 6.3: Use the Sandbox Callback URL

During testing, you should configure the callback URL in your PHP application to point to the sandbox callback handling script (e.g., http://your-server/mpesa_callback.php).

Step 6.4: Simulate Transactions

You can now simulate transactions in the sandbox environment. Create test transactions and submit them through your application. Safaricom provides documentation on how to simulate various transaction scenarios, including successful payments, failed payments, and more.

Step 6.5: Verify Callback Handling

Ensure that the callback handling script, mpesa_callback.php, correctly processes the callback data in the sandbox environment. Verify that the transaction statuses and details are updated as expected in your testing database.

Step 6.6: Monitor Logs and Debug

During testing, keep an eye on your application's logs. Monitor for any errors or unexpected behavior. If you encounter issues, use the logs to help diagnose and debug the problem. The logs can provide valuable information about what went wrong.

Step 7: Deploy to the Live Environment

Once you've successfully tested your M-Pesa integration in the sandbox environment and are confident that it works as expected, you're ready to deploy it to the live environment.

Step 7.1: Update Your PHP Code

Switch your PHP code to use the live credentials you've obtained from Safaricom. Modify your Daraja initialization with your live credentials:

PHP
$daraja = new Daraja([
    'consumerKey' => 'live-consumer-key',
    'consumerSecret' => 'live-consumer-secret',
    'shortcode' => 'live-shortcode',
    'lipaNaMpesaOnlinePasskey' => 'live-passkey',
    'lipaNaMpesaOnlineShortcode' => 'live-lipa-na-mpesa-shortcode',
]);

Step 7.2: Update the Callback URL

Switch the callback URL in your PHP application to point to your live callback handling script.

Step 7.3: Monitor Live Transactions

Once your M-Pesa integration is live, closely monitor all transactions to ensure they're processed correctly. Safaricom provides tools for monitoring and managing live transactions.

With these steps, you can confidently deploy your M-Pesa integration to the live environment and start accepting payments from your customers.

Customizing Your M-PESA PHP Application

While the basic integration process provided in previous steps will cover most scenarios, you may have specific requirements or unique use cases that demand advanced customization. This step will explore how to customize your M-Pesa integration to meet your specific business needs.

Dynamic Transaction Amounts

One common customization is allowing dynamic transaction amounts. In the basic integration, you predefined the transaction amount within your code. To allow users to specify the transaction amount on your website or app, you need to modify your request payload to accept this dynamic input. Here's how you can modify your code:

PHP
// In your PHP code

// Replace the predefined amount with a dynamic one
$amount = $_POST['amount']; // Example: Amount posted from your form

In this case, the transaction amount is dynamically assigned based on user input from a form on your website or app. This customization can be particularly useful for e-commerce sites, allowing customers to enter their desired payment amount.

User-Friendly Payment Descriptions

To make your payment descriptions more user-friendly, you can customize the information presented to your customers during the payment process. By providing clear, concise descriptions, you improve the user experience. Modify your payment request as follows:

PHP
// In your PHP code

// Customize the payment description
$description = "Payment for [Product/Service Name] on [Your Website/App Name]";

Transaction Reference Customization

Customizing transaction references can be beneficial for tracking and reconciliation. This allows you to include order numbers, invoice IDs, or other references in transaction details. Modify your code as shown below:

PHP
// In your PHP code

// Customize the transaction reference
$transactionReference = "Order #[Your Order Number]";

Including your order number in the transaction reference helps with tracking and identifying specific transactions in your records.

Error Handling and User Feedback

A crucial part of customization is providing clear feedback to users when errors occur. Customize your error messages to guide users through the resolution process. Here's an example of how to provide meaningful feedback:

PHP
// In your PHP code

// Handle errors and provide user-friendly messages
if ($errorOccurred) {
    $errorMessage = "Oops! Something went wrong. Please try again or contact our support team for assistance.";
}

By customizing error messages, you can offer users a more transparent and reassuring experience, even in less-than-ideal situations.

Performance Optimization

Customizing your integration can also lead to performance optimization. By fine-tuning your code, you can reduce load times and ensure your M-Pesa integration runs smoothly even during high traffic periods. This may involve caching, asynchronous processing, or other performance enhancements specific to your platform.

Troubleshooting Errors That May Arise

In any integration process, especially one as critical as M-Pesa payments, errors can occur. This step explores how to handle errors gracefully and provides troubleshooting tips to ensure your integration runs smoothly.

Common M-Pesa Integration Errors

  1. Incorrect API Credentials: Always double-check that you've correctly entered your Live App's Secret Code and Consumer Keys. These credentials are crucial for successful communication with the M-Pesa API.
  2. Invalid Paybill or BuyGoods Number: Ensure that the Paybill or BuyGoods number you're using is valid and correctly configured. It must match the one registered with your M-Pesa API account.
  3. Insufficient Funds: If customers encounter issues making payments, it's essential to communicate that their M-Pesa accounts should have sufficient funds to complete transactions.
  4. Server Errors: Like any online service, M-Pesa may experience downtime or temporary issues. Implement error handling for such scenarios to prevent disruptions in your application.
  5. Transaction Reversals: Sometimes, transactions may be reversed, usually due to discrepancies or disputes. Be prepared for these situations and establish a protocol for addressing them.

Handling Errors in PHP Code

To handle errors in your PHP code, you can use try-catch blocks and provide clear feedback to users when issues arise. Here's an example of how to structure error handling:

PHP
// In your PHP code

try {
    // Your M-Pesa API integration code
} catch (Exception $e) {
    // Handle and log the error
    $errorMessage = "Oops! Something went wrong. Please try again or contact our support team for assistance.";
    error_log($e->getMessage());
}

In the event of an error, users will receive a helpful message, and the error will be logged for your review.

Troubleshooting Tips

  1. Check Logs: Regularly review your application's logs for any error messages. These logs can provide insights into the root causes of issues.
  2. Test Environment: If possible, set up a separate testing environment for your integration. This allows you to identify and fix problems before they affect your production environment.
  3. API Documentation: Refer to the official M-Pesa API documentation and Safaricom's developer resources for guidance on troubleshooting and resolving common issues.
  4. Community Support: Engage with the developer community to seek advice and solutions. Online forums and support groups can be valuable resources. Alternatively you can reach out to our team at Burst Digital to help.
  5. Keep APIs Updated: Ensure that you use the latest version of the M-Pesa API. Updates may include bug fixes and improvements.
Integrating M-Pesa with PHP using the Safaricom Daraja API
Integrating M-Pesa with PHP using the Safaricom Daraja API

Conclusion

In conclusion, our comprehensive series on M-Pesa integration with PHP using the Safaricom Daraja API has equipped you with the knowledge and tools to enhance your customers' payment experience. The efficient and secure process we've explored enables you to seamlessly accept mobile payments on your website or application.

At Burst Digital, we understand the importance of a smooth payment process for your online business. That's why we offer this service as an integral part of our e-commerce package. Additionally, if you're looking for a standalone solution, we provide M-Pesa integration at a competitive rate of Kshs 5,000, as well as custom integration services.

Should you have any questions or need assistance with web development or M-Pesa integration, please don't hesitate to reach out. You can contact us via email at hello@burstdigital.co.ke or by giving us a call at 0708865088.

In our next post, we will explore M-Pesa integration in Python and other programming languages. Stay tuned for more valuable insights and solutions to elevate your online payment processes.

Happy Coding!

Share on Faceboook
Share via WhatsApp
Print/ Save as pdf

How useful was this post?

Click on a star to rate it!

Average rating 4.2 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

Tags :
4.2
(5)

Written by:

Related Posts

Wait! Before you go, make sure to grab...
40% OFF OUR WEB BUILDING TOOLS
0
days
0
hours
0
minutes
0
seconds
Exclusive to new users only. Valid May-July.
Facebook
Facebook
Instagram
Tiktok