Ecommerce Web development

How To Integrate A Payment Gateway In Your Ecommerce Website?

Having various payment options integrated into an e-commerce website is a sign of success. In today’s time, more and more buyers prefer different payment options so that they can pay according to their own. Many businesses, startups, or entrepreneurs are providing the most popular payment gateways in their eCommerce website to make customer shopping easier, convenient, and safe.

There’s a huge variety of payment gateways available today that you can integrate into your online store or can even create a similar payment gateway your own. But before you start, let’s understand what is a payment gateway, how a payment gateway works, and how to integrate a payment gateway in your eCommerce website.

These days, online payment has become the primary choice of both buyers and sellers. Various banking & finance institutions have turned to digital baking to make transactions secure and quick. According to the report of Statista, online transactions are growing rapidly. The transaction volume for online payment is set to reach the US $ 5,411,354 by 2022.

Payment Gateway integration In Your Ecommerce Website

What is the Payment Gateway?

A payment gateway is a digital payment service provided by the third party to the eCommerce services. It authorizes direct payments, e-wallet, or credit/debit cards at online retailers, eCommerce websites or traditional physical stores. It provides retailers with access to merchant services in order to process payments from major financial institutions.

How Does A Payment Gateway Work?

A payment gateway service provider keeps sensitive information secure & safe given by the users. It encrypts the data like bank or card details of the users. Merchant, Customer, Issuing Bank, and acquirer are the key players in the complete payment process.

Here are the basic steps as to how a payment gateway works-

Step 1– At the checkout page, a user makes payment by clicking on the button.

Step 2– At the checkout, the eCommerce platform securely passes sensitive payment information to the host page (third party payment gateway).

Step 3– Next, the payment gateway tokenizes customer data or information and sends it to the merchant’s acquiring bank.

Step 4– Acquiring verifies the details and sends an “approved” or “declined” response back to the payment gateway.

Step 5– The payment gateway then pushes the response and token back to the customer.

Step 6– Payment information is received and applied to the Microsoft Dynamics™ GP.

Most Popular Payment Gateways And How To Integrate Them In Ecommerce Website

Payment gateway integration to any eCommerce is easy enough if you have some basic technical skills or knowledge.

Authorize.Net, CCAvenue, PayPal, Stripe, SecurePay, Payline Data, Google Pay and Amazon Pay are the most popular payment gateways that can be used to provide amazing shopping experience.

Here we are going to discuss some most popular payment gateways that you could consider for your eCommerce website as per your need.

  1. Authorize.Net

Authorize.Net is the most popular payment gateway that is trusted by more than 400,000 merchants worldwide. It is affordable and reliable that is why small and medium businesses are using Authorize.Net. Moreover, it accepts all major credit cards and works with digital solutions like PayPal, Visa Checkout, and Apple Pay.

How to integrate Authorize.net in eCommerce website-

It is very easy by creating a sandbox account with merchant authentication to get Authorize.Net API.

HTTP Request Method: POST

Sandbox API Endpoint: https://apitest.authorize.net/xml/v1/request.api

Production API Endpoint: https://api.authorize.net/xml/v1/request.api

XML Content-Type: text/xml

JSON Content-Type: application/json

API Schema (XSD): https://api.authorize.net/xml/v1/schema/AnetApiSchema.xsd

You also need the following aspects to integrate Authorize.net-

  • Server Integration Method (SIM).
  • Advanced Integration Method (AIM).
  • Direct Post Method (DPM).
  • Simple Checkout.

Authorize.net fee structure

  • 2.9% + $0.30 per transaction;
  • $49 merchant account setup;
  • $25 monthly gateway;

Note– Authorize.Net can be operated by businesses located in the US, the UK, Canada, Europe, or Australia.

  1. CCAvenue

CCAvenue is also the most popular payment gateway which is being used by most popular e-commerce websites. This payment integration is fast, secure and supports multi-currency. You can use CCAvenue Platform SDKs for Web Integration (JS), Android SDK, iOS SDKs, Cordova/Phonegap/Ionic, React Native, and Flutter.

