To create a simple WordPress plugin to collect payments using Lipa Na Mpesa Online API, you will need to follow these steps:
-
- 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.
- Next, create a new folder in the
wp-content/pluginsdirectory of your WordPress installation and name itlipa-na-mpesa.
3. Create a lipa-na-mpesa.php file in the plugin directory and add the following code at the top:
- 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 = ' ';
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');
-
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.
-
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.
