PHP CI (CodeIgniter) Payment Gateway Integration
- Shailendra Kadulkar
- 14 July, 2021
Over time, the importance of online payment gateways has increased substantially as digital payments are gaining prominence. In 2021, it is important for an organization to provide faster, more effective, and seamless payment options to its customers/clients to streamline its processes.
Suppose you are willing to set up or integrate a suitable payment gateway with your website or web application. In that case, it is advisable to hire a web development company that understands your requirements and helps you implement secure solutions.
In this blog, we will talk about integrating different payment gateways with the help of PHP CI (CodeIgniter).
A payment gateway is nothing but an online representation of a real point-of-sale terminal that you see in brick-and-mortar retail stores. A payment gateway often makes the entire payment process secure by encrypting all details, preventing a range of cyberattacks and frauds. The encrypted sensitive information contains details such as the credit/debit card number, CVV, passwords, etc.
A payment gateway is used for transferring important information between websites or mobile devices and specific payment processors or banks. So, suppose you are willing to integrate payment within a website and provide a smooth user experience to your customers. In that case, a payment gateway serves as an effective tool for dealing with various financial transactions online.
The primary task of a payment gateway is to process the debit/credit card information of a user making online purchases. Here are the major steps involved in the functioning of a payment gateway:
Finally, this response received by the payment processor is displayed on the user’s device, confirming or denying their payment.
There are two major types of payment gateways commonly used by vendors in 2021 – Seamless Payment Gateways and Non-seamless Payment Gateways.
A Seamless Payment Gateway is used for processing card payments directly on the user’s website without redirecting them to a third-party website in between. Here, the payment processes are seamless, and the payment takes place in real-time. Also, the user receives feedback about their payment almost immediately after the payment is processed.
Normally, one needs to have an Internet Merchant Credit facility to accept these payments and process them in a seamless manner.
If you accept payments from your customers/prospects via web forms, you need to use a Seamless Payment Gateway or Manual Payment Processing only. Web forms cannot be used for receiving non-seamless payments. According to the latest RBI guidelines and PCI/DSS, only the organizations that are PCI/DSS compliant can collect, store, or process card details on their digital platforms through Seamless Payment Gateways.
A Non-seamless Payment Gateway redirects users to a third-party website for processing the payment and directs them back to the concerned platform once the payment is made. These payment gateways have a higher drop-out rate as customers are taken to a third-party platform, making it a longer process before the payment is made.
Moreover, when you use a Non-seamless Payment Gateway, users are limited to using the online shopping cart to purchase new items, allowing the developers to set up every purchase as a product.
Best Indian Payment Gateways To Integrate With Using CodeIgniter In 2021
Now, let us discuss the following four of the best Indian payment gateways that you can integrate within 2021 to ensure smooth and secure payments:
1. Razorpay
2. CCAvenue
3. PayPal
4. Paytm
Here are the major steps involved in integrating Razorpay Payment Gateway In CodeIgniter:
You need to start by creating a Razorpay account and obtain the much-needed secret key ID from Razorpay. You can do so by visiting https://accounts.razorpay.com/auth/, registering yourself, and obtaining the secret key. If you have already registered with the gateway, you can click visit https://dashboard.razorpay.com/?screen=sign_in and log in with your credentials and the secret key.
Once you have signed up or signed in with Razorpay, you will need to download the PHP kit. The kit is available in a zip format. After downloading the kit, extract the contents of the same and copy the entire folder named “Payment.” Then, paste this into your “Views” folder.
Now, open the pay.php file in the folder you just downloaded, and you would find a payment button in the same. You need to give its link to your controller. Before this, you will be required to enter your Razorpay secret key ID and the secret key into the config.php file present in the Payment folder.
After proceeding to checkout, you would be required to pass all relevant data to the “view” page, which is the payment/pay.php page. By that time, you will need to add all order details in the order table and the payment status of the same.
Once you are redirected to the “payment” page, you would be required to select the preferred mode of payment (card, UPI, wallet, net banking, etc.) and go ahead with the payment process.
This code will return to you with the payment status, letting you know if the payment was successful or had failed. If the payment has failed, you need to pass it to the “fail” page directly, keeping the cart alive. If the payment is successful, you will be required to update the order table with the payment status. Also, make sure that you empty the card to prevent any fraudulent transaction.
Here is the sample code.
require(‘config.php’);
require(‘razorpay-php/Razorpay.php’);
session_start();
// Create the Razorpay Order
use Razorpay\Api\Api;
$api = new Api($keyId, $keySecret);
// We create an razorpay order using orders api
// Docs: https://docs.razorpay.com/docs/orders
$orderData = [
‘receipt’ => 3456,
‘amount’ => 2000 * 100, // 2000 rupees in paise
‘currency’ => ‘INR’,
‘payment_capture’ => 1 // auto capture
];
$razorpayOrder = $api->order->create($orderData);
$razorpayOrderId = $razorpayOrder[‘id’];
$_SESSION[‘razorpay_order_id’] = $razorpayOrderId;
$displayAmount = $amount = $orderData[‘amount’];
if ($displayCurrency !== ‘INR’)
{
$url = “https://api.fixer.io/latest?symbols=$displayCurrency&base=INR“;
$exchange = json_decode(file_get_contents($url), true);
$displayAmount = $exchange[‘rates’][$displayCurrency] * $amount / 100;
}
$checkout = ‘automatic’;
if (isset($_GET[‘checkout’]) and in_array($_GET[‘checkout’], [‘automatic’, ‘manual’], true))
{
$checkout = $_GET[‘checkout’];
}
$data = [
“key” => $keyId,
“amount” => $amount,
“name” => “DJ Tiesto”,
“description” => “Tron Legacy”,
“image” => “https://www.movinnza.in/blog/wp-content/uploads/2021/07/Razorpay.png”,
“prefill” => [
“name” => “Daft Punk”,
“email” => “customer@merchant.com”,
“contact” => “9999999999”,
],
“notes” => [
“address” => “Hello World”,
“merchant_order_id” => “12312321”,
],
“theme” => [
“color” => “#F37254”
],
“order_id” => $razorpayOrderId,
];
if ($displayCurrency !== ‘INR’)
{
$data[‘display_currency’] = $displayCurrency;
$data[‘display_amount’] = $displayAmount;
}
$json = json_encode($data);
require(“checkout/{$checkout}.php”);
You can undertake CCAvenue integration in PHP by binding the concerned web application with CCAvenue with the help of the client library. The client library files will help you connect the CCAvenue server when the payment is being made using authentication credentials. You can get these credentials from the CCAvenue dashboard by logging in as a merchant.
Here are the major steps required for integrating CCAvenue in PHP CodeIgniter:
Downloading The CCAvenue Integration Kit
The CCAvenue Payment Gateway Integration kit is the client library offered to the users by
CCAvenue. The kit is available for mobile and web applications.
Once you log in to the platform with your approved Merchant Account, you can see the
Navigation Menu in the header with the integration kit downloads. After logging in, you need to
go to Resources > Web Integration Kit > Download Integration Kit > Download PHP to obtain
the integration kit for PHP.
Once you have downloaded the integration kit from the CCAvenue Merchant Dashboard, you
can see request-response payment handler files. The kit would also contain a file named
Crypto.php with the collection of distinct functions to encrypt or decrypt the merchant data.
Integrating Code In PHP CodeIgniter
To integrate the code in PHP CodeIgniter, you need to start by generating the keys. You can do
so by logging into your CCAvenue account and go to Settings > API Keys, which will provide
you with the CCAvenue API Keys page. Here, you can see your Merchant ID, Access Code, and
the Working Key.
Once you are done, integrate the downloaded PHP kit in the “views” folder. Then, go ahead with
configuring your Merchant ID, Working Key, and Access Code with the PHP CodeIgniter app. In
the PHP Payment Integration kit, you will find the ccavRequestHandler.php, Crypto.php,
ccavResponseHandler.php, and a test file with the sample payment form and the required inputs
To initiate a payment request, one needs to submit a standard payment form. This form contains specific inputs with your Merchant ID, language, amount, currency, and other relevant payment details. Also, the form contains billing information of the concerned customer along with their name and address.
Here is an HTML code showing a sample payment form used in the CCAvenue Payment Gateway integration. Here, the action of the form is pointed to the PHP endpoint ccavRequestHandler.php, to which the necessary payment details will be posted.
<h1> CCAvenue Payment Gateway Intgration </h1>
<div id=”ccav-payment-form”>
<form name=”frmPayment” action=”ccavRequestHandler.php” method=”POST”>
<input type=”hidden” name=”merchant_id” value=” <?php echo ‘$CCA_MERCHANT_ID’; ?> “>
<input type=”hidden” name=”language” value=”EN”>
<input type=”hidden” name=”amount” value=”1″>
<input type=”hidden” name=”currency” value=”INR”>
<input type=”hidden” name=”redirect_url” value=”http://youdomain.com/payment-response.php”>
<input type=”hidden” name=”cancel_url” value=”http://youdomain.com/payment-cancel.php”> <div>
<input type=”text” name=”billing_name” value=”” class=”form-field” Placeholder=”Billing Name”>
<input type=”text” name=”billing_address” value=”” class=”form-field” Placeholder=”Billing Address”>
</div>
<div>
<input type=”text” name=”billing_state” value=”” class=”form-field” Placeholder=”State”>
<input type=”text” name=”billing_zip” value=”” class=”form-field” Placeholder=”Zipcode”>
</div>
<div>
<input type=”text” name=”billing_country” value=”” class=”form-field” Placeholder=”Country”>
<input type=”text” name=”billing_tel” value=”” class=”form-field” Placeholder=”Phone”>
</div>
<div>
<input type=”text” name=”billing_email” value=”” class=”form-field” Placeholder=”Email”> </div>
<div>
<button class=”btn-payment” type=”submit”> Pay Now </button>
</div>
</form>
</div>
ccavRequestHandler.php
With this file, you can receive the payment data posted through the HTML form, which is encrypted in the file. The Working Key obtained from the merchant dashboard needs to be used here as the encryption key. Once the form input is encrypted, the same details are concatenated (compiled) and sent to the CCAvenue server along with the Access Code.
Crypto.php
The Crypto.php file consists of the functions pertaining to encrypting or decrypting payment information posted through the HTML form. The file also contains functions for padding and conversion.
Going Live
Once you have tested the CCAvenue Payment Gateway integration of your PHP application, you can go live by moving the same to production.
PayPal is one of the most commonly used payment gateways across the globe. You can get your web development company to integrate your website or web application with PayPal’s Instant Payment Notification Service (IPN) for processing secure payments.
On integrating this payment gateway to your website, you will be required to deal with the following four major files:
Here are the major steps involved in integrating PayPal Payment Gateway in PHP CodeIgniter:
Downloading PayPal Payment Gateway Integration Kit
You will be required to download a PayPal SDK file from the account/integration section after logging into your PayPal account and extracting a zip file that contains four PHP files. You do not need to change any file except constants.php.
Integrating Code In PHP CodeIgniter
Here are the three major steps involves in integrating PayPal code in PHP CodeIgniter:
1. Sampling HTML Form In PHP CodeIgniter
For seamless integration, your website should send all the required values to PayPal for your payment to be processed.
Here is a code that shows a basic form that can be used for sending the required values:
< form id=”paypal_form” class=”paypal” action=”payments.php” method=”post” >
< input name=”submit” type=”submit” value=”Submit Payment” / >
< /form >
2. Sending Request To PayPal Via PHP CodeIgniter
You would be required to use the payment.php page to handle the outgoing request to PayPal and handle the incoming response once the payment is processed. For making the request, you would need to build up parameters and pass the same to PayPal through a query string.
Here are the rules that you need to pass:
It is important to note that the code will always be present in the kit.
For constructing the query string, you would be required to assign the post data to an array to which you can push additional values that you do not want to be altered by the post data. This helps you ensure that a user does not manipulate the amount they need to pay or any other details that are vulnerable for the organization. You then need to use http_build_query to convert the array to a query string and pass the same to PayPal through the header.
3. Receiving Response From PayPal Via PHP CodeIgniter
Now, you would need to handle the response from PayPal, a process known as a callback. This allows you to notify the URL configured earlier. For this, you need to reassign the post response to a local variable and verify whether the payment transaction is authentic. You also need to ensure that you haven’t already processed the concerned transaction before adding the payment to your database.
For verifying the authenticity of the response, make sure that you call the verifyTransaction function. This will allow you to take the post data received from PayPal and validate the same by making a curl request to PayPal via the transaction data received. If you get the response of “verified,” you can rest assured that everything went well, and you can proceed to add the payment to your database. You can find the verifyTransaction function in the functions.php file.
Make sure you handle the process discussed above in a controller in a way that if you get a response other than that of success, you can redirect the same to the “payment failed” page and insert the order with its payment status, or update the payment status as received and redirect the same to the “payment success” page.
Keep the cart and session intact if the payment is not successful or empty the cart, and end the session if the payment is processed successfully.
Paytm has successfully emerged as one of the most popular mobile wallets and payment gateways in the country. Today, a range of online sellers and organizations across the board use Paytm for making and receiving payments digitally.
The platform reduces the risk of a user exposing their bank or card details while making a transaction by using Paytm money. All one needs to do is send or receive payments via their mobile phones and unique PIN.
Here are some of the major steps involved in integrating Paytm Payment Gateway in PHP CodeIgniter:
Registering On Paytm
You can start by creating a Paytm account by clicking on the link here – https://business.paytm.com/payment-gateway. While you are signing up for the platform, you need to choose the option that says that Paytm requires processing payments through a website or an app. You will also need to submit a valid redirect URL where you want your users to be redirected once the payment is successful.
While you are getting registered on Paytm, the platform would ask for information such as your business type, addresses, ID proof, bank details, etc. While you can get a Paytm Sandbox credential without completing this process, you will need to provide all the required information to get into production.
This will provide you with your unique Paytm Staging Credentials, including your Staging MID, Industry Type, Merchant Key, Website Name, and Channel ID. In addition, you would also be provided with testing wallet details that can be used for test transaction flow.
Downloading The Official Paytm PHP Kit
Paytm has announced its library source code in all major languages. So all you need to do is download the Paytm Payment Gateway Kit in PHP using your registered Paytm account. Once downloaded, extract the zip file to find the “PaytmKit” folder with all the required files.
Configuring The Paytm Access Credential
Now, open the “config_paytm.php” file in the Paytm kit, go to the library folder and update the same with the access credential you received from Paytm.
define(‘PAYTM_ENVIRONMENT’, ‘PROD’);
define(‘PAYTM_MERCHANT_KEY’, ‘******* ‘);
define(‘PAYTM_MERCHANT_MID’, ‘*******’);
define(‘PAYTM_MERCHANT_WEBSITE’, ‘******’);
Creating The HTML Payment Form
Once you have configured your credential, your code key is ready to be processed. You will now need to create an HTML form for carrying out the online transactions. Make sure that the form action is to the file “pgRedirect.php” inside your Paytm kit. This file would handle checksum and other relevant details, redirecting you to the payments page in Paytm. This would allow the users to process their payments through their Paytm wallets by clicking on the Checkout button.
Here is the sample of an HTML payment form:
<!doctype html>
<!doctype html>
<html>
<head>
<title> Patym Payment Gateway Integration in PHP </title>
</head>
<body>
<div>
<div>
<div>
<div>
<h3 class=”text-center”> Paytm Payment Gateway Demo </h3>
</div>
<div>
<form action=”pgRedirect.php” method=”post”>
<input type=”hidden” id=”CUST_ID” name=”CUST_ID” value=”123456″>
<input type=”hidden” id=”INDUSTRY_TYPE_ID” name=”INDUSTRY_TYPE_ID” value=”Retail”>
<input type=”hidden” id=”CHANNEL_ID” name=”CHANNEL_ID” value=”WEB”>
<div class=”form-group”>
<label> Order ID: </label>
<input type=”text” class=”form-control” id=”ORDER_ID” name=”ORDER_ID” size=”20″ maxlength=”20″ autocomplete=”off” tabindex=”1″ value=”ABC123″>
</div>
<div class=”form-group”>
<label> Amount to Pay: </label>
<input type=”text” class=”form-control” id=”TXN_AMOUNT” name=”TXN_AMOUNT” autocomplete=”off” tabindex=”5″ value=”5000″>
</div>
<div class=”form-group”>
<input type=”submit” name=”submit” value=”CheckOut” class=”btn btn-success btn-lg” >
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
In this form, we have sent some specific parameters as hidden variables, such as Channel ID, Industry Type, and Customer ID of the users. You will need to pass these parameters with the form that you submit.
Make sure that you handle the process discussed above so that when you get a response other than that of successful payment, you can redirect the users to the “payment failed” page and insert their order along with the payment status. Otherwise, if the payment is successfully processed, update the status of the payment as received and redirect the users to the “payment successful” page. Make sure that you keep the cart intact and the session ongoing if the payment is not successful. If the payment is successful, empty the cart and end the session to ensure a secure transaction.
These were some of the major payment gateway integrations that can be undertaken in PHP CodeIgniter. Depending on your organization’s specific preferences and needs, you can ask your custom software development company to integrate a specific payment gateway with your website or web application for faster and more secure processing of payments.
Let'S Get Started. Request for Free Website Audit