Saturday, 29 February 2020

Stripe Payment Gateway Integration in PHP Shopping Cart


If you are learner PHP web developer than you have one question in your mind. How do we integrate Stripe payment gateway integration in our shopping cart using PHP. For solve this query, here we have make one tutorial, in which we will first make shopping cart using PHP and then after we will integrate stripe payment gateway for accepting online payment. For any online business, it's last purpose of business is money. So, how can we get money from PHP based website. For this we have to accept online payment and for this here we will use stripe payment gateway for accepting online payment from credit or debit card. So, in this post you will step by step learn how to make shopping cart in PHP and then after we will discuss how to integrate strip payment gateway integration with PHP shopping cart.

First do you know what is online shopping cart, Shopping cart is one type of online software which has been used in e-commerce website for sale product of service online. User has store product or service details in shopping cart, and if user decide to purchase item or service from online website, then they can buy product or item from online website and they can also to pay price for product or service through online payment gateway. So, here we will make simple shopping cart for learn how to integrate stripe payment integration with PHP website. Here will use PHP $_SESSION variable for store shopping cart details. When use add item into cart then that data will store in $_SESSION variable, so when page has been reload shopping cart data will not be lost and we can again display shopping cart details.

Here we have use Stripe payment gateway with this PHP shopping cart for accepting online payment. There are many online payment gatway services like Paypal, Stripe, CCAvenue, Sage Pay etc. are available in the online market for intregrate in our PHP based application. They all have provide us their api for integrate their payment gateway in our PHP based shopping cart or website. But Stripe is one of the most widely used payment gateway for accepting online payment from credit or debtit cards. So, if in our website if payment gateway is enable by using API, then user can make financial transactions with our PHP based service provider website or shopping cart.

So, in this website we will describe you how to make shopping cart in PHP and then after we will implment stripe payment gateway integration with PHP script. Follow following step for create shopping cart with stripe payment integration.

  1. Load Product on web page using Ajax with PHP

  2. Display Shopping Cart details in Popover Plugin

  3. Add item into Shopping Cart

  4. Remove Single Item or all Item from Shopping Cart

  5. Display Order Details with Payment form

  6. Validate Payment form data with Validation of Credit or Debit Card

  7. Integrate Stripe Payment Gateway in Shopping Cart





Database Structure


For make PHP shopping cart with Stripe payment gateway integration. We need to following database table is require. For this we have to run following sql script.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_product`
--

CREATE TABLE `tbl_product` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `price` double(10,2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_product`
--

INSERT INTO `tbl_product` (`id`, `name`, `image`, `price`) VALUES
(1, 'T-shirt 1', 'image-1.jpg', 350.00),
(2, 'T-shirt 2', 'image-2.jpg', 460.00),
(3, 'T-shirt 3', 'image-3.png', 400.00),
(4, 'T-shirt 4', 'image-4.jpg', 530.00),
(5, 'T-shirt 5', 'image-5.jpg', 400.00),
(6, 'T-shirt 6', 'image-6.jpg', 320.00),
(7, 'T-shirt 7', 'image-7.jpg', 270.00);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_product`
--
ALTER TABLE `tbl_product`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_product`
--
ALTER TABLE `tbl_product`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26;


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `order_table`
--