Follow these steps to integrate CCAvenue in your online store-

  1. Go to CCAvenue Configuration > Sales > Payments.Go to CCAvenue Configuration
  2. Click on the edit option “CCAvenue”.Click on the edit option “CCAvenue
  3. Select ‘CCAvenue settings’
  4. Enter Merchant ID
  5. Enter Access Code
  6. Encryption Key
  7. Click on the Save button.Click on Save button
  8. After completing all the above steps go to Configuration > Sales > ShippingConfiguration Sales Shipping
  9. Edit the shipping method.Edit the shipping method
  10. Under supported payment methods, select CCAvenue and click on the Save button.supported payment methods

Note*: If you have filled all the required details correctly, then make a payment for testing purposes by placing an order. During the payment, use CCAvenue as a payment option and check if you are getting redirected on the CCavenue payment gateway page. If you are redirecting to the payment gateway page, then the payment gateway is successfully activated on your eCommerce website. If not, check if the merchant ID, access code, and encryption key are added properly.

  1. PayPal

You all must hear about PayPal. However, there are various digital payment gateways available today that one can choose from, but the most popular digital payment gateway is PayPal that is being used by top eCommerce websites.

PayPal with advanced security features provides an easy and quick way to request and send money online anywhere and anytime. You can transfer money with ease to family, friends, and online shops.

Fees: You can open a PayPal account for free. Thus, transaction fees depend on the payment you make.

Personal Payments: Payments that you make using PayPal to friends and family are free. The payments using PayPal can be done through PayPal balance and bank account. If you make payment using credit cards, the recipient will be charged the associated fees on the amount that you have sent.

Commercial Payments: In this, the recipient (seller) will be charged the associated fees for the products that you have purchased.

Standard PayPal Processing Fee

  • No setup or monthly fees
  • US fees – 2.9% + $0.30 per transaction
  • International fees – 3.9% + $0.30 per transaction

PayPal Payment Integration-

First of all, you need to create a PayPal account (sign up) by providing PayPal with information about your product, service, or company, in order to verify your “lawful alignment”.

After the completion, you’ll get an Access Key (keep this safe). You can use this as your ID to recognize your app and its setting.

Before start, create the following files to PayPal payment gateway-

  • config.php
  • index.php
  • dbConnect.php
  • success.php
  • cancel.php
  • ipn.php
  • images/

While integrating PayPal, you need to check/test transactions in the Sandbox environment.

You must create PayPal Sandbox account

Create a database for Payment and Product to display data-

For Product

