What is Stripe Payment
Stripe PHP is an online and credit card payment method preparing platform for businesses. When a client buys a product online, the funds have to be compelled to be delivered to the seller. Stripe API permits secure and proficient handling of funds via credit card or bank and transfers those funds to the sellers’ account.
The Stripe PHP API permits developers to get to the functionality of Stripe. Stripe is a benefit that permits clients to acknowledge payments online. With the Stripe application, users can keep track of payments, look at past payments, make recurring payments, and keep track of their clients easily.
How to use stripe payment gateway in PHP
The Stripe PHP integration payment gives a simple and effective way to accept credit cards directly on your web application. You’ll be able to coordinate effortlessly with the checkout framework in your PHP-based site, which allows the client to pay via credit or charge cards without clearing out your site.
Stripe periodically releases updates to the Stripe Terminal JavaScript SDK, the Stripe Terminal iOS SDK, and the Stripe Terminal Android SDK, which can incorporate new security upgrades, functionality, and bug fixes.
See also
- Paytm Payment Gateway Integration in PHP Step by Step
- Razorpay Payment Gateway Integration in PHP
- Paypal Payment Gateway Integration in PHP Step by Step
- Integrate Easebuzz payment gateway in PHP
- Integrate PayUMoney Payment Gateway in PHP
- Instamojo payment gateway integration in PHP
- Cashfree Payments Gateway Integration in PHP
How Does Stripe Integrate with PHP?
First, sign in to your Cloudways account. If you don’t have one, sign up now for free.
Get API Keys for Stripe Integration
To get started, you must have a Stripe account. To integrate Stripe gateway in your application, you need to get your Stripe publishable key and secret key.
- Login to your Stripe dashboard and navigate to the Developers » API keys page.
- In the TEST DATA, you’ll see the API keys (Publishable key and Secret key) are listed under the Standard keys section. To show the Secret key, click on Reveal test key button.

On the previous screen, generate API keys for both Test and Live modes and save the Key Id and Key Secret. Evey mode’s navigation is supplied below.
How to Integrate the Stripe Payment Gateway with PHP SDK
To integrate Stripe Payment Gateway with your PHP website, follow the steps outlined below. The PHP sample app, which includes the following files, is used to demonstrate the integration process.
File Structure

