Stripe Payment Gateway Integration in PHP

The Stripe payment gateway provides an easy and powerful way to accept credit cards directly on the web application. Stripe make it easy to integrate checkout system and collect payment on the website. The Stripe API is a powerful solution to integrate checkout system in the web application to provide a smooth payment experience.

If you want to accept credit card payment on your website, Stripe will the best option for that. You can easily integrate checkout system in your PHP-based website, that allows the user to make payment through credit or debit cards without leaving your website. In this tutorial, we will show you how to integrate Stripe payment gateway in PHP for collecting payment online using the credit card or debit card.

In the Stripe payment gateway integration process, the following functionality will be implemented.

  • The HTML form to collect credit card information.
  • Create Stripe token to securely transmit card information.
  • Submit the form with card details.
  • Verify the card and process charges.
  • Insert payment details in the database and status will be shown to the user.

Stripe Test API Keys Data

Before taking your Stripe payment gateway integration live, you need to test it thoroughly. To test the credit card payment process, the test API Keys are needed to generate in your Stripe account.

  • Login to your Stripe account and navigate to the API page.
  • Under the TEST DATA section, you’ll see the API keys are listed. To show the Secret key, click on Reveal test key token button.

Collect the Publishable key and Secret key to later use in the script.

Before you get started to implement Stripe payment gateway in PHP, take a look the files structure.


Create Database Table

To store the transaction details, a table needs to be created in the database. The following SQL creates an orders table in the MySQL database.

