Here’s a general outline of the steps you’ll need to follow:
- First, you’ll need to sign up for a Safaricom developer account and obtain an API key. You can do this by visiting the Safaricom developer portal and clicking on the “Sign Up” button.
- Next, you’ll need to install and activate the WooCommerce plugin on your WordPress website.
- Once WooCommerce is installed and activated, you’ll need to create a new plugin to handle the C2B functionality. You can do this by creating a new folder in the “wp-content/plugins” directory of your WordPress installation, and then creating a new PHP file inside that folder with the following code:
<?php
/*
Plugin Name: WooCommerce C2B Payments
Plugin URI: https://example.com/woocommerce-c2b-payments
Description: Accept C2B payments in WooCommerce using the Safaricom API.
Author: Your Name
Version: 1.0
Author URI: https://example.com
*/
function woocommerce_c2b_payments_init() {
// Code to initialize the plugin goes here
}
add_action( 'init', 'woocommerce_c2b_payments_init' );
- Inside the
woocommerce_c2b_payments_initfunction, you’ll need to use the WooCommerce action hooks to trigger the C2B payment process when a user adds a product to their cart and proceeds to checkout. - To initiate the C2B payment, you’ll need to make an HTTP POST request to the
/mpesa/c2b/v2/registerurlendpoint, passing along the following parameters in the request body:
-
ShortCode: The shortcode of the organization initiating the transaction -
ResponseType: The type of response you want to receive. Possible values are “Completed” or “Cancelled” -
ConfirmationURL: The URL to which a confirmation of the transaction will be sent -
ValidationURL: The URL to which a request for validation will be sent
- The Safaricom API will return a response indicating whether the C2B registration was successful or not. If the registration was successful, you’ll need to store the
ConversationIDin the WooCommerce order as a meta field. This will be used later to confirm the payment. - When the user completes the payment, Safaricom will send a request to the
ConfirmationURLwith details of the transaction. You’ll need to handle this request by verifying that theTransactionTypeis “PayBill” and theResultCodeis “0”. If these conditions are met, you’ll need to use theConversationIDstored in the WooCommerce order to confirm the payment by making an HTTP POST request to the/mpesa/c2b/v1/simulateendpoint, passing along the following parameters in the request body:
-
ShortCode: The shortcode of the organization initiating the transaction -
CommandID: The type of transaction being confirmed. Possible values are “Confirmation” or “Validation” -
Amount: The amount of the transaction -
Msisdn: The phone number of the user in E.164 format - `BillRef
