From 3c101b8f847855f24fc2730deff558d4a18b8796 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=2E=20Nagy=20Gerg=C5=91?= Date: Tue, 6 Feb 2024 09:26:28 +0100 Subject: [PATCH] wip --- .../HandlePaymentIntentSucceededEvent.php | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/src/Listeners/HandlePaymentIntentSucceededEvent.php b/src/Listeners/HandlePaymentIntentSucceededEvent.php index 040596d..ceb2f76 100644 --- a/src/Listeners/HandlePaymentIntentSucceededEvent.php +++ b/src/Listeners/HandlePaymentIntentSucceededEvent.php @@ -6,6 +6,7 @@ use Cone\Bazar\Models\Transaction; use Cone\Bazar\Stripe\Events\StripeWebhookInvoked; use Cone\Bazar\Support\Facades\Gateway; +use Illuminate\Support\Facades\Date; use Stripe\Event; use Throwable; @@ -16,23 +17,29 @@ class HandlePaymentIntentSucceededEvent */ public function handle(StripeWebhookInvoked $event): void { + $order = Order::proxy() + ->newQuery() + ->where('uuid', $event->event->data['object']['metadata']['order']) + ->firstOrFail(); + switch ($event->event->type) { + case 'charge.refunded': + $this->handleRefund($event->event, $order); + break; case 'payment_intent.succeeded': - $this->completeTransaction($event->event); + $this->handlePayment($event->event, $order); break; } } /** - * Handle payment. + * Handle the payment. */ - public function completeTransaction(Event $event): void + public function handlePayment(Event $event, Order $order): void { try { $transaction = Transaction::proxy()->newQuery()->where('key', $event->data['object']['id'])->firstOrFail(); } catch (Throwable $exception) { - $order = Order::proxy()->newQuery()->where('uuid', $event->data['object']['metadata']['order'])->firstOrFail(); - $transaction = Gateway::driver('stripe')->pay( $order, $event->data['object']['amount'] / 100, @@ -42,4 +49,20 @@ public function completeTransaction(Event $event): void $transaction->markAsCompleted(); } + + /** + * Handle the refund. + */ + public function handleRefund(Event $event, Order $order): void + { + foreach ($event->data['refunds']['data'] as $refund) { + if (is_null($order->transactions->firstWhere('key', $refund['id']))) { + Gateway::driver('stripe')->refund( + $order, + $refund['amount'] / 100, + ['key' => $refund['id'], 'completed_at' => Date::now()] + ); + } + } + } }