-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathCreateAnystackLicenseJob.php
More file actions
85 lines (71 loc) · 2.46 KB
/
CreateAnystackLicenseJob.php
File metadata and controls
85 lines (71 loc) · 2.46 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
<?php
namespace App\Jobs;
use App\Enums\Subscription;
use App\Models\User;
use App\Notifications\LicenseKeyGenerated;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class CreateAnystackLicenseJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public User $user,
public Subscription $subscription,
public ?string $firstName = null,
public ?string $lastName = null,
) {}
public function handle(): void
{
if (! $this->user->anystack_contact_id) {
$contact = $this->createContact();
$this->user->anystack_contact_id = $contact['id'];
$this->user->save();
}
$license = $this->createLicense($this->user->anystack_contact_id);
Cache::put($this->user->email.'.license_key', $license['key'], now()->addDay());
$this->user->notify(new LicenseKeyGenerated(
$license['key'],
$this->subscription,
$this->firstName
));
}
private function createContact(): array
{
$data = collect([
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'email' => $this->user->email,
])
->filter()
->all();
// TODO: If an existing contact with the same email address already exists,
// anystack will return a 422 validation error response.
return $this->anystackClient()
->post('https://api.anystack.sh/v1/contacts', $data)
->throw()
->json('data');
}
private function createLicense(string $contactId): ?array
{
$data = [
'policy_id' => $this->subscription->anystackPolicyId(),
'contact_id' => $contactId,
];
return $this->anystackClient()
->post("https://api.anystack.sh/v1/products/{$this->subscription->anystackProductId()}/licenses", $data)
->throw()
->json('data');
}
private function anystackClient(): PendingRequest
{
return Http::withToken(config('services.anystack.key'))
->acceptJson()
->asJson();
}
}