CREATE TABLE `order_table` (
  `order_id` int(11) NOT NULL,
  `order_number` int(11) NOT NULL,
  `order_total_amount` double(12,2) NOT NULL,
  `transaction_id` varchar(200) NOT NULL,
  `card_cvc` int(5) NOT NULL,
  `card_expiry_month` varchar(30) NOT NULL,
  `card_expiry_year` varchar(30) NOT NULL,
  `order_status` varchar(50) NOT NULL,
  `card_holder_number` varchar(250) NOT NULL,
  `email_address` varchar(250) NOT NULL,
  `customer_name` varchar(250) NOT NULL,
  `customer_address` text NOT NULL,
  `customer_city` varchar(250) NOT NULL,
  `customer_pin` varchar(30) NOT NULL,
  `customer_state` varchar(250) NOT NULL,
  `customer_country` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `order_table`
--
ALTER TABLE `order_table`
  ADD PRIMARY KEY (`order_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `order_table`
--
ALTER TABLE `order_table`
  MODIFY `order_id` int(11) NOT NULL AUTO_INCREMENT;


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `order_item`
--

CREATE TABLE `order_item` (
  `order_item_id` int(11) NOT NULL,
  `order_id` int(11) NOT NULL,
  `order_item_name` varchar(250) NOT NULL,
  `order_item_quantity` int(11) NOT NULL,
  `order_item_price` double(12,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `order_item`
--
ALTER TABLE `order_item`
  ADD PRIMARY KEY (`order_item_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `order_item`
--
ALTER TABLE `order_item`
  MODIFY `order_item_id` int(11) NOT NULL AUTO_INCREMENT;





1 - Load Product on web page using Ajax with PHP




In any shopping cart development process, first we want to load product data from Mysql table and display on web page. Here we have use jQuery Ajax with PHP script for load product data on webpage with Add to cart button.

index.php

<?php
//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart with Stripe Payment Integration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Shopping Cart with Stripe Payment Integration</a></h3>
   <br />
   <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
     <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="sr-only">Menu</span>
      <span class="glyphicon glyphicon-menu-hamburger"></span>
      </button>
      <a class="navbar-brand" href="/">Webslesson</a>
     </div>
     <div id="navbar-cart" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
       <li>
        <a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
         <span class="glyphicon glyphicon-shopping-cart"></span>
         <span class="badge"></span>
         <span class="total_price">$ 0.00</span>
        </a>
       </li>
      </ul>
     </div>
    </div>
   </nav>
   
   <div id="popover_content_wrapper" style="display: none">
    <span id="cart_details"></span>
    <div align="right">
     <a href="order_process.php" class="btn btn-primary" id="check_out_cart">
      <span class="glyphicon glyphicon-shopping-cart"></span> Check out
     </a>
     <a href="#" class="btn btn-default" id="clear_cart">
      <span class="glyphicon glyphicon-trash"></span> Clear
     </a>
    </div>
   </div>

   <div id="display_item" class="row">

   </div>

    
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script>  
$(document).ready(function(){

 load_product();

 function load_product()
 {
  $.ajax({
   url:"fetch_item.php",
   method:"POST",
   success:function(data)
   {
    $('#display_item').html(data);
   }
  })
 }    
});

</script>


database_connection.php

<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


fetch_item.php

<?php

//fetch_item.php

include('database_connection.php');

$query = "
SELECT * FROM tbl_product ORDER BY id ASC
";

$statement = $connect->prepare($query);

if($statement->execute())
{
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:430px;" align="center">
             <img src="images/'.$row["image"].'" class="img-responsive" />
             <br />
             <h4 class="text-info">'.$row["name"].'</h4>
             <h4 class="text-danger">$ '.$row["price"].'</h4>
             <input type="text" name="quantity" id="quantity'.$row["id"].'" class="form-control" value="1" />
             
             <input type="hidden" name="hidden_name" id="name'.$row["id"].'" value="'.$row["name"].'" />
             <input type="hidden" name="hidden_price" id="price'.$row["id"].'" value="'.$row["price"].'" />
             <input type="button" name="add_to_cart" id="'.$row["id"].'" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart" />
            </div>
        </div>
  ';
 }
 echo $output;
}

?>


2 - Display Shopping Cart details in Popover Plugin




This second step for developing PHP shopping cart with stripe payment integration and in this step you can find how to display shopping cart details in Bootstrap Popover plugin. Here we have use Bootstrap Popove plugin for display shopping cart details. For display shopping cart details in Popover plugin here we use jQuery Ajax with PHP script.

index.php

<?php
//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart with Stripe Payment Integration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Shopping Cart with Stripe Payment Integration</a></h3>
   <br />
   <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
     <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="sr-only">Menu</span>
      <span class="glyphicon glyphicon-menu-hamburger"></span>
      </button>
      <a class="navbar-brand" href="/">Webslesson</a>
     </div>
     <div id="navbar-cart" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
       <li>
        <a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
         <span class="glyphicon glyphicon-shopping-cart"></span>
         <span class="badge"></span>
         <span class="total_price">$ 0.00</span>
        </a>
       </li>
      </ul>
     </div>
    </div>
   </nav>
   
   <div id="popover_content_wrapper" style="display: none">
    <span id="cart_details"></span>
    <div align="right">
     <a href="order_process.php" class="btn btn-primary" id="check_out_cart">
      <span class="glyphicon glyphicon-shopping-cart"></span> Check out
     </a>
     <a href="#" class="btn btn-default" id="clear_cart">
      <span class="glyphicon glyphicon-trash"></span> Clear
     </a>
    </div>
   </div>

   <div id="display_item" class="row">

   </div>

    
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script>  
$(document).ready(function(){

 load_product();

 load_cart_data();

 function load_product()
 {
  $.ajax({
   url:"fetch_item.php",
   method:"POST",
   success:function(data)
   {
    $('#display_item').html(data);
   }
  })
 }

 function load_cart_data()
 {
  $.ajax({
   url:"fetch_cart.php",
   method:"POST",
   dataType:"json",
   success:function(data)
   {
    $('#cart_details').html(data.cart_details);
    $('.total_price').text(data.total_price);
    $('.badge').text(data.total_item);
   }
  })
 }

 $('#cart-popover').popover({
  html : true,
  container : 'body',
  content:function(){
   return $('#popover_content_wrapper').html();
  }
 });
    
});

</script>


fetch_cart.php

<?php

//fetch_cart.php

session_start();

$total_price = 0;
$total_item = 0;

$output = '
<div class="table-responsive" id="order_table">
 <table class="table table-bordered table-striped">
  <tr>  
            <th width="40%">Product Name</th>  
            <th width="10%">Quantity</th>  
            <th width="20%">Price</th>  
            <th width="15%">Total</th>  
            <th width="5%">Action</th>  
        </tr>
';

if(!empty($_SESSION["shopping_cart"]))
{
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  $output .= '
  <tr>
   <td>'.$values["product_name"].'</td>
   <td>'.$values["product_quantity"].'</td>
   <td align="right">$ '.$values["product_price"].'</td>
   <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>
   <td><button name="delete" class="btn btn-danger btn-xs delete" id="'. $values["product_id"].'">Remove</button></td>
  </tr>
  ';
  $total_price = $total_price + ($values["product_quantity"] * $values["product_price"]);

  $total_item = $total_item + 1;
 }
 $output .= '
 <tr>  
        <td colspan="3" align="right">Total</td>  
        <td align="right">$ '.number_format($total_price, 2).'</td>  
        <td></td>  
    </tr>
 ';
}
else
{
 $output .= '
    <tr>
     <td colspan="5" align="center">
      Your Cart is Empty!
     </td>
    </tr>
    ';
}
$output .= '</table></div>';

$data = array(
 'cart_details'  => $output,
 'total_price'  => '$' . number_format($total_price, 2),
 'total_item'  => $total_item
);

echo json_encode($data);

?>





3 - Add item into Shopping Cart




After load shopping cart item in Bootstrap Popover plugin, now we want to add item into shopping cart by click on Add to cart button. For add item into cart, we have use jQuery with Ajax for send Add to cart item in PHP shopping cart request send to PHP script. And in PHP script we have use PHP $_SESSION variable for store shopping cart details. So, when page has been refresh then shopping cart details will not be lost and we can easily fetch shopping cart details from $_SESSION variable.

index.php

<?php
//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart with Stripe Payment Integration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Shopping Cart with Stripe Payment Integration</a></h3>
   <br />
   <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
     <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="sr-only">Menu</span>
      <span class="glyphicon glyphicon-menu-hamburger"></span>
      </button>
      <a class="navbar-brand" href="/">Webslesson</a>
     </div>
     <div id="navbar-cart" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
       <li>
        <a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
         <span class="glyphicon glyphicon-shopping-cart"></span>
         <span class="badge"></span>
         <span class="total_price">$ 0.00</span>
        </a>
       </li>
      </ul>
     </div>
    </div>
   </nav>
   
   <div id="popover_content_wrapper" style="display: none">
    <span id="cart_details"></span>
    <div align="right">
     <a href="order_process.php" class="btn btn-primary" id="check_out_cart">
      <span class="glyphicon glyphicon-shopping-cart"></span> Check out
     </a>
     <a href="#" class="btn btn-default" id="clear_cart">
      <span class="glyphicon glyphicon-trash"></span> Clear
     </a>
    </div>
   </div>

   <div id="display_item" class="row">

   </div>

    
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script>  
$(document).ready(function(){

 load_product();

 load_cart_data();

 function load_product()
 {
  $.ajax({
   url:"fetch_item.php",
   method:"POST",
   success:function(data)
   {
    $('#display_item').html(data);
   }
  })
 }

 function load_cart_data()
 {
  $.ajax({
   url:"fetch_cart.php",
   method:"POST",
   dataType:"json",
   success:function(data)
   {
    $('#cart_details').html(data.cart_details);
    $('.total_price').text(data.total_price);
    $('.badge').text(data.total_item);
   }
  })
 }

 $('#cart-popover').popover({
  html : true,
  container : 'body',
  content:function(){
   return $('#popover_content_wrapper').html();
  }
 });

 $(document).on('click', '.add_to_cart', function(){
  var product_id = $(this).attr('id');
  var product_name = $('#name'+product_id+'').val();
  var product_price = $('#price'+product_id+'').val();
  var product_quantity = $('#quantity'+product_id).val();
  var action = 'add';
  if(product_quantity > 0)
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity, action:action},
    success:function(data)
    {
     load_cart_data();
     alert("Item has been Added into Cart");
    }
   })
  }
  else
  {
   alert("Please Enter Number of Quantity");
  }
 });
    
});

