Files
fotospiel-app/app/Services/PayPal/PayPalGiftVoucherWebhookService.php

80 lines
2.1 KiB
PHP

<?php
namespace App\Services\PayPal;
use App\Models\GiftVoucher;
use App\Services\GiftVouchers\GiftVoucherService;
use Illuminate\Support\Arr;
class PayPalGiftVoucherWebhookService
{
public function __construct(private readonly GiftVoucherService $vouchers) {}
/**
* @param array<string, mixed> $event
*/
public function handle(array $event): bool
{
$eventType = $event['event_type'] ?? null;
$resource = $event['resource'] ?? null;
if (! is_string($eventType) || ! is_array($resource)) {
return false;
}
$normalized = strtoupper($eventType);
if (! in_array($normalized, [
'PAYMENT.CAPTURE.COMPLETED',
'PAYMENT.CAPTURE.REFUNDED',
'CHECKOUT.ORDER.COMPLETED',
], true)) {
return false;
}
$orderId = $this->resolveOrderId($normalized, $resource);
if (! $orderId) {
return false;
}
$voucher = GiftVoucher::query()
->where('paypal_order_id', $orderId)
->first();
if (! $voucher) {
return false;
}
if (in_array($normalized, ['PAYMENT.CAPTURE.COMPLETED', 'CHECKOUT.ORDER.COMPLETED'], true)) {
$this->vouchers->issueFromPayPal($voucher, $resource, $orderId);
return true;
}
if ($normalized === 'PAYMENT.CAPTURE.REFUNDED') {
$this->vouchers->markRefundedFromPayPal($voucher, $resource);
return true;
}
return false;
}
/**
* @param array<string, mixed> $resource
*/
protected function resolveOrderId(string $eventType, array $resource): ?string
{
if (str_starts_with($eventType, 'PAYMENT.CAPTURE.')) {
$relatedOrderId = Arr::get($resource, 'supplementary_data.related_ids.order_id');
return is_string($relatedOrderId) && $relatedOrderId !== '' ? $relatedOrderId : null;
}
$orderId = $resource['id'] ?? null;
return is_string($orderId) && $orderId !== '' ? $orderId : null;
}
}