Nyavokevin 9e5cc5ab1a
Some checks failed
linter / quality (push) Has been cancelled
tests / ci (push) Has been cancelled
add dark theme
2025-09-18 20:34:07 +03:00

73 lines
2.9 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Payment; // Make sure this is imported
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Webhook;
use Stripe\Exception\SignatureVerificationException;
use Log; // Import the Log facade
use DateTime;
class WebhookController extends Controller
{
public function handleWebhook(Request $request)
{
Stripe::setApiKey(env('STRIPE_SECRET_KEY'));
$payload = $request->getContent();
$signature = $request->header('Stripe-Signature');
$endpointSecret = env('STRIPE_WEBHOOK_SECRET');
try {
$event = Webhook::constructEvent($payload, $signature, $endpointSecret);
} catch (SignatureVerificationException $e) {
Log::error('Stripe webhook signature verification failed: ' . $e->getMessage());
return response()->json(['error' => 'Invalid signature'], 400);
}
try {
// Handle the event
switch ($event->type) {
case 'checkout.session.completed':
$session = $event->data->object;
$clientSessionId = $session->metadata->client_session_id;
$payment = Payment::where('client_session_id', $clientSessionId)->first();
if ($payment) {
if (isset($session->metadata->type_appointment) && $session->metadata->type_appointment === 'true') {
$dateTimeObj = new DateTime($session->metadata->appointment_date);
$payment->update([
'status' => 'succeeded',
'appointment_date' => $dateTimeObj->format('Y-m-d')
]);
} else {
// Original logic for other payments
$drawCount = $session->metadata->draw_count;
$payment->update([
'status' => 'succeeded',
'draw_count' => $drawCount,
]);
}
} else {
// Log if no matching payment record is found
Log::warning('No pending payment record found for client_session_id: ' . $clientSessionId);
}
break;
default:
Log::info('Received a non-checkout.session.completed webhook event: ' . $event->type);
break;
}
} catch (\Exception $e) {
// Log any other unexpected errors
Log::error('Stripe webhook processing error: ' . $e->getMessage(), ['exception' => $e]);
return response()->json(['error' => 'Server error'], 500);
}
return response()->json(['status' => 'success'], 200);
}
}