Files
fotospiel-app/app/Services/GiftVouchers/GiftVoucherCheckoutService.php
2026-02-03 10:59:54 +01:00

94 lines
3.2 KiB
PHP

<?php
namespace App\Services\GiftVouchers;
use App\Services\LemonSqueezy\LemonSqueezyCheckoutService;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class GiftVoucherCheckoutService
{
public function __construct(private readonly LemonSqueezyCheckoutService $checkout) {}
/**
* @return array<int, array{key:string,label:string,amount:float,currency:string,lemonsqueezy_variant_id?:string|null,can_checkout:bool}>
*/
public function tiers(): array
{
return collect(config('gift-vouchers.tiers', []))
->map(function (array $tier): array {
$currency = Str::upper($tier['currency'] ?? 'EUR');
$variantId = $tier['lemonsqueezy_variant_id'] ?? null;
return [
'key' => $tier['key'],
'label' => $tier['label'],
'amount' => (float) $tier['amount'],
'currency' => $currency,
'lemonsqueezy_variant_id' => $variantId,
'can_checkout' => ! empty($variantId),
];
})
->values()
->all();
}
/**
* @param array{tier_key:string,purchaser_email:string,recipient_email?:string|null,recipient_name?:string|null,message?:string|null,success_url?:string|null,return_url?:string|null} $data
* @return array{checkout_url:?string,expires_at:?string,id:?string}
*/
public function create(array $data): array
{
$tier = $this->findTier($data['tier_key']);
if (! $tier || empty($tier['lemonsqueezy_variant_id'])) {
throw ValidationException::withMessages([
'tier_key' => __('Gift voucher is not available right now.'),
]);
}
$customData = array_filter([
'type' => 'gift_voucher',
'tier_key' => $tier['key'],
'purchaser_email' => $data['purchaser_email'],
'recipient_email' => $data['recipient_email'] ?? null,
'recipient_name' => $data['recipient_name'] ?? null,
'message' => $data['message'] ?? null,
'app_locale' => App::getLocale(),
'success_url' => $data['success_url'] ?? null,
'return_url' => $data['return_url'] ?? null,
'lemonsqueezy_variant_id' => $tier['lemonsqueezy_variant_id'],
], static fn ($value) => $value !== null && $value !== '');
return $this->checkout->createVariantCheckout(
(string) $tier['lemonsqueezy_variant_id'],
$customData,
[
'success_url' => $data['success_url'] ?? null,
'return_url' => $data['return_url'] ?? null,
'customer_email' => $data['purchaser_email'],
]
);
}
/**
* @return array<string, mixed>|null
*/
protected function findTier(string $key): ?array
{
$tiers = collect(config('gift-vouchers.tiers', []))
->keyBy('key');
$tier = $tiers->get($key);
if (! $tier) {
return null;
}
$tier['currency'] = Str::upper($tier['currency'] ?? 'EUR');
return $tier;
}
}