Menu

Stripe Payment Gateway Integration in PHP

Stripe Payment Gateway Integration in PHP

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.

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="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.

// set your stripe publishable key
Stripe.setPublishableKey('Your_Stripe_API_Publishable_Key');
$(document).ready(function() {
$("#paymentForm").submit(function(event) {
$('#makePayment').attr("disabled", "disabled");
// create stripe token to make payment
Stripe.createToken({
number: $('#cardNumber').val(),
cvc: $('#cardCVC').val(),
exp_month: $('#cardExpMonth').val(),
exp_year: $('#cardExpYear').val()
}, handleStripeResponse);
return false;
});
});
// handle the response from stripe
function handleStripeResponse(status, response) {
console.log(JSON.stringify(response));
if (response.error) {
$('#makePayment').removeAttr("disabled");
$(".paymentErrors").html(response.error.message);
} else {
var payForm = $("#paymentForm");
//get stripe token id from response
var stripeToken = response['id'];
//set the token into the form hidden input to make payment
payForm.append("<input type='hidden' name='stripeToken' value='" + stripeToken + "' />");
payForm.get(0).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
//check if stripe token exist to proceed with payment
if(!empty($_POST['stripeToken'])){
// get token and user details
$stripeToken = $_POST['stripeToken'];
$custName = $_POST['custName'];
$custEmail = $_POST['custEmail'];
$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(
'email' => $custEmail,
'source' => $stripeToken
));
// item details for which payment made
$itemName = "phpzag test item";
$itemNumber = "PHPZAG987654321";
$itemPrice = 50;
$currency = "usd";
$orderID = "SKA987654321";
// details for which payment performed
$payDetails = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $itemPrice,
'currency' => $currency,
'description' => $itemName,
'metadata' => array(
'order_id' => $orderID
)
));
// 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("../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('".$custName."','".$custEmail."','".$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: {$lastInsertId}";
} else{
$paymentMessage = "Payment failed!";
}
} else{
$paymentMessage = "Payment failed!";
}
} else{
$paymentMessage = "Payment failed!";
}
echo $paymentMessage;
?>



You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

Komentar

  1. PHPZAG Team, thanks so much for the post.Really thank you! Great.

    BalasHapus

Posting Komentar

Ads middle content1

Ads middle content2