Stripe is the hottest payment gateway in the web industry. It offers payment processing services that can easily integrate in web applications. Stripe provides an easy way to accept debit card and credit card to collect payment on web applications.
If you want to integrate payment gateway in your web application, Stripe can be the best choice. The Stripe is more secure and fast and its major killer feature is Stripe.js that makes it different from other. When you use Stripe.js in your web application, the debit or card card details entered into payment form is never sent to your server. Instead, the data is sent directly to Stripe. This makes entire payment process more secure as you don’t need to handle any sensitive data on your servers.
Also, read:
- Paypal Express Checkout Integration with PHP
- Paypal Payment Gateway Integration in PHP
- CCAvenue Payment Gateway Integration in PHP
- Paytm Payment Gateway Integration in PHP
- EBS Payment Gateway Integration in PHP
- PayUMoney Payment Gateway Integration in PHP
- Razorpay Payment Gateway Integration in PHP
The Stripe is also allows the users to make payment through credit or debit cards without leaving website. So if you’re looking for tutorial to integrate Stripe payment gateway using PHP, then you’re here at right place. In this tutorial you will learn how to integrate Stripe payment gateway in PHP. The tutorial explained in easy steps with live demo and links to download source code of live demo.
Stripe Payment Gateway Integration Checkout Flow
The Stripe payment gateway integration checkout flow have following steps to charge customer:
- HTML Form to collect customer payment detail.
- Send customer payment details to Stripe to create Token to perform payment securely.
- Submit Form to your server with Token.
- Your server uses the token to charge the customer.
So let’s start coding. As we will cover this tutorial with live demo to to integrate Stripe payment gateway in PHP, so the file structure for this example is following.
- index.php
- payment.js
- process.php
Step1: Get Stripe API Details
For Stripe payment gateway integration, we first need to create Stripe account and login to Strip account to get test API Keys to test it thoroughly before get it live.
- Just login to Stripe Dashboard and navigate to the API page.
- Then 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.
- Get the Publishable key and Secret key to use during payment gateway integration.
Step2: Include jQuery and Stipe Files
We will include Stripe.js in index.php file and custom payment.js to get Token from Stripe. We will also include jQuery and Bootstrap as we will handle this example with Bootstrap and jQuery.
<script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript" src="script/payment.js"></script>
Step3: Create HTML Payment Form
In index.php file, we will create HTML Form to collect customer payment details like name, email and card details. We will also create form action with process.php submit form to process customer payment after getting Token from Stripe.
<div class="col-xs-12 col-md-4"> <div class="panel panel-default"> <div class="panel-body"> <span class="paymentErrors alert-danger"></span> <form action="process.php" method="POST" id="paymentForm"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="custName" class="form-control"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="custEmail" class="form-control"> </div> <div class="form-group"> <label>Card Number</label> <input type="text" name="cardNumber" size="20" autocomplete="off" id="cardNumber" class="form-control" /> </div> <div class="row"> <div class="col-xs-4"> <div class="form-group"> <label>CVC</label> <input type="text" name="cardCVC" size="4" autocomplete="off" id="cardCVC" class="form-control" /> </div> </div> </div> <div class="row"> <div class="col-xs-10"> <div class="form-group"> <label>Expiration (MM/YYYY)</label> <div class="col-xs-5"> <input type="text" name="cardExpMonth" placeholder="MM" size="2" id="cardExpMonth" class="form-control" /> </div> <div class="col-xs-5"> <input type="text" name="cardExpYear" placeholder="YY" size="4" id="cardExpYear" class="form-control" /> </div> </div> </div> </div> <br> <div class="form-group"> <input type="submit" id="makePayment" class="btn btn-success" value="Make Payment"> </div> </form> </div> </div> </div>
Step4: Get Token with Strip.js
We will create custom JavaScript file payment.js and set test publishable key. Then we will get Stripe Token using Stripe.js with customer Card details to charge customer. We will set token in hidden input in form and then submit form to finally charge customer.
Stripe.setPublishableKey('Your_Stripe_API_Publishable_Key'); function stripePay(event) { event.preventDefault(); if(validateForm() == true) { $('#payNow').attr('disabled', 'disabled'); $('#payNow').val('Payment Processing....'); Stripe.createToken({ number:$('#cardNumber').val(), cvc:$('#cardCVC').val(), exp_month : $('#cardExpMonth').val(), exp_year : $('#cardExpYear').val() }, stripeResponseHandler); return false; } } function stripeResponseHandler(status, response) { if(response.error) { $('#payNow').attr('disabled', false); $('#message').html(response.error.message).show(); } else { var stripeToken = response['id']; $('#paymentForm').append("<input type='hidden' name='stripeToken' value='" + stripeToken + "' />"); $('#paymentForm').submit(); } }
Step5: Make Payment with Stripe Payment Gateway with PHP
Now finally in process.php file, we will get customer form details and Stripe token and charge customer. The Stripe PHP library will be used to charge the customer. You can get all the Stripe library files in our download source code, you can also download it from GitHub.
We will also insert customer charge transaction details into MySQL database table transaction after successful payment. You will get table transaction schema in download source code zip file.
<?php $paymentMessage = ''; if(!empty($_POST['stripeToken'])){ // get token and user details $stripeToken = $_POST['stripeToken']; $customerName = $_POST['customerName']; $customerEmail = $_POST['emailAddress']; $customerAddress = $_POST['customerAddress']; $customerCity = $_POST['customerCity']; $customerZipcode = $_POST['customerZipcode']; $customerState = $_POST['customerState']; $customerCountry = $_POST['customerCountry']; $cardNumber = $_POST['cardNumber']; $cardCVC = $_POST['cardCVC']; $cardExpMonth = $_POST['cardExpMonth']; $cardExpYear = $_POST['cardExpYear']; //include Stripe PHP library require_once('stripe-php/init.php'); //set stripe secret key and publishable key $stripe = array( "secret_key" => "Your_Stripe_Secret_Key", "publishable_key" => "Your_Stripe_API_Publishable_Key" ); \Stripe\Stripe::setApiKey($stripe['secret_key']); //add customer to stripe $customer = \Stripe\Customer::create(array( 'name' => $customerName, 'description' => 'test description', 'email' => $customerEmail, 'source' => $stripeToken, "address" => ["city" => $customerCity, "country" => $customerCountry, "line1" => $customerAddress, "line2" => "", "postal_code" => $customerZipcode, "state" => $customerState] )); // item details for which payment made $itemName = $_POST['item_details']; $itemNumber = $_POST['item_number']; $itemPrice = $_POST['price']; $totalAmount = $_POST['total_amount']; $currency = $_POST['currency_code']; $orderNumber = $_POST['order_number']; // details for which payment performed $payDetails = \Stripe\Charge::create(array( 'customer' => $customer->id, 'amount' => $totalAmount, 'currency' => $currency, 'description' => $itemName, 'metadata' => array( 'order_id' => $orderNumber ) )); // get payment details $paymenyResponse = $payDetails->jsonSerialize(); // check whether the payment is successful if($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1){ // transaction details $amountPaid = $paymenyResponse['amount']; $balanceTransaction = $paymenyResponse['balance_transaction']; $paidCurrency = $paymenyResponse['currency']; $paymentStatus = $paymenyResponse['status']; $paymentDate = date("Y-m-d H:i:s"); //insert tansaction details into database include_once("include/db_connect.php"); $insertTransactionSQL = "INSERT INTO transaction(cust_name, cust_email, card_number, 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('".$customerName."','".$customerEmail."','".$cardNumber."','".$cardCVC."','".$cardExpMonth."','".$cardExpYear."','".$itemName."','".$itemNumber."','".$itemPrice."','".$paidCurrency."','".$amountPaid."','".$paidCurrency."','".$balanceTransaction."','".$paymentStatus."','".$paymentDate."','".$paymentDate."')"; mysqli_query($conn, $insertTransactionSQL) or die("database error: ". mysqli_error($conn)); $lastInsertId = mysqli_insert_id($conn); //if order inserted successfully if($lastInsertId && $paymentStatus == 'succeeded'){ $paymentMessage = "The payment was successful. Order ID: {$orderNumber}"; } else{ $paymentMessage = "failed"; } } else{ $paymentMessage = "failed"; } } else{ $paymentMessage = "failed"; } $_SESSION["message"] = $paymentMessage; header('location:index.php'); ?>
You may also like:
- Star Rating System with Ajax, PHP and MySQL
- Create Event Calendar with jQuery, PHP and MySQL
- Build Your Own CAPTCHA Script with PHP
- Convert Unix Timestamp To Readable Date Time in PHP
- Inventory Management System with Ajax, PHP & MySQL
- Create Live Editable Table with jQuery, PHP and MySQL
- Live Add Edit Delete datatables Records with Ajax, PHP and MySQL
- Stripe Payment Gateway Integration in PHP
- Export Data to Excel with PHP and MySQL
- Star Rating System with Ajax, PHP and MySQL
- Create Dynamic Bootstrap Tabs with PHP & MySQL
- How To Create Simple REST API in PHP
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download
PHPZAG Team, thanks so much for the post.Really thank you! Great.
Any plans to update to the version 3 API?
I will update you when updated to version 3, thanks!
Superb bro after a long time your code works for me
Perfect!!! It works like a Swiss watch