|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Data\Cashier; |
| 6 | + |
| 7 | +use App\Models\Organization; |
| 8 | +use function App\Support\tenant; |
| 9 | + |
| 10 | +use Filament\Pages\Dashboard; |
| 11 | +use Illuminate\Support\Arr; |
| 12 | +use InvalidArgumentException; |
| 13 | + |
| 14 | +readonly class Stripe |
| 15 | +{ |
| 16 | + private function __construct( |
| 17 | + private int $trialDays, |
| 18 | + private bool $allowPromotionCodes, |
| 19 | + private array $billedPeriods, |
| 20 | + private array $plans |
| 21 | + ) { |
| 22 | + } |
| 23 | + |
| 24 | + public static function fromConfig(): self |
| 25 | + { |
| 26 | + return new self( |
| 27 | + trialDays: config('stripe.trial_days'), |
| 28 | + allowPromotionCodes: config('stripe.allow_promotion_codes'), |
| 29 | + billedPeriods: config('stripe.billed_periods'), |
| 30 | + plans: config('stripe.plans'), |
| 31 | + ); |
| 32 | + } |
| 33 | + |
| 34 | + public function trialDays(): int |
| 35 | + { |
| 36 | + return $this->trialDays; |
| 37 | + } |
| 38 | + |
| 39 | + public function allowPromotionCodes(): bool |
| 40 | + { |
| 41 | + return $this->allowPromotionCodes; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @return array<Plan> |
| 46 | + */ |
| 47 | + public function plans(): array |
| 48 | + { |
| 49 | + return array_map( |
| 50 | + fn (array $plan, string $key) => Plan::fromArray($plan, $key), |
| 51 | + $this->plans, |
| 52 | + array_keys($this->plans) |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + public function billedPeriods(): array |
| 57 | + { |
| 58 | + return $this->billedPeriods; |
| 59 | + } |
| 60 | + |
| 61 | + public function checkoutUrl(string $period): void |
| 62 | + { |
| 63 | + |
| 64 | + $plan = Arr::first($this->plans()); |
| 65 | + |
| 66 | + if (! $plan) { |
| 67 | + throw new InvalidArgumentException('Plan not configured'); |
| 68 | + } |
| 69 | + |
| 70 | + /** @var Price|null $price */ |
| 71 | + $price = collect($plan->prices()) |
| 72 | + ->first(fn (Price $price) => $price->period() === $period); |
| 73 | + |
| 74 | + if (! $price) { |
| 75 | + throw new InvalidArgumentException("Price not found for period: {$period}"); |
| 76 | + } |
| 77 | + |
| 78 | + $tenant = tenant(Organization::class); |
| 79 | + |
| 80 | + $tenant->newSubscription($plan->type(), $price->id()) |
| 81 | + ->checkout([ |
| 82 | + 'success_url' => Dashboard::getUrl(), |
| 83 | + 'cancel_url' => Dashboard::getUrl(), |
| 84 | + ]) |
| 85 | + ->redirect(); |
| 86 | + } |
| 87 | +} |
0 commit comments