|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Jobs; |
| 4 | + |
| 5 | +use App\Enums\Subscription; |
| 6 | +use App\Notifications\LicenseKeyGenerated; |
| 7 | +use Illuminate\Bus\Queueable; |
| 8 | +use Illuminate\Contracts\Queue\ShouldQueue; |
| 9 | +use Illuminate\Foundation\Bus\Dispatchable; |
| 10 | +use Illuminate\Http\Client\PendingRequest; |
| 11 | +use Illuminate\Queue\InteractsWithQueue; |
| 12 | +use Illuminate\Queue\SerializesModels; |
| 13 | +use Illuminate\Support\Facades\Cache; |
| 14 | +use Illuminate\Support\Facades\Http; |
| 15 | +use Illuminate\Support\Facades\Notification; |
| 16 | + |
| 17 | +class CreateAnystackLicenseJob implements ShouldQueue |
| 18 | +{ |
| 19 | + use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; |
| 20 | + |
| 21 | + public function __construct( |
| 22 | + public string $email, |
| 23 | + public Subscription $subscription, |
| 24 | + public ?string $firstName = null, |
| 25 | + public ?string $lastName = null, |
| 26 | + ) {} |
| 27 | + |
| 28 | + public function handle(): void |
| 29 | + { |
| 30 | + $contact = $this->createContact(); |
| 31 | + |
| 32 | + $license = $this->createLicense($contact['id']); |
| 33 | + |
| 34 | + Cache::put($this->email.'.license_key', $license['key'], now()->addDay()); |
| 35 | + |
| 36 | + Notification::route('mail', $this->email) |
| 37 | + ->notify(new LicenseKeyGenerated( |
| 38 | + $license['key'], |
| 39 | + $this->subscription, |
| 40 | + $this->firstName |
| 41 | + )); |
| 42 | + } |
| 43 | + |
| 44 | + private function createContact(): array |
| 45 | + { |
| 46 | + $data = collect([ |
| 47 | + 'first_name' => $this->firstName, |
| 48 | + 'last_name' => $this->lastName, |
| 49 | + 'email' => $this->email, |
| 50 | + ]) |
| 51 | + ->filter() |
| 52 | + ->all(); |
| 53 | + |
| 54 | + // TODO: If an existing contact with the same email address already exists, |
| 55 | + // anystack will return a 422 validation error response. |
| 56 | + return $this->anystackClient() |
| 57 | + ->post('https://api.anystack.sh/v1/contacts', $data) |
| 58 | + ->throw() |
| 59 | + ->json('data'); |
| 60 | + } |
| 61 | + |
| 62 | + private function createLicense(string $contactId): ?array |
| 63 | + { |
| 64 | + $data = [ |
| 65 | + 'policy_id' => $this->subscription->anystackPolicyId(), |
| 66 | + 'contact_id' => $contactId, |
| 67 | + ]; |
| 68 | + |
| 69 | + return $this->anystackClient() |
| 70 | + ->post("https://api.anystack.sh/v1/products/{$this->subscription->anystackProductId()}/licenses", $data) |
| 71 | + ->throw() |
| 72 | + ->json('data'); |
| 73 | + } |
| 74 | + |
| 75 | + private function anystackClient(): PendingRequest |
| 76 | + { |
| 77 | + return Http::withToken(config('services.anystack.key')) |
| 78 | + ->acceptJson() |
| 79 | + ->asJson(); |
| 80 | + } |
| 81 | +} |
0 commit comments