-
-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathOrderSuccess.php
More file actions
114 lines (85 loc) · 2.78 KB
/
Copy pathOrderSuccess.php
File metadata and controls
114 lines (85 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace App\Livewire;
use App\Enums\Subscription;
use App\Models\User;
use Laravel\Cashier\Cashier;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Stripe\Exception\InvalidRequestException;
#[Layout('components.layout')]
#[Title('Thank You for Your Purchase')]
class OrderSuccess extends Component
{
public ?string $email = null;
public ?string $licenseKey = null;
public ?Subscription $subscription = null;
public string $checkoutSessionId;
public function mount(string $checkoutSessionId): void
{
$this->checkoutSessionId = $checkoutSessionId;
$this->loadData();
}
public function loadData(): void
{
$this->email = $this->loadEmail();
$this->licenseKey = $this->loadLicenseKey();
$this->subscription = $this->loadSubscription();
}
private function loadEmail(): ?string
{
if ($email = session($this->sessionKey('email'))) {
return $email;
}
try {
$checkoutSession = Cashier::stripe()->checkout->sessions->retrieve($this->checkoutSessionId);
} catch (InvalidRequestException $e) {
return $this->redirect('/mobile');
}
if (! ($email = $checkoutSession?->customer_details?->email)) {
return null;
}
session()->put($this->sessionKey('email'), $email);
return $email;
}
private function loadLicenseKey(): ?string
{
if ($licenseKey = session($this->sessionKey('license_key'))) {
return $licenseKey;
}
if (! $this->email) {
return null;
}
$user = User::where('email', $this->email)->first();
if (! $user) {
return null;
}
$license = $user->licenses()->latest()->first();
if (! $license) {
return null;
}
session()->put($this->sessionKey('license_key'), $license->key);
return $license->key;
}
private function loadSubscription(): ?Subscription
{
if ($subscription = session($this->sessionKey('subscription'))) {
return Subscription::tryFrom($subscription);
}
try {
$priceId = Cashier::stripe()->checkout->sessions->allLineItems($this->checkoutSessionId)->first()?->price->id;
} catch (InvalidRequestException $e) {
return $this->redirect('/mobile');
}
if (! $priceId) {
return null;
}
$subscription = Subscription::fromStripePriceId($priceId);
session()->put($this->sessionKey('subscription'), $subscription->value);
return $subscription;
}
private function sessionKey(string $key): string
{
return "{$this->checkoutSessionId}.{$key}";
}
}