File Name | Purpose |
---|---|
index.php | Contains the Products listing |
config.php | Contains the database connection |
checkout.php | Contains the checkout code |
process.php | Contains the payment process and insert in payment_txns table. |
Download the Stripe PHP SDK
You can either download or run a composer command to install Stripe PHP SDK.
Download
Download the latest https://github.com/stripe/stripe-php File from the releases section on GitHub. The stripe-php.zip is pre-compiled to include all dependencies. Add SDK file to your project.
Use Composer Command
You can install Stripe using a composer command. Run the below command on your Composer: Unzip the SDK file and include the Stripe.php file in your project.
composer require stripe/stripe-php
Create Database and Table by SQL query
We need to create database and table, so here I created webscodex database payment_transaction & products table. payment_transaction table holds the records which will be payment success or failed. You can simply create table as following SQL query.
-- -- Database: `webscodex` -- -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `product_name` varchar(100) NOT NULL, `image` varchar(100) NOT NULL, `description` text NOT NULL, `price` float(10,2) NOT NULL, `status` tinyint(4) NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; CREATE TABLE `payment_transaction` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `order_id` varchar(100) NOT NULL, `full_name` varchar(100) NOT NULL, `mobile_number` varchar(100) NOT NULL, `amount` float(10,2) NOT NULL, `status` varchar(100) NOT NULL, `txns_id` varchar(100) NOT NULL, `currency` varchar(100) NOT NULL, `txns_date` datetime NOT NULL, `address` text NOT NULL, `pincode` varchar(100) NOT NULL, `city` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Create Database Configuration File
In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create config.php file on your root directory and put bellow code:
<?php // Database configuration define('DBSERVER', 'localhost'); define('DBUSERNAME', 'root'); define('DBPASSWORD', ''); define('DBNAME', 'webscodex'); // Create database connection $con = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } ?>
Create Add to cart or Buy Product Page
Create Product list or add to card list in our project for e-commerce feature then buy a product using stripe payment gateway. We have created an index.php file for product payment form.
index.php
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Stripe Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container" style="background:#e6e6e6;padding: 50px;"> <div class="py-5 text-center"> <h2> Products List (Stripe Payment Gateway Integration) </h2> </div> <div class="row"> <?php // Database configuration require_once "inc/config.php"; $sql = "SELECT * FROM products WHERE status = '1' order by id DESC"; $query = $con->query($sql); if ($query->num_rows > 0) { while ($row = $query->fetch_assoc()) { ?> <div class="col-md-4"> <div class="card" style="height: 543px;"> <img src="images/<?php echo $row['image']?>" style="width:325px; height: 250px;"> <div class="card-body"> <h5 class="card-title"><?php echo $row['product_name']?></h5> <p class="card-text"><?php echo $row['description']?></p> <a href="checkout.php?product_id=<?php echo $row['id']?>" class="btn btn-sm btn-success">Buy Now</a> <b><span style="float: right;"> ₹<?php echo $row['price']?></span></b> </div> </div> </div> <?php } } ?> </div> </div> </body> </html>
Create HTML Checkout Form
Create an HTML checkout form on your website with the required fields so that it can be passed to the Stripe library to retrieve the order id and other information needed for the payment step. An example HTML form field is shown below. Name of the item, quantity, amount, item description, item address, email, and so on.
checkout.php
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Stripe Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Include External CSS --> <link rel="stylesheet" href="inc/style.css"/> <!-- Stripe JavaScript --> <script src="https://js.stripe.com/v3/"></script> </head> <body> <div class="container" style="background: #f2f2f2; padding-bottom:10px; border: 1px solid #d9d9d9; border-radius: 5px;"> <div class="py-3 text-center"> <h2> Stripe Payment Gateway Integration Checkout</h2> <p class="lead">This Checkout page using Stripe Payment Gateway for Testing purpose </p> </div> <form action="process.php" method="POST" id="payment-form"> <div class="row"> <div class="col-md-8"> <h5>Billing address</h5> <div class="card p-3"> <div class="row"> <div class="col-md-6 mb-3"> <label for="firstName">Full Name </label> <input type="text" class="form-control" name="full_name" placeholder="Full Name" required=""> </div> <div class="col-md-6 mb-3"> <label for="mobile">Mobile Number</label> <input type="text" class="form-control" name="mobile_number" placeholder="Mobile Number" required=""> </div> </div> <div class="mb-3"> <label for="email">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" name="email" placeholder="Email"> </div> <div class="mb-3"> <label for="address">Flat, House no. Area, Street, Sector, Village</label> <input type="text" class="form-control" name="address" placeholder="Full Address" required=""> </div> <div class="row"> <div class="col-md-6 mb-3"> <label for="city">Town/City</label> <input type="text" class="form-control" name="city" placeholder="Town/City"> </div> <div class="col-md-6 mb-3"> <label for="pincode">Pincode</label> <input type="text" class="form-control" name="pincode" placeholder="6 digits [0-9] Pin code" required=""> </div> </div> </div><br> <h5>Payment Options</h5> <div class="card p-3"> <div class="card-body"> <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> </div> </div> <div class="col-md-4"> <?php // Database configuration require_once "inc/config.php"; if (!empty($_GET['product_id']) && isset($_GET['product_id'])) { $pid = $_GET['product_id']; } $sql = "SELECT * FROM products WHERE id = $pid"; $query = $con->query($sql); if ($count = $query->num_rows > 0) { $row = $query->fetch_assoc(); ?> <h4 class="d-flex justify-content-between align-items-center"> <span>Order Summary</span> <span class="badge badge-secondary badge-pill"><?php echo $count; ?></span> </h4> <ul class="list-group mb-3 sticky-top"> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div class="product-list"> <img src="images/<?php echo $row['image']?>" style="width:100px; height: 100px;"> <h6><?php echo $row['product_name']?></h6> <small class="text-muted"><?php echo $row['description']?></small> </div> <span class="text-muted">₹<?php echo $row['price']?></span> </li> <li class="list-group-item d-flex justify-content-between"> <strong> Order Total: </strong> <strong>₹<?php echo $row['price']?></strong> <input type="hidden" name="amount" value="<?php echo $row['price']?>" /> <input type="hidden" name="product_summary" value="<?php echo $row['product_name']?>" /> <input type="hidden" name="product_id" value="<?php echo $row['id']?>" /> </li> </ul> <?php } else{ header("Location:index.php"); } ?> <button type="submit" class="btn-submit btn-block text-white">Pay Now</button> </div> </div> </form> </div> <script> // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('pk_test_51NG2QaSGQbphAuaeiRs7XZaF9APZDhlEKSZGJL7iCrWQL5ZghIpYgByf88M0jMzkJgxOCltLDMW9lcjCGvShmrNS00JGND2dQS'); const elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. const style = { base: { // Add your base input styles here. For example: fontSize: '16px', color: '#32325d', }, }; // Create an instance of the card Element. const card = elements.create('card', {style}); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element'); // Create a token or display an error when the form is submitted. const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); document.querySelector(".btn-submit").disabled = true; const {token, error} = await stripe.createToken(card); if (error) { // Inform the customer that there was an error. const errorElement = document.getElementById('card-errors'); errorElement.textContent = error.message; document.querySelector(".btn-submit").disabled = false; } else { // Send the token to your server. stripeTokenHandler(token); document.querySelector(".btn-submit").disabled = true; } }); const stripeTokenHandler = (token) => { // Insert the token ID into the form so it gets submitted to the server const form = document.getElementById('payment-form'); const 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(); } </script> </body> </html>

