Stripe Payment Gateway Integration in PHP
php code / September 8, 2018
Step by Step
Step 1 : Created Database Database Name demos
Step 2 : Created Table SQL QUERY
CREATE TABLE `transaction` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cust_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`cust_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`card_number` 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,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Step 3 : Created header.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- jQuery -->
Step 4 : Created footer.php
<div class="insert-post-ads1" style="margin-top:20px;">
</div>
</div>
</body></html>
Step 5 : Created container.php file
</head>
<body class="">
<div role="navigation" class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="https://phpcodeinfomation.blogspot.com/p/php-script.html" class="navbar-brand">PHPCODE</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="https://phpcodeinfomation.blogspot.com/p/php-script.html">Home</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" style="min-height:500px;">
<div class=''>
</div>
Step 6 : Created db_connect.php File Created
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demos";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %sn", mysqli_connect_error());
exit();
}/* Your code... */
Step 7 : Created index.php file
<?php
include('header.php');
?>
<title>phpcode : Demo Stripe Payment Gateway Integration in PHP</title>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript" src="payment.js"></script>
<?php include('container.php');?>
<div class="container">
<div class="row">
<h2>Stripe Payment Gateway Integration in PHP</h2>
<span class="paymentErrors"></span>
<br>
<div class="col-xs-12 col-md-4">
<div class="panel panel-default">
<div class="panel-body">
<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-6">
<input type="text" name="cardExpMonth" placeholder="MM" size="2" id="cardExpMonth" class="form-control" />
</div>
<div class="col-xs-6">
<input type="text" name="cardExpYear" placeholder="YYYY" 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>
</div>
<div style="margin:50px 0px 0px 0px;">
<a class="btn btn-default read-more" style="background:#3399ff;color:white" href="https://phpcodeinfomation.blogspot.com/p/php-script.html" title="">Back</a>
</div>
</div>
<?php include('footer.php');?>
Step 8 :Created payment.js File
// set your stripe publishable key
Stripe.setPublishableKey('Your_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();
}
}/* Your code... */
Step 9 : Created process.php 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_API_Secret_Key",
"publishable_key" => "Your_API_Publishable_Key"
);
StripeStripe::setApiKey($stripe['secret_key']);
//add customer to stripe
$customer = StripeCustomer::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 = StripeCharge::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 = "<strong>The payment was successful.</strong><strong> Order ID: {$lastInsertId}</strong>";
} else{
$paymentMessage = "Payment failed!";
}
} else{
$paymentMessage = "Payment failed!";
}
} else{
$paymentMessage = "Payment failed!";
}
echo $paymentMessage;
Comments
Njfhsjdwkdjwfh jiwkdwidwhidjwi jiwkdowfiehgejikdoswfiw https://gehddijiwfugwdjaidheufeduhwdwhduhdwudw.com/fjhdjwksdehfjhejdsdefhe