CREATE TABLE `products` (

`id` int(10) NOT NULL AUTO_INCREMENT,

`name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,

`image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

`price` float(10,2) NOT NULL,

`status` tinyint(1) NOT NULL DEFAULT ‘1’ COMMENT ‘1=Active | 0=Inactive’,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

For Payment

CREATE TABLE `payments` (

`payment_id` int(11) NOT NULL AUTO_INCREMENT,

`item_number` varchar(50) COLLATE utf8_unicode_ci NOT NULL,

`txn_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,

`payment_gross` float(10,2) NOT NULL,

`currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,

`payment_status` varchar(20) COLLATE utf8_unicode_ci NOT NULL,

PRIMARY KEY (`payment_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Now you need to configure database-

Config.php

<?php

/*

* PayPal and database configuration

*/

// PayPal configuration

define(‘PAYPAL_ID’, ‘Insert_PayPal_Business_Email’);

define(‘PAYPAL_SANDBOX’, TRUE); //TRUE or FALSE

define(‘PAYPAL_RETURN_URL’, ‘http://www.example.com/success.php’);

 define(‘PAYPAL_CANCEL_URL’, ‘http://www.example.com/cancel.php’);

 define(‘PAYPAL_NOTIFY_URL’, ‘http://www.example.com/ipn.php’);

 define(‘PAYPAL_CURRENCY’, ‘USD’);

 // Database configuration

 define(‘DB_HOST’, ‘MySQL_Database_Host’);

 define(‘DB_USERNAME’, ‘MySQL_Database_Username’);

 define(‘DB_PASSWORD’, ‘MySQL_Database_Password’);

 define(‘DB_NAME’, ‘MySQL_Database_Name’);

 // Change not required

define(‘PAYPAL_URL’, (PAYPAL_SANDBOX == true)?”https://www.sandbox.paypal.com/cgi-bin/webscr”:”https://www.paypal.com/cgi-bin/webscr”);

Connect Database-

dbConnect.php

PHP and MySQL are used to connect the database.

<?php

// Connect with the database

$db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Display error if failed to connect

if ($db->connect_errno) {

     printf(“Connect failed: %s\n”, $db->connect_error);

exit();

}

Now create a file with index.php to display data

After configure data, all the products will display on the website. Create a PayPal Buy Now button to display on each page of the product.

Index.php 

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />

<title>Paypal :: Endive </title>

</head>

<body>

<?php

//fetch products from the database

$results = $db->query(“SELECT * FROM products”);

while($row = $results->fetch_assoc())

{

?>

    <img src=”images/<?php echo $row[‘image’]; ?>”/>

    <br/>Prodcut Name: <?php echo $row[‘name’]; ?>

    <br/>Product Price: <?php echo $row[‘price’]; ?>

    <form action=”<?php echo $paypal_link; ?>” method=”post”>  

        <input type=”hidden” name=”business” value=”<?php echo $paypal_username; ?>”>  

        <!– Specify a Buy Now button. –>

        <input type=”hidden” name=”cmd” value=”_xclick”>      

        <!– Specify details about the item that buyers will purchase. –>

        <input type=”hidden” name=”item_name” value=”<?php echo $row[‘name’]; ?>”>

        <input type=”hidden” name=”item_number” value=”<?php echo $row[‘id’]; ?>”>

        <input type=”hidden” name=”amount” value=”<?php echo $row[‘price’]; ?>”>

        <input type=”hidden” name=”currency_code” value=”USD”> 

                <!– Specify URLs –>

        <input type=’hidden’ name=’cancel_return’ value=’http://localhost/paypal_integration_php/paypal_cancel.php’>

<input type=’hidden’ name=’return’ value=’http://localhost/paypal_integration_php/paypal_success.php’>

        <!– Display the payment button. –>

        <input type=”image” name=”submit” border=”0″

        src=”https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif” alt=”PayPal – The safer, easier way to pay online”>

        <img alt=”” border=”0″ width=”1″ height=”1″ src=”https://www.paypalobjects.com/en_US/i/scr/pixel.gif” >  

    </form>

    <?php } ?>

</body>

</html>

success.php

Upon a successful transaction, the buyer will be redirected to this page. And the payment details will be saved in the database.

<?php

// Include configuration file

include_once ‘config.php’;

// Include database connection file

include_once ‘dbConnect.php’;

// If transaction data is available in the URL

if(!empty($_GET[‘item_number’]) && !empty($_GET[‘tx’]) && !empty($_GET[‘amt’]) && !empty($_GET[‘cc’]) && !empty($_GET[‘st’])){

     // Get transaction information from URL

     $item_number = $_GET[‘item_number’]; 

     $txn_id = $_GET[‘tx’];

     $payment_gross = $_GET[‘amt’];

     $currency_code = $_GET[‘cc’];

     $payment_status = $_GET[‘st’];

     // Get product info from the database

     $productResult = $db->query(“SELECT * FROM products WHERE id = “.$item_number);

     $productRow = $productResult->fetch_assoc();

     // Check if transaction data exists with the same TXN ID.

     $prevPaymentResult = $db->query(“SELECT * FROM payments WHERE txn_id = ‘”.$txn_id.”‘”);

     if($prevPaymentResult->num_rows > 0){

         $paymentRow = $prevPaymentResult->fetch_assoc();

         $payment_id = $paymentRow[‘payment_id’];

         $payment_gross = $paymentRow[‘payment_gross’];

         $payment_status = $paymentRow[‘payment_status’];

}else{

         // Insert transaction data into the database

         $insert = $db->query(“INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES(‘”.$item_number.”‘,'”.$txn_id.”‘,'”.$payment_gross.”‘,'”.$currency_code.”‘,'”.$payment_status.”‘)”);

         $payment_id = $db->insert_id;

}

}

?>

<div class=”container”>

    <div class=”status”>

        <?php if(!empty($payment_id)){ ?>

            <h1 class=”success”>Your Payment has been Successful</h1>

            <h4>Payment Information</h4>

            <p><b>Reference Number:</b> <?php echo $payment_id; ?></p>

            <p><b>Transaction ID:</b> <?php echo $txn_id; ?></p>

            <p><b>Paid Amount:</b> <?php echo $payment_gross; ?></p>

            <p><b>Payment Status:</b> <?php echo $payment_status; ?></p>

            <h4>Product Information</h4>

            <p><b>Name:</b> <?php echo $productRow[‘name’]; ?></p>

            <p><b>Price:</b> <?php echo $productRow[‘price’]; ?></p>

        <?php }else{ ?>

            <h1 class=”error”>Your Payment has Failed</h1>

        <?php } ?>

    </div>

    <a href=”index.php” class=”btn-link”>Back to Products</a>

</div>

Cancel.php

If a buyer cancels the payment at the PayPal page, he/she will be redirected to this page.

<div class=”container”>

<div class=”status”>

<h1 class=”error”>Your PayPal Transaction has been Canceled</h1>

</div>

<a href=”index.php” class=”btn-link”>Back to Products</a>

</div>

  1. Stripe

Stripe is the most popular payment gateway which accepts all major credit cards and works with Android Pay, Apple Pay, etc. Kickstarter, Shopify, Twitter, and Pinterest are some of the brands that rely on Stripe.

It accepts all major credit cards and works with Apple Pay, Ali Pay, Android Pay, and WeChat Pay (beta). Kickstarter, Twitter, Shopify, Pinterest, etc., are popular platforms that rely on Stripe.

Read Also: Easy Apple Pay Integration into iOS Apps via Stripe

Integrating Stripe to the online store is very simple as it requires pre-built UI components. Follow the steps to integrate Stripe-

Stripe Payment Integration

  1. Set up Stripe Elements

Stripe.js consists of all elements that you can use for better integration. You can call this script directly from https://js.stripe.com and add it on your page-

<script src=”https://js.stripe.com/v3/”></script>

In addition to the checkout page, use this script on your every page for better fraud protection.

  1. Create A Payment Form

For your payment form, you need to create a DOM container with unique IDs.

Use this code to create element

<form action=”/charge” method=”post” id=”payment-form”>

 <div class=”form-row”>

   <label for=”card-element”>

     Credit or debit card

   </label>

   <div id=”card-element”>

     <!– A Stripe Element will be inserted here. –>

   </div> 

   <!– Used to display Element errors. –>

   <div id=”card-errors” role=”alert”></div>

 </div>

 <button>Submit Payment</button>

</form> 

After this form is loaded, create an instance of an Element and put it in the Element container: 

Including Stripe.js: <script src=”https://js.stripe.com/v3/”></script>

Initializing Stripe.js: var stripe = Stripe(‘pk_test_TYooMQauvdEDq54NiTphI7jx’);

Create an Elements Instance: var elements = stripe.elements();

Create Card Element: var cardElement = elements.create(‘card’); 

// Custom styling can be passed to options when creating an Element.

var style = {

 base: {

   // Add your base input styles here. For example:

   fontSize: ’16px’,

   color: “#32325d”,

 }

}; 

// Create an instance of the card Element.

var card = elements.create(‘card’, {style: style}); 

// Add an instance of the card Element into the `card-element` <div>.

card.mount(‘#card-element’);

  1. Create A Token To Securely Transmit Card Information-

All the data of payment that you have collected through Elements may turn into a token. By creating an event handler, handle the submit event on the form. It will be used to send the data to Stipe and prevents the submission.

// Create a token or display an error when the form is submitted.

var form = document.getElementById(‘payment-form’);

form.addEventListener(‘submit’, function(event) {

 event.preventDefault(); 

 stripe.createToken(card).then(function(result) {

   if (result.error) {

     // Inform the customer that there was an error.

     var errorElement = document.getElementById(‘card-errors’);

     errorElement.textContent = result.error.message;

   } else {

     // Send the token to your server.

     stripeTokenHandler(result.token);

   }

 });

});

After this, stripe.createToken sends object that has either-

  • error: a Token was created successfully.
  • error: an error occurred.
  1. Submit the token and the rest of your form to your server

Here now, you require to submit the token to your server by providing all the additional information. This is how it should look in JavaScript: 

function stripeTokenHandler(token) {

 // Insert the token ID into the form so it gets submitted to the server

 var form = document.getElementById(‘payment-form’);

 var hiddenInput = document.createElement(‘input’);

 hiddenInput.setAttribute(‘type’, ‘hidden’);

 hiddenInput.setAttribute(‘name’, ‘stripeToken’);

 hiddenInput.setAttribute(‘value’, token.id);

 form.appendChild(hiddenInput); 

 // Submit the form

 form.submit();

}

  1. Amazon Pay

Amazon pay integration is very easy and simple as you can integrate Amazon Pay for your eCommerce website development.

It accepts all major debit/credit cards such as MasterCard, Visa Card, American Express, Discover, and Diner’s Club credit cards. But it has one drawback as the cards you are using must have US billing address.

Amazon Pay fee

It charges per transaction and also takes domestic processing fee which is 2.9% plus $0.30 for an authorization fee.

How to integrate Amazon Pay?

  1. It is a very easy process to get started with, you need to create Amazon Pay account and connect it with your eCommerce website to Login with Amazon:
  2. Next, set up an Amazon Sandbox account that you will use for testing purposes.
  3. Get an SSL certificate.
  4. Get the following Amazon Pay credentials:
    • Merchant ID (seller ID)
    • MWS Access Key and MWS Secret Key
    • LWA Client ID and Client Secret

For your Sandbox integration, use this code snippet:

<script async type=’text/javascript’

    src=’https://static-na.payments-amazon.com/OffAmazonPayments/us/sandbox/js/Widgets.js’>

</script>

For your live Production integration, use this code snippet:

<script async type=’text/javascript’

    src=’https://static-na.payments-amazon.com/OffAmazonPayments/us/js/Widgets.js’>

</script>

How To Choose The Right Gateway For Your E-Commerce Website

You can either choose an integrated or hosted payment gateway for your eCommerce store.

  1. Integrated Payment Gateways

Integrated payment gateway option is one of the best ways that allow users to make payment process on the website without navigating on other third-party merchant pages. But the problem here is that you are responsible for the security and keeping customer data protected.

  1. Hosted Payment Gateways

A hosted payment gateway is a third-party merchant that provides advanced security and keep customer data protected. In this, it redirected customers to the third-party merchant account to complete the transaction and then redirect back to the main website once the payment is completed.

Conclusion-

A payment gateway is a primary thing that is very important for every e-commerce website to offer customers. In order to make the right choice, you must do the groundwork for your website and targeted customers.

If you want to know more about payment gateway integration or are looking technology partner to help you in payment gateway integration in eCommerce website, then we are here to assist with the right solution.

Avatar
About author

Ravikant Chouhan, soft by nature and creative by mind. Being an Engineer specialized in Computer Science, he carries similar curiosity for both; technical world and automobile industry. He keeps himself indulged in discovering new things and with this passion and the vast knowledge attained by him has helped the company to grow at a faster pace.
    Related posts
    Ecommerce Web development

    How to Build an eCommerce Website from Scratch & Start Selling Products Worldwide

    Ecommerce Web development

    How Much It Costs To Build And Maintain An Ecommerce Website Like Amazon And Flipkart?

    Ecommerce Web developmentHelpful ResourcesMagento Development

    WooCommerce Vs Magento Vs OpenCart- Detailed Comparison