Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 2
In the second part of this tutorial, we will create the product and payment controllers, and later we will add the functions, and finally, we will add the API routes.
Create the product controller and resource
Next, create a new controller 'ProductController' and a new resource 'ProductResource' and add the code below in the product controller:
<?php
namespace App\Http\Controllers\Api;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProductResource;
class ProductController extends Controller
{
//
public function index()
{
return ProductResource::collection(Product::latest()->get());
}
}
Create the PaymentController
Next, let's install the stripe package we need.
run the command:
composer require stripe/stripe-php
once done create a new controller 'PaymentController' and add the code below inside:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use ErrorException;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use Stripe\Stripe;
class PaymentController extends Controller
{
//
public function payByStripe(Request $request)
{
//provide the stripe key
Stripe::setApiKey(env('STRIPE_KEY'));
try {
$checkout_session = Session::create([
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => 'React Shop Orders'
],
'unit_amount' => $this->calculateOrderTotal($request->cartItems),
],
'quantity' => 1
]],
'mode' => 'payment',
'success_url' => $request->success_url
]);
return response()->json([
'url' => $checkout_session->url
]);
} catch (ErrorException $e) {
return response()->json([
'error' => $e->getMessage()
]);
}
}
public function calculateOrderTotal($items)
{
$total = 0;
foreach ($items as $item) {
$total += $item['product_price'] * $item['quantity'];
}
return $total * 100;
}
}
Adding the routes
Next, to add the API routes to Laravel 11 run the command:
php artisan install:api
once done inside the file 'api.php' add the code below:
<?php
use App\Http\Controllers\Api\PaymentController;
use App\Http\Controllers\Api\ProductController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Route::get('/user', function (Request $request) {
// return $request->user();
// })->middleware('auth:sanctum');
Route::get('products', [ProductController::class, 'index']);
Route::post('pay/order', [PaymentController::class, 'payByStripe']);
Update the file .env
Inside the .env file grab the stripe secret key and add a new env variable to hold the secret key.
STRIPE_KEY="YOUR SECRET KEY"