CREATE TABLE `orders` (
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `card_num` bigint(20) NOT NULL,
 `card_cvc` int(5) NOT NULL,
 `card_exp_month` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
 `card_exp_year` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `item_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `item_number` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `item_price` float(10,2) NOT NULL,
 `item_price_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'usd',
 `paid_amount` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `paid_amount_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `txn_id` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `payment_status` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

//Database credentials
$dbHost     'localhost';
$dbUsername 'root';
$dbPassword '*****';
$dbName     'codexworld';

//Connect with the database
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

//Display error if failed to connect
if ($db->connect_errno) {
printf("Connect failed: %s\n"$db->connect_error);

Stripe Checkout Form (index.php)

At first, include the Stripe JavaScript library, for securely sending the sensitive information to Stripe directly from browser.

<!-- Stripe JavaScript library -->
<script type="text/javascript" src=""></script>

The jQuery library is used only for this example, it’s not required to use Stripe.

<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script src=""></script>

In the JavaScript code, set your publishable API key that identifies your website to Stripe. The stripeResponseHandler() function creates a single-use token and inserts a token field in the payment form HTML.

<script type="text/javascript">
//set your publishable key

//callback to handle the response from stripe
function stripeResponseHandler(status, response) {
    if (response.error) {
        //enable the submit button
        //display the errors on the form
    } else {
        var form$ = $("#paymentFrm");
        //get token id
        var token = response['id'];
        //insert the token into the form
        form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
        //submit form to the server
$(document).ready(function() {
    //on form submit
    $("#paymentFrm").submit(function(event) {
        //disable the submit button to prevent repeated clicks
        $('#payBtn').attr("disabled", "disabled");
        //create single-use token to charge the user
            number: $('.card-number').val(),
            cvc: $('.card-cvc').val(),
            exp_month: $('.card-expiry-month').val(),
            exp_year: $('.card-expiry-year').val()
        }, stripeResponseHandler);
        //submit from callback
        return false;

The following HTML form collects the user information (name and email) and card details (Card Number, Expiration Date, and CVC No.). For further card payment processing, the form is submitted to the PHP script (submit.php).

<h1>Charge $55 with Stripe</h1>

<!-- display errors returned by createToken -->
<span class="payment-errors"></span>

<!-- stripe payment form -->
<form action="submit.php" method="POST" id="paymentFrm">
        <input type="text" name="name" size="50" />
        <input type="text" name="email" size="50" />
        <label>Card Number</label>
        <input type="text" name="card_num" size="20" autocomplete="off" class="card-number" />
        <input type="text" name="cvc" size="4" autocomplete="off" class="card-cvc" />
        <label>Expiration (MM/YYYY)</label>
        <input type="text" name="exp_month" size="2" class="card-expiry-month"/>
        <span> / </span>
        <input type="text" name="exp_year" size="4" class="card-expiry-year"/>
    <button type="submit" id="payBtn">Submit Payment</button>

Stripe PHP Library

The Stripe PHP library will be used to process the card payment. You can get all the library files in our source code, alternatively, you can download it from GitHub.

Validate and Process Payment (submit.php)

In this file, the submitted card details are validated and the charge is processed using Stripe PHP library.

  • Get token, card details and user info from the submitted form.
  • Include the Stripe PHP library.
  • Set your Publishable key and Secret key which we have created in Stripe Test API Data section.
  • Add customer to stripe using the user email and Stripe token.
  • Specify product details and create a charge to the credit card or debit card.
  • Retrieve the charge details that have previously been created.
  • If the charge is successful, the order and transaction details will be inserted in the database. Otherwise, an error message will be shown.
//check whether stripe token is not empty
//get token, card and user info from the form
$token  $_POST['stripeToken'];
$name $_POST['name'];
$email $_POST['email'];
$card_num $_POST['card_num'];
$card_cvc $_POST['cvc'];
$card_exp_month $_POST['exp_month'];
$card_exp_year $_POST['exp_year'];
//include Stripe PHP library
//set api key
$stripe = array(
"secret_key"      => "Your_API_Secret_Key",
"publishable_key" => "Your_API_Publishable_Key"
//add customer to stripe
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source'  => $token
//item information
$itemName "Premium Script CodexWorld";
$itemNumber "PS123456";
$itemPrice 55;
$currency "usd";
$orderID "SKA92712382139";
//charge a credit or a debit card
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount'   => $itemPrice,
'currency' => $currency,
'description' => $itemName,
'metadata' => array(
'order_id' => $orderID
//retrieve charge details
$chargeJson $charge->jsonSerialize();

//check whether the charge is successful
if($chargeJson['amount_refunded'] == && empty($chargeJson['failure_code']) && $chargeJson['paid'] == && $chargeJson['captured'] == 1){
//order details 
$amount $chargeJson['amount'];
$balance_transaction $chargeJson['balance_transaction'];
$currency $chargeJson['currency'];
$status $chargeJson['status'];
$date date("Y-m-d H:i:s");
//include database config file
include_once 'dbConfig.php';
//insert tansaction data into the database
$sql "INSERT INTO orders(name,email,card_num,card_cvc,card_exp_month,card_exp_year,item_name,item_number,item_price,item_price_currency,paid_amount,paid_amount_currency,txn_id,payment_status,created,modified) VALUES('".$name."','".$email."','".$card_num."','".$card_cvc."','".$card_exp_month."','".$card_exp_year."','".$itemName."','".$itemNumber."','".$itemPrice."','".$currency."','".$amount."','".$currency."','".$balance_transaction."','".$status."','".$date."','".$date."')";
$insert $db->query($sql);
$last_insert_id $db->insert_id;
//if order inserted successfully
if($last_insert_id && $status == 'succeeded'){
$statusMsg "<h2>The transaction was successful.</h2><h4>Order ID: {$last_insert_id}</h4>";
$statusMsg "Transaction has been failed";
$statusMsg "Transaction has been failed";
$statusMsg "Form submission error.......";

//show success or error message
echo $statusMsg;

PayPal Payment Gateway Integration in PHP

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.

  • 4242424242424242 Visa
  • 4000056655665556 Visa (debit)
  • 5555555555554444 Mastercard
  • 5200828282828210 Mastercard (debit)
  • 378282246310005 American Express
  • 6011111111111117 Discover

Make Stripe Payment Gateway Live

Once testing is done and the payment process working properly, follow the below steps to make Stripe payment gateway live.

  • Login to your Stripe account and navigate to the API page.
  • Collect the API keys (Publishable key and Secret key) from Live Data.
  • Change the Test API keys (Publishable key and Secret key) with the Live API keys (Publishable key and Secret key) in the script.

PayPal Subscriptions Payment Gateway Integration in PHP

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

Leave a reply