Integrating a secure payment gateway is importance in any web application, whether one operates an online store, a subscription service or a donation platform. For the developers, stripe presents itself as a good alternative that provides an easy to follow and yet strong way of doing things.
This tutorial will focus on the integration of stripe into your PHP web application and also it will teach how you can add more fields to your payment form so that you are able get all the details you need. Before finishing you will have a smooth to use interface.
CLICK HERE FOR DEMO
For testing , you can use the following test credit card details:
Card Number: 4242 4242 4242 4242
Expiry Date: Any upcoming date
CVV: Any three-digit code
Step 1: Download the Stripe PHP Library
To integrate Stripe into your web application, you’ll first need to download the Stripe PHP library.This library will handle the communication between your server and Stripe’s API.
You can download this library using this Link.
Step 2: Set Up Your HTML Form
Create a new HTML file (index.php
) for your payment form. This form will include fields for the customer’s first name, last name, email, and credit card information. Here’s an example of what your HTML might look like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Impressive Strip</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" >
<style>
/* Custom CSS for styling */
body {
background-color: #f8f9fa; /* Light gray background */
}
.container {
margin-top: 50px; /* Space from top */
max-width: 500px; /* Limit container width */
border-radius: 10px; /* Rounded corners */
box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.1); /* Box shadow */
padding: 30px; /* Padding inside container */
background-color: #ffffff; /* White background */
}
h1 {
text-align: center; /* Center heading */
margin-bottom: 30px; /* Space after heading */
}
label {
font-weight: bold; /* Bold labels */
}
input[type="text"],
input[type="number"] {
border-radius: 5px; /* Rounded input fields */
margin-bottom: 15px; /* Space between input fields */
}
button {
width: 100%; /* Button width */
padding: 10px; /* Button padding */
border: none; /* No border */
background-color: #007bff; /* Blue button */
color: #ffffff; /* White text */
border-radius: 5px; /* Rounded corners */
cursor: pointer; /* Pointer cursor on hover */
}
button:hover {
background-color: #0056b3; /* Darker blue on hover */
}
#card-element,
#card-expiry-element,
#card-cvc-element {
border: 1px solid #ced4da; /* Gray border for stripe elements */
padding: 10px; /* Padding for stripe elements */
border-radius: 5px; /* Rounded corners */
margin-bottom: 15px; /* Space between stripe elements */
}
#card-errors {
color: #dc3545; /* Red color for error messages */
margin-top: 10px; /* Space above error messages */
}
</style>
</head>
<body>
<div class="container">
<h1> Strip Payment Gateway</h1>
<form action="./charge.php" method="post" id="payment-form">
<div class="form-group">
<label for="first_name">Price(円)</label>
<input type="number" class="form-control stripeElement" name="price_SAMPLE" value="5000" disabled=""/>
<input type="hidden" class="form-control stripeElement" name="price" value="5000" =""/>
</div>
<div class="form-group">
<input type="text" class="form-control stripeElement" name="first_name" placeholder="First Name" />
</div>
<div class="form-group">
<input type="text" class="form-control stripeElement" name="last_name" placeholder="Last Name" />
</div>
<div class="form-group">
<input type="text" class="form-control stripeElement" name="email" placeholder="Email Address" />
</div>
<div class="form-group">
<div id="card-element" class="form-control"> </div>
</div>
<div class="form-group">
<div id="card-expiry-element" class="form-control"></div>
</div>
<div class="form-group">
<div id="card-cvc-element" class="form-control"> </div>
</div>
<div>
<!-- Used to display form errors -->
<div id="card-errors" role="alert"></div>
</div>
<button type="submit">Submit Payment</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://js.stripe.com/v3/"></script>
<script src="payment.js"></script>
</body>
</html>
Step 3: Create the JavaScript File for Stripe Integration
Next, you’ll need to create a JavaScript file (payment.js
) to handle the Stripe payment form. This script will handle the creation of Stripe elements, form validation, and token generation.
// Create a Stripe client
// Use your stripe Publishable key here
var stripe = Stripe('');
// Create an instance of Elements
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Style button with Bbootstrap
document.querySelector('#payment-form button').classList =
'btn btn-primary btn-block mt-4';
// Create an instance of the card Element
var card = elements.create('cardNumber', {
style: style,
});
// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');
// Create an instance of the card Element for expiry date
var cardExpiry = elements.create('cardExpiry', { style: style });
cardExpiry.mount('#card-expiry-element');
// Create an instance of the card Element for CVC
var cardCvc = elements.create('cardCvc', { style: style });
cardCvc.mount('#card-cvc-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server
stripeTokenHandler(result.token);
}
});
});
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var 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();
}
Step 4: Create the PHP Script to Handle the Charge
Create a file named charge.php
to handle the form submission and process the payment. This script will use the Stripe PHP library to create a customer and charge them.
<?php
//include the Stripe PHP library into your project
require_once('stripe-php/init.php');
// Set your Stripe API key
\Stripe\Stripe::setApiKey('');
// Collect form data
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$price = $_POST['price'];
$token = $_POST['stripeToken'];
// Create a customer
try {
$customer = \Stripe\Customer::create([
'email' => $email,
'name' => $first_name . ' ' . $last_name,
'source' => $token,
]);
} catch (\Stripe\Exception\ApiErrorException $e) {
// Handle API error
echo 'Error creating customer: ' . $e->getMessage();
exit;
}
// Charge the customer
try {
$charge = \Stripe\Charge::create([
'amount' => $price, // Amount in cents
'currency' => 'jpy',
'description' => 'Lorem Ipsum is simply dummy text of.',
'customer' => $customer->id, // Customer ID obtained from creating customer
]);
// Prepare the data to be sent in the header as an array
$data = array(
'tid' => $charge->id,
'product' => $charge->description,
'price' => $charge->amount,
'email' => $customer->email,
'cname' => $customer->name
);
// Encode the data as JSON
$jsonData = json_encode($data);
// Set the appropriate content type header
header('Content-Type: application/json');
// Send the JSON data in the header
header('Location: success.php?data=' . urlencode($jsonData));
} catch (\Stripe\Exception\ApiErrorException $e) {
// Handle API error
echo 'Error charging customer: ' . $e->getMessage();
exit;
}
Step 5: Create the PHP Script to Display Confirmation
Create a file named ‘success.php
‘ to display a confirmation message to the user after a successful payment. This script will receive the payment details as JSON data and render them on the page.
<?php
// Check if the data parameter is set in the URL
if (isset($_GET['data'])) {
// Decode the JSON data into an array
$jsonData = json_decode(urldecode($_GET['data']), true);
// Ensure the data is properly decoded and contains the expected fields
if ($jsonData && isset($jsonData['tid'], $jsonData['product'], $jsonData['price'], $jsonData['email'], $jsonData['cname'])) {
$t_id = htmlspecialchars($jsonData['tid']);
$des = htmlspecialchars($jsonData['product']);
$price = htmlspecialchars($jsonData['price']);
$email = htmlspecialchars($jsonData['email']);
$name = htmlspecialchars($jsonData['cname']);
} else {
// Redirect to the homepage if the data is not valid
header('Location: index.php');
exit;
}
} else {
// Redirect to the homepage if the data parameter is not set
header('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thank You</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous">
<style>
/* Custom CSS for styling */
body {
background-color: #f8f9fa; /* Light gray background */
}
.container {
margin-top: 50px; /* Space from top */
max-width: 800px; /* Limit container width */
border-radius: 10px; /* Rounded corners */
box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.1); /* Box shadow */
padding: 30px; /* Padding inside container */
background-color: #ffffff; /* White background */
}
h1 {
text-align: center; /* Center heading */
margin-bottom: 30px; /* Space after heading */
}
table {
width: 100%; /* Full width table */
}
th, td {
padding: 10px; /* Cell padding */
}
th {
text-align: left; /* Align title to left */
width: 30%; /* Set a fixed width for title column */
}
td {
text-align: right; /* Align value to right */
}
.token {
word-break: break-all; /* Break long token string */
}
</style>
</head>
<body>
<div class="container">
<h1>Thank You for Your Purchase!</h1>
<table class="table">
<tbody>
<tr>
<th>Customer Name:</th>
<td><?= $name; ?></td>
</tr>
<tr>
<th>Email:</th>
<td><?= $email; ?></td>
</tr>
<tr>
<th>Purchase ID:</th>
<td><?= $t_id; ?></td>
</tr>
<tr>
<th>Product Price:</th>
<td><?= $price; ?> Yen</td>
</tr>
<tr>
<th>Product Description:</th>
<td><?= $des; ?></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
For testing , you can use the following test credit card details:
- Card Number: 4242 4242 4242 4242
- Expiry Date: Any upcoming date
- CVV: Any three-digit code
Thank you for visiting this page and exploring the integration of the Stripe payment gateway into your project. With this implementation, you can securely process payments from your users with ease and confidence.
To experience a demo of this payment gateway click here and try out the payment process using the provided test credit card details.
I hope this integration enhances your project and provides a seamless payment experience for your users. If you have any questions or need further assistance, don’t hesitate to reach out.
Happy payments!