Process Payment and Charge Card
This server-side script is accessed by the client-side Fetch API in the JavaScript code to create PaymentIntent and process credit card charge using Stripe API library with PHP.
process.php
<?php require_once 'vendor/autoload.php'; // Token is created using Stripe Checkout or Elements! // Get the payment token ID submitted by the form: if (!empty($_POST['stripeToken'])) { //set stripe secret key and publishable key $secretKey = "sk_test_51NG2QaSGQbphAuaemrC15L71sO9uF3EjRITHApQu6dBrueEcSL0tZiVGSVUgZZnVQpWXqP3l1kPCHNkCCGUPys7200I6ZItDKg"; $stripeToken = $_POST['stripeToken']; $fullName = $_POST['full_name']; $description = $_POST['product_summary']; $mobile_number = $_POST['mobile_number']; $email = $_POST['email']; $address = $_POST['address']; $pincode = $_POST['pincode']; $city = $_POST['city']; $amount = $_POST['amount']; $orderId = "WC".mt_rand(11111, 99999); $stripe = new \Stripe\StripeClient($secretKey); try { // Add customer to stripe $customer = $stripe->customers->create([ 'name' => $fullName, 'description' => $description, 'phone' => $mobile_number, 'email' => $email, 'source' => $stripeToken, 'address' => [ 'line1' => $address, 'postal_code' => $pincode, 'city' => $city, 'line2' => $address, 'country' => 'India', 'state' => $city, ], ]); // Get customer Id from create customer method $customerId = $customer->id; // Create PaymentIntent with amount and currency $paymentIntent = $stripe->paymentIntents->create([ 'customer' => $customerId, 'amount' => $amount, 'currency' => 'usd', 'description' => $description, 'metadata' => [ 'order_id' => $orderId ], 'confirm' => true, 'capture_method' => 'manual', 'payment_method_types' => ['card'], ]); $intent = $stripe->paymentIntents->retrieve($paymentIntent->id); $charge = $stripe->paymentIntents->capture( $paymentIntent->id, ['amount_to_capture' => $amount] ); // Check whether the charge was successful if (!empty($paymentIntent) && $paymentIntent->status == 'succeeded') { // Database configuration require_once "inc/config.php"; date_default_timezone_set("Asia/Kolkata"); if(!empty($customer)){ $customerName = !empty($customer->name) ? $customer->name: ''; $customerEmail = !empty($customer->email) ? $customer->email: ''; $customerPhone = !empty($customer->phone) ? $customer->phone: ''; $description = !empty($customer->description) ? $customer->description : ''; $address = !empty($customer->address->line1) ? $customer->address->line1 : ''; $city = !empty($customer->address->city) ? $customer->address->city : ''; $pincode = !empty($customer->address->postal_code) ? $customer->address->postal_code : ''; } $transaction_id = $paymentIntent->id; $paid_amount = $paymentIntent->amount; $amount = ($paid_amount/100); $currency = $paymentIntent->currency; $payment_status = $paymentIntent->status; $timestamp = $paymentIntent->created; $txnsDate = date('Y-m-d H:i:s', $timestamp); $orderId = $paymentIntent->metadata->order_id; // Insert transaction data into the database $query = "INSERT INTO payment_transaction (order_id, product_summary, full_name, mobile_number, email, amount, currency, status, txns_id, txns_date, address, pincode, city) VALUES ('$orderId', '$description', '$customerName', '$customerPhone', '$customerEmail', '$amount', '$currency', '$payment_status', '$transaction_id', '$txnsDate', '$address', '$pincode', '$city')"; if ($con->query($query)) { if ($paymentIntent->next_action) { header("Location:".$paymentIntent->redirect_to_url->return_url."?pid=".$transaction_id); } }else{ echo "Transaction has been failed!"; } } } catch (Exception $e) { echo $e->getMessage(); } } ?>
Test Card Details
To test the payment process, you need test card details. Use any of the following test card numbers, a valid future expiration date, and any random CVC number, to test Stripe payment gateway integration in PHP.
- 4242 4242 4242 4242 – Visa
- 4000 0566 5566 5556 – Visa (debit)
- 5555 5555 5555 4444 – Mastercard
- 5200 8282 8282 8210 – Mastercard (debit)
- 3782 822463 10005 – American Express
- 6011 1111 1111 1117 – Discover
- 3566 0020 2036 0505 – JCB
- 6200 0000 0000 0005 – UnionPay
Conclusion
The Stripe payment gateway is the easiest way to accept credit card payment on the web application. Our example code uses the Stripe PHP library to create a charge and make payment with a credit/debit card. The 3D Secure authentication is integrated to make this Stripe integration script ready for SCA (Strong Customer Authentication).
You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions or problems about this tutorial, please comment on the form below.😊
Frequently Asked Questions
Does Stripe Support PHP?
Yes, The latest version of the Stripe PHP server-side SDK is v10. 0.0. It supports PHP versions 5.6. 0+
How to integrate payment in PHP?
Step 1: Create an HTML form to collect the customer’s payment source information
Step 2: Create a token to transmit the encrypted data securely. …
Step 3: Allow form submission along with payment information.
Step 4: Verify and validate the charges.
How to use Stripe in PHP?
Create a payment form and render the Stripe element to get the user’s card details. Process Stripe payment requests in PHP. Create and configure webhook to notify the response. Parse the payment response object and store it in a database