How to Integrate Stripe Payment with React js & Laravel 10 Part 1
In this tutorial, we will see how to integrate stripe payment with React js and Laravel 10, in this first part we will handle the backend logic so I assume that you have already created a stripe account and you have your API keys.
Install the packages
First, let's install the packages that we need.
//for the frontend
npm install --save @stripe/react-stripe-js @stripe/stripe-js
//for the backend
composer require stripe/stripe-php
Create the controller
Next, create the PaymentController.
<?php
namespace App\Http\Controllers\Api;
use Stripe\Stripe;
use ErrorException;
use App\Http\Controllers\Controller;
class PaymentController extends Controller
{
/** Pay order via stripe */
public function payByStripe(){
Stripe::setApiKey('Your Secret Key');
try {
// retrieve JSON from POST body
$jsonStr = file_get_contents('php://input');
$jsonObj = json_decode($jsonStr);
// Create a PaymentIntent with amount and currency
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $this->calculateOrderAmount($jsonObj->items),
'currency' => 'usd',
'description' => 'React Store',
'setup_future_usage' => 'on_session'
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
return response()->json($output);
} catch (ErrorException $e) {
return response()->json(['error' => $e->getMessage()]);
}
}
/** Calculate order total for stripe */
public function calculateOrderAmount(array $items): int {
// Replace this constant with a calculation of the order's amount
// Calculate the order total on the server to prevent
// people from directly manipulating the amount on the client
foreach($items as $item){
return $item->amount * 100;
}
}
}
Create the route
Next, we will add the route inside routes/api.php.
Route::post('order/pay',[PaymentController::class,'payByStripe']);