It is useful to have the orders and products stored locally in addition to syncing them with Stripe. This allows for easier management and tracking of orders and products.
To associate the order with the unfulfilled order in the database, you can use the Stripe webhook to return the order ID and update the paid field. Here's an example of how to do this:
- Create a webhook endpoint in your Laravel application to receive the Stripe webhook. You can use the
stripe-phplibrary to handle the webhook.
Route::post('/stripe/webhook', function (Request $request) {
$payload = $request->getContent();
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, config('services.stripe.webhook_secret')
);
} catch (\UnexpectedValueException $e) {
// Invalid payload
return response()->json(['error' => $e->getMessage()], 400);
} catch (\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
return response()->json(['error' => $e->getMessage()], 400);
}
// Handle the event
switch ($event->type) {
case 'checkout.session.completed':
$session = $event->data->object;
$order_id = $session->metadata->order_id;
$order = Order::find($order_id);
$order->paid = true;
$order->save();
break;
// Handle other event types
}
return response()->json(['success' => true]);
});
- When creating the Stripe checkout session, include the order ID as metadata so that it can be retrieved in the webhook.
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [
[
'price_data' => [
'currency' => 'usd',
'unit_amount' => 1000,
'product_data' => [
'name' => 'Product Name',
],
],
'quantity' => 1,
],
],
'mode' => 'payment',
'success_url' => 'https://example.com/success',
'cancel_url' => 'https://example.com/cancel',
'metadata' => [
'order_id' => $order->id,
],
]);
- When the user clicks the button to create the order, create a new order in the database with the
paidfield set tofalse.
$order = new Order;
$order->customer_id = $customer->id;
$order->service_id = $service->id;
$order->price = $service->price;
$order->paid = false;
$order->save();
- When the webhook is received, update the
paidfield of the corresponding order in the database.
$order_id = $session->metadata->order_id;
$order = Order::find($order_id);
$order->paid = true;
$order->save();