</script>


action.php

<?php

//action.php

session_start();

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'add')
 {
  if(isset($_SESSION["shopping_cart"]))
  {
   $is_available = 0;
   foreach($_SESSION['shopping_cart'] as $keys => $values)
   {
    if($_SESSION['shopping_cart'][$keys]['product_id'] == $_POST['product_id'])
    {
     $is_available++;
     $_SESSION['shopping_cart'][$keys]['product_quantity'] = $_SESSION['shopping_cart'][$keys]['product_quantity'] + $_POST['product_quantity'];
    }
   }

   if($is_available == 0)
   {
    $item_array = array(
     'product_id' => $_POST['product_id'],
     'product_name' => $_POST['product_name'],
     'product_price' => $_POST['product_price'],
     'product_quantity' => $_POST['product_quantity']
    );
    $_SESSION['shopping_cart'][] = $item_array;
   }
  }
  else
  {
   $item_array = array(
    'product_id'  => $_POST['product_id'],
    'product_name'  => $_POST['product_name'],
    'product_price'  => $_POST['product_price'],
    'product_quantity' => $_POST['product_quantity']
   );

   $_SESSION['shopping_cart'][] = $item_array;
  }
 }
}

?>


4 - Remove Single Item or all Item from Shopping Cart




Once Item has been added into shopping cart. Now suppose User want to single item from Shopping cart or remove all item from shopping cart. So, this things you can learn from this part. Here we have use jQuery Ajax for front-side operation and for server-side operation we have use PHP script for remove single item or clear shopping cart.

index.php

<?php
//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart with Stripe Payment Integration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Shopping Cart with Stripe Payment Integration</a></h3>
   <br />
   <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
     <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="sr-only">Menu</span>
      <span class="glyphicon glyphicon-menu-hamburger"></span>
      </button>
      <a class="navbar-brand" href="/">Webslesson</a>
     </div>
     <div id="navbar-cart" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
       <li>
        <a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
         <span class="glyphicon glyphicon-shopping-cart"></span>
         <span class="badge"></span>
         <span class="total_price">$ 0.00</span>
        </a>
       </li>
      </ul>
     </div>
    </div>
   </nav>
   
   <div id="popover_content_wrapper" style="display: none">
    <span id="cart_details"></span>
    <div align="right">
     <a href="order_process.php" class="btn btn-primary" id="check_out_cart">
      <span class="glyphicon glyphicon-shopping-cart"></span> Check out
     </a>
     <a href="#" class="btn btn-default" id="clear_cart">
      <span class="glyphicon glyphicon-trash"></span> Clear
     </a>
    </div>
   </div>

   <div id="display_item" class="row">

   </div>

    
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script>  
$(document).ready(function(){

 load_product();

 load_cart_data();

 function load_product()
 {
  $.ajax({
   url:"fetch_item.php",
   method:"POST",
   success:function(data)
   {
    $('#display_item').html(data);
   }
  })
 }

 function load_cart_data()
 {
  $.ajax({
   url:"fetch_cart.php",
   method:"POST",
   dataType:"json",
   success:function(data)
   {
    $('#cart_details').html(data.cart_details);
    $('.total_price').text(data.total_price);
    $('.badge').text(data.total_item);
   }
  })
 }

 $('#cart-popover').popover({
  html : true,
  container : 'body',
  content:function(){
   return $('#popover_content_wrapper').html();
  }
 });

 $(document).on('click', '.add_to_cart', function(){
  var product_id = $(this).attr('id');
  var product_name = $('#name'+product_id+'').val();
  var product_price = $('#price'+product_id+'').val();
  var product_quantity = $('#quantity'+product_id).val();
  var action = 'add';
  if(product_quantity > 0)
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity, action:action},
    success:function(data)
    {
     load_cart_data();
     alert("Item has been Added into Cart");
    }
   })
  }
  else
  {
   alert("Please Enter Number of Quantity");
  }
 });

 $(document).on('click', '.delete', function(){
  var product_id = $(this).attr('id');
  var action = 'remove';
  if(confirm("Are you sure you want to remove this product?"))
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, action:action},
    success:function(data)
    {
     load_cart_data();
     $('#cart-popover').popover('hide');
     alert("Item has been removed from Cart");
    }
   })
  }
  else
  {
   return false;
  }
 });

 $(document).on('click', '#clear_cart', function(){
  var action = 'empty';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action},
   success:function()
   {
    load_cart_data();
    $('#cart-popover').popover('hide');
    alert("Your Cart has been clear");
   }
  })
 });
    
});

</script>


action.php

<?php

//action.php

session_start();

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'add')
 {
  if(isset($_SESSION["shopping_cart"]))
  {
   $is_available = 0;
   foreach($_SESSION['shopping_cart'] as $keys => $values)
   {
    if($_SESSION['shopping_cart'][$keys]['product_id'] == $_POST['product_id'])
    {
     $is_available++;
     $_SESSION['shopping_cart'][$keys]['product_quantity'] = $_SESSION['shopping_cart'][$keys]['product_quantity'] + $_POST['product_quantity'];
    }
   }

   if($is_available == 0)
   {
    $item_array = array(
     'product_id' => $_POST['product_id'],
     'product_name' => $_POST['product_name'],
     'product_price' => $_POST['product_price'],
     'product_quantity' => $_POST['product_quantity']
    );
    $_SESSION['shopping_cart'][] = $item_array;
   }
  }
  else
  {
   $item_array = array(
    'product_id'  => $_POST['product_id'],
    'product_name'  => $_POST['product_name'],
    'product_price'  => $_POST['product_price'],
    'product_quantity' => $_POST['product_quantity']
   );

   $_SESSION['shopping_cart'][] = $item_array;
  }
 }

 if($_POST['action'] == 'remove')
 {
  foreach($_SESSION['shopping_cart'] as $keys => $values)
  {
   if($values['product_id'] == $_POST['product_id'])
   {
    unset($_SESSION['shopping_cart'][$keys]);
   }
  }
 }
 if($_POST['action'] == 'empty')
 {
  unset($_SESSION['shopping_cart']);
 }
}

