How To Integrate Stripe API In A Laravel Application

E-commerce is integral to the online business landscape

Azizi Yusuph
Areas & Producers
7 min readSep 19, 2023

--

Photo by Fahim Muntashir on Unsplash

Introduction

E-commerce has become an integral part of the online business landscape, and if you’re developing a Laravel application that involves processing payments, integrating a reliable payment gateway like Stripe is crucial. Stripe provides a simple and developer-friendly API that allows you to handle payments securely and efficiently. In this tutorial, we’ll walk you through the process of integrating the Stripe API into your Laravel application.

Prerequisites

Before we begin, ensure you have the following prerequisites in place:

  1. Laravel Installed: You should have Laravel installed on your development machine. If not, you can easily set up a new Laravel project using Composer.
  2. Stripe Account: You need an active Stripe account to obtain your API keys. If you don’t have one, sign up at Stripe.
  3. Composer: Make sure you have Composer installed to manage Laravel packages

Step 1: Installing the Stripe PHP Library

To integrate Stripe into your Laravel application, you’ll need to install the Stripe PHP library. Open your terminal and run the following Composer command within your Laravel project directory:

composer require stripe/stripe-php

This command downloads and installs the Stripe PHP library, allowing you to interact with Stripe’s API from your Laravel application.

Step 2: Configuring Your Stripe API Keys

Next, you’ll need to configure your Stripe API keys. In your Laravel project, open the .env file and add your Stripe API keys:

STRIPE_KEY=your_stripe_public_key
STRIPE_SECRET=your_stripe_secret_key

Replace your_stripe_public_key and your_stripe_secret_key with your actual Stripe API keys, which you can find in your Stripe dashboard.

Step 3: Creating a Payment Form

Now, let’s create a simple payment form that allows users to enter their payment details. In your Laravel application, create a Blade view file, such as payment.blade.php, and add the following form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stripe Payment</title>
</head>
<body>
<form action="{{ route('process.payment') }}" method="POST">
@csrf
<label for="cardholderName">Cardholder's Name</label>
<input type="text" id="cardholderName" name="cardholderName" required><br>

<label for="cardNumber">Card Number</label>
<input type="text" id="cardNumber" name="cardNumber" required><br>

<label for="expMonth">Expiration Month</label>
<input type="text" id="expMonth" name="expMonth" required><br>

<label for="expYear">Expiration Year</label>
<input type="text" id="expYear" name="expYear" required><br>

<label for="cvc">CVC</label>
<input type="text" id="cvc" name="cvc" required><br>

<button type="submit">Submit Payment</button>
</form>
</body>
</html>

Ready to level up your coding skills and advance your career? Dive into top-notch interactive courses with Educative and learn at your own pace. From beginner to expert, there’s something for everyone.

🔗 Start Your Learning Journey Now!

Don’t miss out on this opportunity to invest in yourself and your future. Click the link and get started today!

Step 4: Creating a Payment Controller

Now, let’s create a controller that will handle the payment processing. In your terminal, run the following Artisan command to generate a new controller:

php artisan make:controller PaymentController

In your PaymentController.php file, define two methods: one to display the payment form and another to process the payment:

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;

class PaymentController extends Controller
{
public function showPaymentForm()
{
return view('payment');
}

public function processPayment(Request $request)
{
Stripe::setApiKey(config('services.stripe.secret'));

try {
Charge::create([
'amount' => 1000, // Amount in cents
'currency' => 'usd',
'source' => $request->stripeToken,
'description' => 'Test Payment',
]);

return redirect()->route('payment.success')->with('success', 'Payment successful!');
} catch (\Exception $e) {
return redirect()->route('payment.failure')->with('error', $e->getMessage());
}
}
}

Step 5: Handling Payment Routes

Now, define the routes for showing the payment form, processing the payment, and handling success or failure:

In your routes/web.php file, add the following routes:

Route::get('/payment', 'PaymentController@showPaymentForm')->name('payment.form');
Route::post('/process-payment', 'PaymentController@processPayment')->name('process.payment');
Route::get('/payment/success', function () {
return 'Payment Successful!';
})->name('payment.success');
Route::get('/payment/failure', function () {
return 'Payment Failed!';
})->name('payment.failure');

Step 6: Displaying Payment Status

Create Blade Views

  1. Payment Success View (payment-success.blade.php):

Create a new Blade view file named payment-success.blade.php in your resources/views directory. This view will be displayed to users upon successful payment.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Successful</title>
</head>
<body>
<h1>Payment Successful</h1>
<p>Your payment has been processed successfully.</p>
<!-- You can customize this view further with additional information or a thank you message. -->
</body>
</html>

2. Payment Failure View (payment-failure.blade.php):

