Create a simple wordpress plugin to collect payments using lipa na mpesa online API

To create a simple WordPress plugin to collect payments using Lipa Na Mpesa Online API, you will need to follow these steps:

 

    1. First, you need to create a developer account on the Mpesa API Portal (https://developer.safaricom.co.ke/). This will give you access to the API documentation and allow you to create your own API keys.
    2. Next, create a new folder in the wp-content/plugins directory of your WordPress installation and name it lipa-na-mpesa.

  1.  

3. Create a lipa-na-mpesa.php file in the plugin directory and add the following code at the top:

				
					<?php /*
Plugin Name: Lipa Na Mpesa
Description: A plugin to collect payments using Lipa Na Mpesa Online API
Version: 1.0
Author: Your Name
*/

				
			
  1. In the same file, add the following code to create a shortcode that you can use to display the payment form on your website:
 
				
					function lipa_na_mpesa_form_shortcode() {
    $output = '
'; $output .= '
'; $output .= '

'; $output .= ''; $output .= '
'; return $output; } add_shortcode('lipa_na_mpesa_form', 'lipa_na_mpesa_form_shortcode');

5. To handle the payment request, you will need to add a function that processes the form submission and sends a request to the Mpesa API. Add the following code to your plugin file:

				
					function lipa_na_mpesa_process_payment() {
    if (isset($_POST['amount'])) {
        $amount = sanitize_text_field($_POST['amount']);
        // Send request to Mpesa API using your API keys and other required parameters
    }
}
add_action('init', 'lipa_na_mpesa_process_payment');

				
			
  1. You will also need to include the Mpesa API PHP library in your plugin. You can find the library and instructions for installing it in the Mpesa API documentation.

  2. To finalize the payment process, you will need to handle the response from the Mpesa API and display a success or error message to the user. You can do this by adding a function that processes the API response and displays the appropriate message.

				
					function lipa_na_mpesa_handle_response($response) {
    if ($response['success']) {
        // Payment was successful, display success message
    } else {
        // Payment failed, display error message
    }
}

				
			

That’s it! Your WordPress plugin is now ready to collect payments using Lipa Na Mpesa Online API. You can now use the [lipa_na_mpesa_form] shortcode to display the payment form on your website and start accepting payments.

What's your reaction?
0Smile0Shocked0Cool0Sad0Laugh