?>


5 - Display Order Details with Payment form




After adding item into shopping cart, and suppose user want to proceed for payment. For this user want to click on check out button in shopping cart, which has been display in Bootstrap Popover plugin. Once user has click on check out button, then page will redirect to order process page. On which user can see shopping cart details like, which item has been added into shopping cart with total amount of shopping cart which has been fetch from $_SESSION variable. And at left side user can see payment form.

order_process.php

<?php

//order_process.php

session_start();

$total_price = 0;

$item_details = '';

$order_details = '
<div class="table-responsive" id="order_table">
 <table class="table table-bordered table-striped">
  <tr>  
            <th>Product Name</th>  
            <th>Quantity</th>  
            <th>Price</th>  
            <th>Total</th>  
        </tr>
';

if(!empty($_SESSION["shopping_cart"]))
{
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  $order_details .= '
  <tr>
   <td>'.$values["product_name"].'</td>
   <td>'.$values["product_quantity"].'</td>
   <td align="right">$ '.$values["product_price"].'</td>
   <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>
  </tr>
  ';
  $total_price = $total_price + ($values["product_quantity"] * $values["product_price"]);

  $item_details .= $values["product_name"] . ', ';
 }
 $item_details = substr($item_details, 0, -2);
 $order_details .= '
 <tr>  
        <td colspan="3" align="right">Total</td>  
        <td align="right">$ '.number_format($total_price, 2).'</td>
    </tr>
 ';
}
$order_details .= '</table>';

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart with Stripe Payment Integration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://js.stripe.com/v2/"></script>
  <script src="js/jquery.creditCardValidator.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  .require
  {
   border:1px solid #FF0000;
   background-color: #cbd9ed;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Shopping Cart with Stripe Payment Integration</a></h3>
   <br />
   <span id="message"></span>
   <div class="panel panel-default">
    <div class="panel-heading">Order Process</div>
    <div class="panel-body">
     <form method="post" id="order_process_form" action="payment.php">
      <div class="row">
       <div class="col-md-8" style="border-right:1px solid #ddd;">
        <h4 align="center">Customer Details</h4>
        <div class="form-group">
         <label><b>Card Holder Name <span class="text-danger">*</span></b></label>
               <input type="text" name="customer_name" id="customer_name" class="form-control" value="" />
               <span id="error_customer_name" class="text-danger"></span>
           </div>
           <div class="form-group">
            <label><b>Email Address <span class="text-danger">*</span></b></label>
            <input type="text" name="email_address" id="email_address" class="form-control" value="" />
            <span id="error_email_address" class="text-danger"></span>
           </div>
           <div class="form-group">
            <label><b>Address <span class="text-danger">*</span></b></label>
            <textarea name="customer_address" id="customer_address" class="form-control"></textarea>
            <span id="error_customer_address" class="text-danger"></span>
           </div>
           <div class="row">
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>City <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_city" id="customer_city" class="form-control" value="" />
              <span id="error_customer_city" class="text-danger"></span>
             </div>
            </div>
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>Zip <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_pin" id="customer_pin" class="form-control" value="" />
              <span id="error_customer_pin" class="text-danger"></span>
             </div>
            </div>
           </div>
           <div class="row">
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>State </b></label>
              <input type="text" name="customer_state" id="customer_state" class="form-control" value="" />
             </div>
            </div>
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>Country <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_country" id="customer_country" class="form-control" />
              <span id="error_customer_country" class="text-danger"></span>
             </div>
            </div>
           </div>
           <hr />
           <h4 align="center">Payment Details</h4>
           <div class="form-group">
                  <label>Card Number <span class="text-danger">*</span></label>
                  <input type="text" name="card_holder_number" id="card_holder_number" class="form-control" placeholder="1234 5678 9012 3456" maxlength="20" onkeypress="" />
                  <span id="error_card_number" class="text-danger"></span>
              </div>
              <div class="form-group">
                 <div class="row">
                  <div class="col-md-4">
                   <label>Expiry Month</label>
                   <input type="text" name="card_expiry_month" id="card_expiry_month" class="form-control" placeholder="MM" maxlength="2" onkeypress="return only_number(event);" />
                   <span id="error_card_expiry_month" class="text-danger"></span>
                  </div>
                  <div class="col-md-4">
                   <label>Expiry Year</label>
                   <input type="text" name="card_expiry_year" id="card_expiry_year" class="form-control" placeholder="YYYY" maxlength="4" onkeypress="return only_number(event);" />
                   <span id="error_card_expiry_year" class="text-danger"></span>
                  </div>
                  <div class="col-md-4">
                   <label>CVC</label>
                   <input type="text" name="card_cvc" id="card_cvc" class="form-control" placeholder="123" maxlength="4" onkeypress="return only_number(event);" />
                   <span id="error_card_cvc" class="text-danger"></span>
                  </div>
                 </div>
              </div>
              <br />
        <div align="center">
         <input type="hidden" name="total_amount" value="<?php echo $total_price; ?>" />
         <input type="hidden" name="currency_code" value="USD" />
         <input type="hidden" name="item_details" value="<?php echo $item_details; ?>" />
         <input type="button" name="button_action" id="button_action" class="btn btn-success btn-sm" value="Pay Now" />
        </div>
        <br />
       </div>
       <div class="col-md-4">
        <h4 align="center">Order Details</h4>
        <?php
        echo $order_details;
        ?>
       </div>
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>





6 - Validate Payment form data with Validation of Credit or Debit Card




After making payment form. First we want to validate form data. For validate form data here we have use javascript. For validate Credit Card or Debit Card details, here we have use creditCardValidator.js library. By using this library we can validate Credit Card or Debit Card number. And for validate other form field we have use simple javascript with regular expression. This form validate function will be called on submit button click event. So, when user have click on Pay Now submit button, then form validation javascript function will be called and it will display validation error if any occur otherwise it will submit form data to server for proceed for payment.

order_process.php

<?php

//order_process.php

session_start();

$total_price = 0;

$item_details = '';

$order_details = '
<div class="table-responsive" id="order_table">
 <table class="table table-bordered table-striped">
  <tr>  
            <th>Product Name</th>  
            <th>Quantity</th>  
            <th>Price</th>  
            <th>Total</th>  
        </tr>
';

if(!empty($_SESSION["shopping_cart"]))
{
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  $order_details .= '
  <tr>
   <td>'.$values["product_name"].'</td>
   <td>'.$values["product_quantity"].'</td>
   <td align="right">$ '.$values["product_price"].'</td>
   <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>
  </tr>
  ';
  $total_price = $total_price + ($values["product_quantity"] * $values["product_price"]);

  $item_details .= $values["product_name"] . ', ';
 }
 $item_details = substr($item_details, 0, -2);
 $order_details .= '
 <tr>  
        <td colspan="3" align="right">Total</td>  
        <td align="right">$ '.number_format($total_price, 2).'</td>
    </tr>
 ';
}
$order_details .= '</table>';

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart with Stripe Payment Integration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://js.stripe.com/v2/"></script>
  <script src="js/jquery.creditCardValidator.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  .require
  {
   border:1px solid #FF0000;
   background-color: #cbd9ed;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Shopping Cart with Stripe Payment Integration</a></h3>
   <br />
   <span id="message"></span>
   <div class="panel panel-default">
    <div class="panel-heading">Order Process</div>
    <div class="panel-body">
     <form method="post" id="order_process_form" action="payment.php">
      <div class="row">
       <div class="col-md-8" style="border-right:1px solid #ddd;">
        <h4 align="center">Customer Details</h4>
        <div class="form-group">
         <label><b>Card Holder Name <span class="text-danger">*</span></b></label>
               <input type="text" name="customer_name" id="customer_name" class="form-control" value="" />
               <span id="error_customer_name" class="text-danger"></span>
           </div>
           <div class="form-group">
            <label><b>Email Address <span class="text-danger">*</span></b></label>
            <input type="text" name="email_address" id="email_address" class="form-control" value="" />
            <span id="error_email_address" class="text-danger"></span>
           </div>
           <div class="form-group">
            <label><b>Address <span class="text-danger">*</span></b></label>
            <textarea name="customer_address" id="customer_address" class="form-control"></textarea>
            <span id="error_customer_address" class="text-danger"></span>
           </div>
           <div class="row">
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>City <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_city" id="customer_city" class="form-control" value="" />
              <span id="error_customer_city" class="text-danger"></span>
             </div>
            </div>
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>Zip <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_pin" id="customer_pin" class="form-control" value="" />
              <span id="error_customer_pin" class="text-danger"></span>
             </div>
            </div>
           </div>
           <div class="row">
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>State </b></label>
              <input type="text" name="customer_state" id="customer_state" class="form-control" value="" />
             </div>
            </div>
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>Country <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_country" id="customer_country" class="form-control" />
              <span id="error_customer_country" class="text-danger"></span>
             </div>
            </div>
           </div>
           <hr />
           <h4 align="center">Payment Details</h4>
           <div class="form-group">
                  <label>Card Number <span class="text-danger">*</span></label>
                  <input type="text" name="card_holder_number" id="card_holder_number" class="form-control" placeholder="1234 5678 9012 3456" maxlength="20" onkeypress="" />
                  <span id="error_card_number" class="text-danger"></span>
              </div>
              <div class="form-group">
                 <div class="row">
                  <div class="col-md-4">
                   <label>Expiry Month</label>
                   <input type="text" name="card_expiry_month" id="card_expiry_month" class="form-control" placeholder="MM" maxlength="2" onkeypress="return only_number(event);" />
                   <span id="error_card_expiry_month" class="text-danger"></span>
                  </div>
                  <div class="col-md-4">
                   <label>Expiry Year</label>
                   <input type="text" name="card_expiry_year" id="card_expiry_year" class="form-control" placeholder="YYYY" maxlength="4" onkeypress="return only_number(event);" />
                   <span id="error_card_expiry_year" class="text-danger"></span>
                  </div>
                  <div class="col-md-4">
                   <label>CVC</label>
                   <input type="text" name="card_cvc" id="card_cvc" class="form-control" placeholder="123" maxlength="4" onkeypress="return only_number(event);" />
                   <span id="error_card_cvc" class="text-danger"></span>
                  </div>
                 </div>
              </div>
              <br />
        <div align="center">
         <input type="hidden" name="total_amount" value="<?php echo $total_price; ?>" />
         <input type="hidden" name="currency_code" value="USD" />
         <input type="hidden" name="item_details" value="<?php echo $item_details; ?>" />
         <input type="button" name="button_action" id="button_action" class="btn btn-success btn-sm" onclick="stripePay(event)" value="Pay Now" />
        </div>
        <br />
       </div>
       <div class="col-md-4">
        <h4 align="center">Order Details</h4>
        <?php
        echo $order_details;
        ?>
       </div>
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

function validate_form()
{
 var valid_card = 0;
 var valid = true;
 var card_cvc = $('#card_cvc').val();
 var card_expiry_month = $('#card_expiry_month').val();
 var card_expiry_year = $('#card_expiry_year').val();
 var card_holder_number = $('#card_holder_number').val();
 var email_address = $('#email_address').val();
 var customer_name = $('#customer_name').val();
 var customer_address = $('#customer_address').val();
 var customer_city = $('#customer_city').val();
 var customer_pin = $('#customer_pin').val();
 var customer_country = $('#customer_country').val();
 var name_expression = /^[a-z ,.'-]+$/i;
 var email_expression = /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/;
 var month_expression = /^01|02|03|04|05|06|07|08|09|10|11|12$/;
 var year_expression = /^2017|2018|2019|2020|2021|2022|2023|2024|2025|2026|2027|2028|2029|2030|2031$/;
 var cvv_expression = /^[0-9]{3,3}$/;

 $('#card_holder_number').validateCreditCard(function(result){
  if(result.valid)
  {
   $('#card_holder_number').removeClass('require');
   $('#error_card_number').text('');
   valid = true;
  }
  else
  {
   $('#card_holder_number').addClass('require');
   $('#error_card_number').text('Invalid Card Number');
   valid = false;
  }
 });

 if(!name_expression.test(customer_name))
 {
  $('#customer_name').addClass('require');
  $('#error_customer_name').text('Invalid Name');
  valid = false;
 }
 else
 {
  $('#customer_name').removeClass('require');
  $('#error_customer_name').text('');
  valid = true;
 }

 if(!email_expression.test(email_address))
 {
  $('#email_address').addClass('require');
  $('#error_email_address').text('Invalid Email Address');
  valid = false;
 }
 else
 {
  $('#email_address').removeClass('require');
  $('#error_email_address').text('');
  valid = true;
 }

 if(customer_address == '')
 {
  $('#customer_address').addClass('require');
  $('#error_customer_address').text('Enter Address Detail');
  valid = false;
 }
 else
 {
  $('#customer_address').removeClass('require');
  $('#error_customer_address').text('');
  valid = true;
 }

 if(customer_city == '')
 {
  $('#customer_city').addClass('require');
  $('#error_customer_city').text('Enter City');
  valid = false;
 }
 else
 {
  $('#customer_city').removeClass('require');
  $('#error_customer_city').text('');
  valid = true;
 }

 if(customer_pin == '')
 {
  $('#customer_pin').addClass('require');
  $('#error_customer_pin').text('Enter Zip code');
  valid = false;
 }
 else
 {
  $('#customer_pin').removeClass('require');
  $('#error_customer_pin').text('');
  valid = true;
 }

 if(customer_country == '')
 {
  $('#customer_country').addClass('require');
  $('#error_customer_country').text('Enter Country Detail');
  valid = false;
 }
 else
 {
  $('#customer_country').removeClass('require');
  $('#error_customer_country').text('');
  valid = true;
 }

 if(!month_expression.test(card_expiry_month))
 {
  $('#card_expiry_month').addClass('require');
  $('#error_card_expiry_month').text('Invalid Data');
  valid = false;
 }
 else
 { 
  $('#card_expiry_month').removeClass('require');
  $('#error_card_expiry_month').text('');
  valid = true;
 }

 if(!year_expression.test(card_expiry_year))
 {
  $('#card_expiry_year').addClass('require');
  $('#error_card_expiry_year').error('Invalid Data');
  valid = false;
 }
 else
 {
  $('#card_expiry_year').removeClass('require');
  $('#error_card_expiry_year').error('');
  valid = true;
 }

 if(!cvv_expression.test(card_cvc))
 {
  $('#card_cvc').addClass('require');
  $('#error_card_cvc').text('Invalid Data');
  valid = false;
 }
 else
 {
  $('#card_cvc').removeClass('require');
  $('#error_card_cvc').text('');
  valid = true;
 }

 return valid;
}

function stripePay(event)
{
 event.preventDefault();
 if(validate_form())
 {

 }
 else
 {

 }
}

</script>



7 - Integrate Stripe Payment Gateway in Shopping Cart




Now we have come on the main part of this tutorial and in this part, we have to integrate stripe payment gateway into PHP shopping cart. For Integrate Stripe Payment Gateway in PHP, we have to follow following steps.

  1. For Integrate Stripe Payment Gateway in PHP Shopping cart. First we have to make account in https://stripe.com/ website. Once you have make account in this website. Then after login into your Stripe Account. Then it has provide two test API key like Secret Keys and Publishable Keys. By using both keys, we can use Stripe Payment Gateway API with our PHP script. Create a Stripe account and login to get the API keys.
  2. In second steps, we have to download Stripe Gateway PHP library. For this we have go to command prompt and in our computer composer has been install. Then after go to our working directory and write composer require stripe/stripe-php this command will download in define folder.
  3. In third steps we have to create payment form, which we have already created and we have also validate form details like validate credit or debit card number and other form details.
  4. In third steps, we have to include Stripe JavaScript library and set Publishable keys. After this, by using Stripe JavaScript Library, we have to create payment token by sending credit card or debit card details send to stripe and get payment process token from Stripe Payment API.
  5. After received token append in to payment form and send payment form details to PHP script for charge amount from Credit or debit card.
  6. Once payment form data has been send to PHP script at server side, First we want to set Stripe secret API key. Afte set stripe secret api key, then after we have to add customer details to Stripe.
  7. After add customer details to Stripe, then after we have to Charge bill amount from Credit or Debit Card and received amount charge response from Stripe and then after save Order data in Mysql table.

order_process.php

<?php

//order_process.php

session_start();

$total_price = 0;

$item_details = '';

$order_details = '
<div class="table-responsive" id="order_table">
 <table class="table table-bordered table-striped">
  <tr>  
            <th>Product Name</th>  
            <th>Quantity</th>  
            <th>Price</th>  
            <th>Total</th>  
        </tr>
';

if(!empty($_SESSION["shopping_cart"]))
{
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  $order_details .= '
  <tr>
   <td>'.$values["product_name"].'</td>
   <td>'.$values["product_quantity"].'</td>
   <td align="right">$ '.$values["product_price"].'</td>
   <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>
  </tr>
  ';
  $total_price = $total_price + ($values["product_quantity"] * $values["product_price"]);

  $item_details .= $values["product_name"] . ', ';
 }
 $item_details = substr($item_details, 0, -2);
 $order_details .= '
 <tr>  
        <td colspan="3" align="right">Total</td>  
        <td align="right">$ '.number_format($total_price, 2).'</td>
    </tr>
 ';
}
$order_details .= '</table>';

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart with Stripe Payment Integration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://js.stripe.com/v2/"></script>
  <script src="js/jquery.creditCardValidator.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  .require
  {
   border:1px solid #FF0000;
   background-color: #cbd9ed;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Shopping Cart with Stripe Payment Integration</a></h3>
   <br />
   <span id="message"></span>
   <div class="panel panel-default">
    <div class="panel-heading">Order Process</div>
    <div class="panel-body">
     <form method="post" id="order_process_form" action="payment.php">
      <div class="row">
       <div class="col-md-8" style="border-right:1px solid #ddd;">
        <h4 align="center">Customer Details</h4>
        <div class="form-group">
         <label><b>Card Holder Name <span class="text-danger">*</span></b></label>
               <input type="text" name="customer_name" id="customer_name" class="form-control" value="" />
               <span id="error_customer_name" class="text-danger"></span>
           </div>
           <div class="form-group">
            <label><b>Email Address <span class="text-danger">*</span></b></label>
            <input type="text" name="email_address" id="email_address" class="form-control" value="" />
            <span id="error_email_address" class="text-danger"></span>
           </div>
           <div class="form-group">
            <label><b>Address <span class="text-danger">*</span></b></label>
            <textarea name="customer_address" id="customer_address" class="form-control"></textarea>
            <span id="error_customer_address" class="text-danger"></span>
           </div>
           <div class="row">
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>City <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_city" id="customer_city" class="form-control" value="" />
              <span id="error_customer_city" class="text-danger"></span>
             </div>
            </div>
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>Zip <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_pin" id="customer_pin" class="form-control" value="" />
              <span id="error_customer_pin" class="text-danger"></span>
             </div>
            </div>
           </div>
           <div class="row">
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>State </b></label>
              <input type="text" name="customer_state" id="customer_state" class="form-control" value="" />
             </div>
            </div>
            <div class="col-sm-6">
             <div class="form-group">
              <label><b>Country <span class="text-danger">*</span></b></label>
              <input type="text" name="customer_country" id="customer_country" class="form-control" />
              <span id="error_customer_country" class="text-danger"></span>
             </div>
            </div>
           </div>
           <hr />
           <h4 align="center">Payment Details</h4>
           <div class="form-group">
                  <label>Card Number <span class="text-danger">*</span></label>
                  <input type="text" name="card_holder_number" id="card_holder_number" class="form-control" placeholder="1234 5678 9012 3456" maxlength="20" onkeypress="" />
                  <span id="error_card_number" class="text-danger"></span>
              </div>
              <div class="form-group">
                 <div class="row">
                  <div class="col-md-4">
                   <label>Expiry Month</label>
                   <input type="text" name="card_expiry_month" id="card_expiry_month" class="form-control" placeholder="MM" maxlength="2" onkeypress="return only_number(event);" />
                   <span id="error_card_expiry_month" class="text-danger"></span>
                  </div>
                  <div class="col-md-4">
                   <label>Expiry Year</label>
                   <input type="text" name="card_expiry_year" id="card_expiry_year" class="form-control" placeholder="YYYY" maxlength="4" onkeypress="return only_number(event);" />
                   <span id="error_card_expiry_year" class="text-danger"></span>
                  </div>
                  <div class="col-md-4">
                   <label>CVC</label>
                   <input type="text" name="card_cvc" id="card_cvc" class="form-control" placeholder="123" maxlength="4" onkeypress="return only_number(event);" />
                   <span id="error_card_cvc" class="text-danger"></span>
                  </div>
                 </div>
              </div>
              <br />
        <div align="center">
         <input type="hidden" name="total_amount" value="<?php echo $total_price; ?>" />
         <input type="hidden" name="currency_code" value="USD" />
         <input type="hidden" name="item_details" value="<?php echo $item_details; ?>" />
         <input type="button" name="button_action" id="button_action" class="btn btn-success btn-sm" onclick="stripePay(event)" value="Pay Now" />
        </div>
        <br />
       </div>
       <div class="col-md-4">
        <h4 align="center">Order Details</h4>
        <?php
        echo $order_details;
        ?>
       </div>
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

function validate_form()
{
 var valid_card = 0;
 var valid = false;
 var card_cvc = $('#card_cvc').val();
 var card_expiry_month = $('#card_expiry_month').val();
 var card_expiry_year = $('#card_expiry_year').val();
 var card_holder_number = $('#card_holder_number').val();
 var email_address = $('#email_address').val();
 var customer_name = $('#customer_name').val();
 var customer_address = $('#customer_address').val();
 var customer_city = $('#customer_city').val();
 var customer_pin = $('#customer_pin').val();
 var customer_country = $('#customer_country').val();
 var name_expression = /^[a-z ,.'-]+$/i;
 var email_expression = /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/;
 var month_expression = /^01|02|03|04|05|06|07|08|09|10|11|12$/;
 var year_expression = /^2017|2018|2019|2020|2021|2022|2023|2024|2025|2026|2027|2028|2029|2030|2031$/;
 var cvv_expression = /^[0-9]{3,3}$/;

 $('#card_holder_number').validateCreditCard(function(result){
  if(result.valid)
  {
   $('#card_holder_number').removeClass('require');
   $('#error_card_number').text('');
   valid_card = 1;
  }
  else
  {
   $('#card_holder_number').addClass('require');
   $('#error_card_number').text('Invalid Card Number');
   valid_card = 0;
  }
 });

 if(valid_card == 1)
 {
  if(!month_expression.test(card_expiry_month))
  {
   $('#card_expiry_month').addClass('require');
   $('#error_card_expiry_month').text('Invalid Data');
   valid = false;
  }
  else
  { 
   $('#card_expiry_month').removeClass('require');
   $('#error_card_expiry_month').text('');
   valid = true;
  }

  if(!year_expression.test(card_expiry_year))
  {
   $('#card_expiry_year').addClass('require');
   $('#error_card_expiry_year').error('Invalid Data');
   valid = false;
  }
  else
  {
   $('#card_expiry_year').removeClass('require');
   $('#error_card_expiry_year').error('');
   valid = true;
  }

  if(!cvv_expression.test(card_cvc))
  {
   $('#card_cvc').addClass('require');
   $('#error_card_cvc').text('Invalid Data');
   valid = false;
  }
  else
  {
   $('#card_cvc').removeClass('require');
   $('#error_card_cvc').text('');
   valid = true;
  }
  if(!name_expression.test(customer_name))
  {
   $('#customer_name').addClass('require');
   $('#error_customer_name').text('Invalid Name');
   valid = false;
  }
  else
  {
   $('#customer_name').removeClass('require');
   $('#error_customer_name').text('');
   valid = true;
  }

  if(!email_expression.test(email_address))
  {
   $('#email_address').addClass('require');
   $('#error_email_address').text('Invalid Email Address');
   valid = false;
  }
  else
  {
   $('#email_address').removeClass('require');
   $('#error_email_address').text('');
   valid = true;
  }

  if(customer_address == '')
  {
   $('#customer_address').addClass('require');
   $('#error_customer_address').text('Enter Address Detail');
   valid = false;
  }
  else
  {
   $('#customer_address').removeClass('require');
   $('#error_customer_address').text('');
   valid = true;
  }

  if(customer_city == '')
  {
   $('#customer_city').addClass('require');
   $('#error_customer_city').text('Enter City');
   valid = false;
  }
  else
  {
   $('#customer_city').removeClass('require');
   $('#error_customer_city').text('');
   valid = true;
  }

  if(customer_pin == '')
  {
   $('#customer_pin').addClass('require');
   $('#error_customer_pin').text('Enter Zip code');
   valid = false;
  }
  else
  {
   $('#customer_pin').removeClass('require');
   $('#error_customer_pin').text('');
   valid = true;
  }

  if(customer_country == '')
  {
   $('#customer_country').addClass('require');
   $('#error_customer_country').text('Enter Country Detail');
   valid = false;
  }
  else
  {
   $('#customer_country').removeClass('require');
   $('#error_customer_country').text('');
   valid = true;
  }

  
 }
 return valid;
}

Stripe.setPublishableKey('pk_test_JKDlpKvWn3oe1nIwl75D9pC400hFQsqUwu');

function stripeResponseHandler(status, response)
{
 if(response.error)
 {
  $('#button_action').attr('disabled', false);
  $('#message').html(response.error.message).show();
 }
 else
 {
  var token = response['id'];
  $('#order_process_form').append("<input type='hidden' name='token' value='" + token + "' />");

  $('#order_process_form').submit();
 }
}

function stripePay(event)
{
 event.preventDefault();
 
 if(validate_form() == true)
 {
  $('#button_action').attr('disabled', 'disabled');
  $('#button_action').val('Payment Processing....');
  Stripe.createToken({
   number:$('#card_holder_number').val(),
   cvc:$('#card_cvc').val(),
   exp_month : $('#card_expiry_month').val(),
   exp_year : $('#card_expiry_year').val()
  }, stripeResponseHandler);
  return false;
 }
}


function only_number(event)
{
 var charCode = (event.which) ? event.which : event.keyCode;
 if (charCode != 32 && charCode > 31 && (charCode < 48 || charCode > 57))
 {
  return false;
 }
 return true;
}

</script>



payment.php

<?php

//payment.php

include('database_connection.php');

session_start();

if(isset($_POST["token"]))
{
 require_once 'stripe_vendor/autoload.php';

 \Stripe\Stripe::setApiKey('sk_test_M8aSXyC69s7owKnr7zKlAe8s00BJIaNslz');

 $customer = \Stripe\Customer::create(array(
  'email'   => $_POST["email_address"],
  'source'  => $_POST["token"],
  'name'   => $_POST["customer_name"],
  'address'  => array(
   'line1'   => $_POST["customer_address"],
   'postal_code' => $_POST["customer_pin"],
   'city'   => $_POST["customer_city"],
   'state'   => $_POST["customer_state"],
   'country'  => 'US'
  )
 ));

 $order_number = rand(100000,999999);

 $charge = \Stripe\Charge::create(array(
  'customer'  => $customer->id,
  'amount'  => $_POST["total_amount"] * 100,
  'currency'  => $_POST["currency_code"],
  'description' => $_POST["item_details"],
  'metadata'  => array(
   'order_id'  => $order_number
  )
 ));

 $response = $charge->jsonSerialize();

 if($response["amount_refunded"] == 0 && empty($response["failure_code"]) && $response['paid'] == 1 && $response["captured"] == 1 && $response['status'] == 'succeeded')
 {
  $amount = $response["amount"]/100;

  $order_data = array(
   ':order_number'   => $order_number,
   ':order_total_amount' => $amount,
   ':transaction_id'  => $response["balance_transaction"],
   ':card_cvc'    => $_POST["card_cvc"],
   ':card_expiry_month' => $_POST["card_expiry_month"],
   ':card_expiry_year'  => $_POST["card_expiry_year"],
   ':order_status'   => $response["status"],
   ':card_holder_number' => $_POST["card_holder_number"],
   ':email_address'  => $_POST['email_address'],
   ':customer_name'  => $_POST["customer_name"],
   ':customer_address'  => $_POST['customer_address'],
   ':customer_city'  => $_POST['customer_city'],
   ':customer_pin'   => $_POST['customer_pin'],
   ':customer_state'  => $_POST['customer_state'],
   ':customer_country'  => $_POST['customer_country']
  );

  $query = "
  INSERT INTO order_table 
     (order_number, order_total_amount, transaction_id, card_cvc, card_expiry_month, card_expiry_year, order_status, card_holder_number, email_address, customer_name, customer_address, customer_city, customer_pin, customer_state, customer_country) 
     VALUES (:order_number, :order_total_amount, :transaction_id, :card_cvc, :card_expiry_month, :card_expiry_year, :order_status, :card_holder_number, :email_address, :customer_name, :customer_address, :customer_city, :customer_pin, :customer_state, :customer_country)
  ";

  $statement = $connect->prepare($query);

  $statement->execute($order_data);

  $order_id = $connect->lastInsertId();

  foreach($_SESSION["shopping_cart"] as $keys => $values)
  {
   $order_item_data = array(
    ':order_id'  => $order_id,
    ':order_item_name' => $values["product_name"],
    ':order_item_quantity' => $values["product_quantity"],
    ':order_item_price' => $values["product_price"]
   );

   $query = "
   INSERT INTO order_item 
   (order_id, order_item_name, order_item_quantity, order_item_price) 
   VALUES (:order_id, :order_item_name, :order_item_quantity, :order_item_price)
   ";

   $statement = $connect->prepare($query);

   $statement->execute($order_item_data);
  }

  unset($_SESSION["shopping_cart"]);

  $_SESSION["success_message"] = "Payment is completed successfully. The TXN ID is " . $response["balance_transaction"] . "";
  header('location:index.php');
 }

}

?>


So, here tutorial on Stripe Payment Gateway Integration in PHP Shopping cart. If you want to get complete tutorial with Sql file and library file, you can email us at webslesson@gmail.com


12 comments:

  1. Excelente buen tutorial lo lei completo . Cuando tenga tiempo lo implento .

    ReplyDelete
  2. i have read lot of php code from you but this one is awesome stunning.

    ReplyDelete
  3. Hello admin, can you send me your code



    ReplyDelete
  4. please send source code with all folders such css and image

    ReplyDelete
  5. hello sir ur video is so nice.can u send me full source code plz send your are code is giving me some error plz sir send me full source code my email address is-abhishekgouda882@gmail.com plz send me sir

    ReplyDelete
  6. plz send me full source code this code is giving an error sir

    ReplyDelete
  7. I want to get complete tutorial with Sql file and library file,

    ReplyDelete
  8. thank you for a wonderful tutorial. works like a gun

    ReplyDelete
  9. Hey admin great tutorial, however I still have errors from your code! please send the full code with pics to; 17868uk@saeinstitute.edu

    ReplyDelete
  10. How to update the quantity of the product in this case?

    Awaiting a favorable response.

    Cordially

    ReplyDelete
  11. Good evening admin, I would like to know how to update the quantity of the product?

    Thank you for answering me.

    ReplyDelete
  12. i've problem with stripe v2, how about stripe v3 tutorial and script?
    please help me

    ReplyDelete