Businesses use Stripe for payments because it is fast, reliable, and easy to set up. It supports multiple currencies and works in many countries. Stripe also provides built-in fraud protection and detailed reporting. Its key features include handling one-time payments and recurring subscriptions, managing customer information, and integrating with web and mobile apps.
Table of Contents
Table of Contents
Steps to Integrate Stripe on Your Account
Step 1: Install Stripe PHP SDK
Run this command in your project directory:
composer require stripe/stripe-php
This installs Stripe’s official PHP library inside your /vendor folder.
Now include it using:
require 'vendor/autoload.php';
Step 2: Add Your Stripe API Keys
Go to your Stripe Dashboard → Developers → API keys
You’ll find:
- Publishable Key (starts with pk_test_…)
- Secret Key (starts with sk_test_…)
Keep the Secret Key in your server-side code only (never expose it on frontend).
Step 3: Create a Checkout Session (Server-side)
This script will create a Stripe Checkout session and return its ID.
File: create-checkout-session.php
<?php
require 'vendor/autoload.php';
// Set your Stripe secret key
\Stripe\Stripe::setApiKey('sk_test_your_secret_key_here');
header('Content-Type: application/json');
$domain = 'https://yourdomain.com'; // replace with your domain
try {
// Create a new checkout session
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => 'Test Product',
],
'unit_amount' => 2000, // $20.00 (in cents)
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => $domain . '/success.php?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain . '/cancel.php',
]);
echo json_encode(['id' => $session->id]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
Step 4: Create a Checkout Page (Client-side redirect)
File: checkout.php
<!DOCTYPE html>
<html>
<head>
<title>Stripe Checkout Example</title>
</head>
<body>
<button id="checkout-button">Pay $20</button>
<script src="https://js.stripe.com/v3/"></script>
<script>
const stripe = Stripe("pk_test_your_publishable_key_here");
document.getElementById("checkout-button").addEventListener("click", async () => {
const response = await fetch("/create-checkout-session.php", { method: "POST" });
const session = await response.json();
const result = await stripe.redirectToCheckout({ sessionId: session.id });
if (result.error) {
alert(result.error.message);
}
});
</script>
</body>
</html>
Step 5: Create Success and Cancel Pages
File: success.php
<?php
echo "<h1>Payment Successful </h1>";
?>
File: cancel.php
<?php
echo "<h1>Payment Canceled </h1>";
?>
Step 6: Verify Payment using Webhooks
This ensures payments are securely verified even if the user closes the browser early.
File: webhook.php
<?php
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('sk_test_your_secret_key_here');
// Replace with your endpoint's secret (found in Stripe Dashboard → Webhooks)
$endpoint_secret = 'whsec_your_webhook_secret_here';
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload,
$sig_header,
$endpoint_secret
);
} catch (\UnexpectedValueException $e) {
http_response_code(400);
exit();
} catch (\Stripe\Exception\SignatureVerificationException $e) {
http_response_code(400);
exit();
}
w
if ($event->type === 'checkout.session.completed') {
$session = $event->data->object;
// You can mark the order as paid here or save it to database
file_put_contents('payments.log', "Payment successful for session: " . $session->id . PHP_EOL, FILE_APPEND);
}
http_response_code(200);
⚠️ Important:
Set up your webhook URL (e.g., https://yourdomain.com/webhook.php) in the Stripe Dashboard and copy its secret key.
Step 7: Test the Integration
Use the following test card number:
4242 4242 4242 4242
Expiry: any future date
CVC: any 3 digits
You can also simulate failed or incomplete payments using Stripe test cards.
Step 8: Go Live
When everything works fine:
- Replace sk_test_… and pk_test_… with your live keys
- Switch to live mode in Stripe Dashboard
- That’s it — your PHP app now accepts real payments!
Final Folder Structure
/your-project
│
├── vendor/
├── composer.json
├── create-checkout-session.php
├── checkout.php
├── success.php
├── cancel.php
└── webhook.php
Installing Stripe PHP Library
Using Composer to Install Stripe PHP
The easiest way to install the Stripe PHP library is by using Composer, a PHP dependency manager. Open your project folder in the terminal and run the command to require the Stripe package. Composer will automatically download the library and set it up in your project.
Verifying Installation
After installation, check that the library is working correctly. You can do this by including the Stripe autoload file in your PHP script and creating a simple test object, like a Stripe client instance. If there are no errors, the installation is successful.
Updating the Library
It’s important to keep the Stripe PHP library updated. Use Composer’s update command periodically to get the latest features, bug fixes, and security improvements. This ensures your integration remains smooth and secure.
Configuring API Keys in PHP
Stripe provides two sets of API keys: test keys and live keys. Test keys are used while developing and testing your payment system. They let you simulate transactions without real money. Live keys are used when your site goes live and starts accepting real payments. Always keep them separate to avoid accidental charges.
Storing API Keys Securely
Never hardcode your API keys directly in your PHP scripts. Store them in environment variables or a secure configuration file. This protects your keys from being exposed if your code is shared or published online. Only your server-side code should access the keys.
Adding API Keys to Your PHP Project
Include the Stripe PHP library in your project and initialize it with your API keys. This usually involves calling the Stripe client with the secret key from your environment or configuration. Once set up, your PHP project can communicate securely with Stripe’s servers.
Next Steps After Configuration
After configuring API keys, you can start creating payment intents, managing transactions, and integrating payment forms on your website. Proper key configuration ensures secure and smooth payment processing.
Creating a Payment Intent
A Payment Intent in Stripe represents a single payment from a customer. It tracks the lifecycle of the payment, including authorization, confirmation, and completion. Using Payment Intents ensures that the payment process follows Stripe’s latest standards and supports strong authentication methods like 3D Secure.
Setting Amount, Currency, and Metadata
When creating a Payment Intent, you need to define the payment amount and the currency. You can also add metadata such as order ID or customer details to help track the transaction. Metadata is useful for reporting and managing payments in your dashboard.
Confirming Payment
Once the Payment Intent is created, it must be confirmed. This tells Stripe to process the payment. Confirmation can be automatic during checkout or manual, depending on the payment method. Stripe will handle authentication if required.
Next Steps After Creating a Payment Intent
After creating and confirming a Payment Intent, you can handle the payment result in your PHP code. This allows you to update orders, show success messages to customers, or manage failed payments efficiently.
Managing Webhooks for Real-Time Updates
Webhooks are notifications that Stripe sends to your server when specific events occur, such as a successful payment or a failed transaction. They help your system stay updated in real-time without constantly checking Stripe for changes.
Setting Up a Webhook Endpoint in PHP
To use webhooks, create a PHP script on your server that can receive incoming POST requests from Stripe. In your Stripe dashboard, register the endpoint URL so Stripe knows where to send event notifications. Make sure your endpoint is publicly accessible and uses HTTPS for security.
Handling Payment Events
Inside your webhook script, listen for relevant events, like payment_intent.succeeded or payment_intent.payment_failed. You can then perform actions such as updating order status, sending confirmation emails, or logging transaction details in your database.
Securing Webhooks
Stripe provides a signature for each webhook request. Verify this signature in your PHP code to ensure that requests really come from Stripe. This prevents unauthorized or malicious requests from affecting your system.
Testing Stripe Integration in PHP
Using Stripe Test Cards
Stripe provides special test card numbers that simulate different payment scenarios. You can use these cards in test mode to check if your payment forms and Payment Intents work correctly without using real money. This helps identify issues before going live.
Simulating Successful and Failed Payments
You can test both successful and failed transactions using different test cards. This allows you to see how your PHP code handles confirmations, errors, or declined payments. Testing failures is important to make sure your system responds correctly and informs customers.
Checking Webhook Responses
While testing, also verify that your webhooks are triggered properly. Stripe sends event notifications for test payments just like real ones. Make sure your PHP webhook script receives the events and updates your database or order status as expected.
Preparing for Live Mode
After testing, switch your API keys from test mode to live mode. Double-check that everything works correctly, including payment forms, Payment Intents, and webhook handling. This ensures a smooth transition to real transactions.
Conclusion
Stripe API integration in PHP makes online payments simple and secure. By setting up your Stripe account, installing the PHP library, and configuring API keys correctly, you can start accepting payments on your website. Creating Payment Intents and handling customer payments becomes easier with Stripe’s tools.
Using webhooks and testing in test mode ensures your system works smoothly before going live. Following security best practices keeps transactions safe. Overall, integrating Stripe with PHP helps you manage payments efficiently, track transactions, and provide a smooth experience for your customers without worrying about complex payment processes.











