1 <?php 2 3 namespace App\Jobs; 4 5 use App\Models\Subscription; 6 use App\Notifications\SubscriptionRenewed; 7 use App\Services\Billing\PaymentGateway; 8 use Illuminate\Contracts\Queue\ShouldQueue; 9 use Illuminate\Foundation\Queue\Queueable; 10 use Illuminate\Support\Facades\DB; 11 12 class RenewSubscription implements ShouldQueue 13 { 14 use Queueable; 15 16 public int $tries = 3; 17 18 public function __construct(public Subscription $subscription) {} 19 20 public function handle(PaymentGateway $gateway): void 21 { 22 $subscription = $this->subscription; 23 24 DB::transaction(function () use ($subscription, $gateway) { 25 $charge = $gateway->charge( 26 customerId: $subscription->user->billing_id, 27 amountCents: $subscription->plan->price_cents, 28 ); 29 30 $periodStart = $subscription->renews_at; 31 $periodEnd = $periodStart->copy()->addMonth(); 32 33 $subscription->payments()->create([ 34 'charge_id' => $charge->id, 35 'amount_cents' => $charge->amountCents, 36 'period_start' => $periodStart, 37 'period_end' => $periodEnd, 38 ]); 39 40 $subscription->update([ 41 'renews_at' => $periodEnd, 42 'grace_ends_at' => $periodEnd->addDays(3), 43 ]); 44 }); 45 46 $subscription->user->notify(new SubscriptionRenewed($subscription)); 47 } 48 }