Stripe Payment Integration
Stripe is a popular payment processing platform that allows businesses to accept online payments seamlessly. In this tutorial, we will guide you through the process of integrating Stripe payment into a Laravel web application. By the end of this guide, you will be able to accept payments from your users using Stripe's secure and efficient payment system.
Prerequisites
Before we start, make sure you have the following prerequisites:
- Basic understanding of Laravel and web development.
- A Stripe account to obtain the necessary API keys. If you don't have one, you can sign up for free at Stripe's official website.
Part 1: Setting up the Laravel Project
First, let's set up a new Laravel project or use an existing one. If you're starting from scratch, you can create a new Laravel project using the following command:
composer create-project --prefer-dist laravel/laravel stripe-payment
cd stripe-payment
Next, we need to install the required packages for Stripe integration. Open the terminal and run the following command:
composer require stripe/stripe-php
Once the packages are installed, you'll need to set up your environment variables. In the root of your Laravel project, create a .env
file and add the following lines:
STRIPE_KEY=your_stripe_publishable_key
STRIPE_SECRET=your_stripe_secret_key
Replace your_stripe_publishable_key
and your_stripe_secret_key
with your actual Stripe API keys.
Part 2: Creating the Stripe.blade.php View
Now, let's create the view for our payment form. In your resources/views
directory, create a new file named stripe.blade.php
and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Card Payment</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>Stripe Payment from your card</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default credit-card-box">
<div class="panel-heading display-table" >
<h2 class="panel-title">Checkout Forms</h2>
</div>
<div class="panel-body">
@if (Session::has('success'))
<div class="alert alert-success text-center">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>{{ Session::get('success') }}</p>
</div>
@endif
<form id='checkout-form' method='post' action="{{ route('stripe.post') }}">
@csrf
<input type='hidden' name='stripeToken' id='stripe-token-id'>
<br>
<div id="card-element" class="form-control"></div>
<button
id='pay-btn'
class="btn btn-success mt-3"
type="button"
style="margin-top: 20px; width: 100%;padding: 7px;"
onclick="createToken()">PAY $10
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
var stripe = Stripe('{{ env('STRIPE_KEY') }}')
var elements = stripe.elements();
var cardElement = elements.create('card');
cardElement.mount('#card-element');
/*------------------------------------------
--------------------------------------------
Create Token Code
--------------------------------------------
--------------------------------------------*/
function createToken() {
document.getElementById("pay-btn").disabled = true;
stripe.createToken(cardElement).then(function(result) {
if (typeof result.error != 'undefined') {
document.getElementById("pay-btn").disabled = false;
alert(result.error.message);
}
/* creating token success */
if (typeof result.token != 'undefined') {
document.getElementById("stripe-token-id").value = result.token.id;
document.getElementById('checkout-form').submit();
}
});
}
</script>
</html>
Part 3: The web.php Routes
In the routes/web.php
file, add the following routes to handle the payment:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StripePaymentController;
Route::get('/', function () {
return view('welcome');
});
Route::get('/stripe', [StripePaymentController::class, 'stripe']);
Route::post('/stripe', [StripePaymentController::class, 'stripePost'])->name('stripe.post');
Part 4: The StripePaymentController.php Controller
Next, let's create the controller to handle the payment logic. In the app/Http/Controllers
directory, create a new file named StripePaymentController.php
and add the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stripe;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
class StripePaymentController extends Controller
{
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function stripe(): View
{
return view('stripe');
}
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function stripePost(Request $request): RedirectResponse
{
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
Stripe\Charge::create([
"amount" => 100 * 100,
"currency" => "usd",
"source" => $request->stripeToken,
"description" => "Test payment from your card"
]);
return back()
->with('success', 'Payment successful!');
}
}
Part 5: Making a Test Payment
Now comes the exciting part - testing the payment integration. To simulate a payment, you can use the following test card details provided by Stripe:
- Card Number: 4242 4242 4242 4242
- Expiry Date (MM/YY): 04/25
- CVC: 005
- ZIP: 55555
Please note that these are test card details meant for demonstration purposes only. In a real production environment, you would need to use valid card information.
Here's how you can test the payment:
- Open the application in your web browser and navigate to the payment page.
- Enter the test card details provided above into the payment form.
- Click the "PAY $10" button to initiate the payment.
- If the payment is successful, you should see a success message indicating that the payment was successful.
- You can also check your Stripe Dashboard to see
the details of the test payment.
Remember that as we are using the test card details, no real money will be charged, and the transaction will not affect your actual Stripe account balance.
Conclusion
Congratulations! You have successfully integrated Stripe payment into your Laravel web application. You can now securely accept payments from your users using Stripe's robust and reliable payment system. This integration opens up numerous opportunities for monetizing your application and enhancing the user experience.
To explore more features of Stripe and take your payment system to the next level, be sure to check out the official Stripe documentation and resources.
We hope you found this step-by-step guide helpful. Happy coding!
With this comprehensive blog, readers will have a clear understanding of how to integrate Stripe payment into their Laravel applications. The step-by-step guide and the provided test card details allow them to test the payment integration safely before implementing it in a live environment. Happy blogging!(Ghanshyam).
Top comments (1)
Very useful, I wrote a complementary post on how to structure the code using interfaces and service providers in laravel 11: How to Add and Implement Payment Processing Interfaces in Laravel 11: The Part 1 with Hardcoded Binding