Create another Blade view file named payment-failure.blade.php in the same directory. This view will be displayed to users when there's an issue with the payment.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Failed</title>
</head>
<body>
<h1>Payment Failed</h1>
<p>There was an issue processing your payment. Please try again later or contact support.</p>
<!-- You can provide troubleshooting tips or contact information for support here. -->
</body>
</html>

Update Routes

Now, update your routes to display these views when the payment is successful or fails.

In your routes/web.php file, modify the success and failure routes to return the corresponding views:

Route::get('/payment/success', function () {
return view('payment-success');
})->name('payment.success');

Route::get('/payment/failure', function () {
return view('payment-failure');
})->name('payment.failure');

Displaying Payment Status Messages

To display payment status messages to the user, you can use the session variable to store and retrieve messages. Update your processPayment method in the PaymentController.php file to store success and error messages in the session:

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;

class PaymentController extends Controller
{
// ...

public function processPayment(Request $request)
{
Stripe::setApiKey(config('services.stripe.secret'));

try {
Charge::create([
'amount' => 1000, // Amount in cents
'currency' => 'usd',
'source' => $request->stripeToken,
'description' => 'Test Payment',
]);

// Payment successful; store a success message in the session
$request->session()->flash('success', 'Payment successful!');

return redirect()->route('payment.success');
} catch (\Exception $e) {
// Payment failed; store an error message in the session
$request->session()->flash('error', $e->getMessage());

return redirect()->route('payment.failure');
}
}
}

With this code, a success message will be flashed to the session upon successful payment, and an error message will be flashed in case of payment failure.

Displaying Messages in Views

Finally, you can display these flashed messages in your Blade views (payment-success.blade.php and payment-failure.blade.php) using Laravel's session helper:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Successful</title>
</head>
<body>
<h1>Payment Successful</h1>

<!-- Display the success message, if available -->
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif

<p>Your payment has been processed successfully.</p>
<!-- You can customize this view further with additional information or a thank you message. -->
</body>
</html>

Similarly, update the payment-failure.blade.php view to display the error message:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Failed</title>
</head>
<body>
<h1>Payment Failed</h1>

<!-- Display the error message, if available -->
@if(session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif

<p>There was an issue processing your payment. Please try again later or contact support.</p>
<!-- You can provide troubleshooting tips or contact information for support here. -->
</body>
</html>

Now, when a user completes a payment, they will be shown either the “Payment Successful” or “Payment Failed” page with the corresponding message based on the result of the payment processing. This provides a clear and user-friendly way to communicate the payment status to your application’s users.

Step 7: Testing Your Stripe Integration

To test your Stripe integration, follow these steps:

  1. Make sure you have set up the payment form and routes as explained in the previous steps.
  2. Start your Laravel development server if it’s not already running. Open your terminal and navigate to your Laravel project directory. Then run:
php artisan serve

This will start the development server, and you’ll see the URL where your Laravel application is accessible (usually http://127.0.0.1:8000).

3. Open your web browser and visit the /payment route in your Laravel application. This route should display the payment form you created earlier.

For example, if your application is running on http://127.0.0.1:8000, you can access the payment form by navigating to:

http://127.0.0.1:8000/payment

4. Fill in the payment form with valid card information. You can use Stripe’s testing card numbers for this purpose. For example, you can use the card number 4242 4242 4242 4242, any future expiration date, and any CVC.

5. Submit the payment form.

6. If everything is set up correctly and the payment is successful, you will be redirected to the success page (/payment/success), and you should see the "Payment Successful" message along with any additional information you included in the view.

7. If there’s an issue with the payment (e.g., invalid card details or insufficient funds), you will be redirected to the failure page (/payment/failure), and you should see the "Payment Failed" message along with any error details.

By following these steps, you can thoroughly test your Stripe integration within your Laravel application. This testing process ensures that your payment flow works as expected, and it allows you to identify and address any issues before deploying your application to a production environment.

Remember to use the Stripe testing card numbers and scenarios provided in Stripe’s documentation to simulate various payment outcomes and test how your application handles different scenarios. Testing thoroughly will help you ensure that your Stripe integration is robust and reliable for your users.

Conclusion

Integrating the Stripe API into your Laravel application allows you to handle online payments securely and efficiently. With this step-by-step guide, you can easily set up Stripe in your Laravel project, create a payment form, and process payments with confidence. Stripe’s developer-friendly API and Laravel’s flexibility make it a powerful combination for building robust e-commerce applications.

Ready to level up your coding skills and advance your career? Dive into top-notch interactive courses with Educative and learn at your own pace. From beginner to expert, there’s something for everyone.

🔗 Start Your Learning Journey Now!

Don’t miss out on this opportunity to invest in yourself and your future. Click the link and get started today!

Check out more content from Aziz Yusuph in Areas & Producers today!

The content in Areas & Producers provides a methodology for readers and writers who are curious about global trends and the future of the world.

--

--

Azizi Yusuph
Areas & Producers

Technical Writer | Community builder | Full Stack Software Developer