Build a Shopping Cart Using Vue js 3 Composition API Laravel 11 & Stripe Payment Gateway Part 2
In the second part of this tutorial, we will create the product and order controllers, add the functions, and finally 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\Http\Controllers\Controller;
use App\Http\Resources\ProductResource;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
//
public function index()
{
return ProductResource::collection(Product::all());
}
}
Create the order controller
Next, let's install the stripe package we need.
run the command:
composer require stripe/stripe-php
once done create a new controller 'OrderController' and add the code below inside:
<?php
namespace App\Http\Controllers\Api;
use Stripe\Stripe;
use ErrorException;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use App\Http\Controllers\Controller;
class OrderController extends Controller
{
//
public function payByStripe(Request $request)
{
Stripe::setApiKey(env('STRIPE_KEY'));
try {
$checkout_session = Session::create([
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => 'Vue 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()]);
}
}
/**
* Calculate the orders total amount
*/
public function calculateTotal($price, $qty)
{
$total = $price * $qty;
return $total;
}
/**
* Calculate the amount for stripe
*/
public function calculateOrderTotal($items)
{
$total = 0;
//calculate the total amount of cart items
foreach ($items as $item) {
$total += $this->calculateTotal($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\OrderController;
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('order/store', [OrderController::class, 'store']);
Route::post('order/pay', [OrderController::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"