where('order_id', $order->id)->first(); if ($existing !== null) { return $existing; } $start = now(); // The contract and its entry in the register commit together. If the // record could fail after the subscription is in, the next webhook // retry would find the contract, return early, and leave a paid sale // permanently missing from the evidence. return DB::transaction(fn () => $this->open($order, $term, $start)); } private function open(Order $order, string $term, Carbon $start): Subscription { $subscription = Subscription::create(array_merge( // The version the order carries, when the checkout recorded one: // what the customer saw beats what happens to be on sale by the // time their payment reaches us. Subscription::snapshotFrom($order->plan, $term, $order->plan_version_id), [ 'customer_id' => $order->customer_id, 'order_id' => $order->id, // Carried from the checkout: from here on, Stripe's events // name this and nothing else. 'stripe_subscription_id' => $order->stripe_subscription_id, 'started_at' => $start, 'current_period_start' => $start, 'current_period_end' => $term === Subscription::TERM_YEARLY ? $start->copy()->addYear() : $start->copy()->addMonth(), 'status' => 'active', ], )); // The sale, entered in the register the moment it happens. Written from // the contract that was just frozen, so the evidence and the contract // cannot describe different purchases. ($this->record)( event: SubscriptionRecord::EVENT_PURCHASE, subscription: $subscription, netCents: $subscription->price_cents, at: $start, stripe: ['event' => $order->stripe_event_id], // The order carries what Stripe actually took — gross, including // whatever tax or discount applied on the day. The contract price // is what was agreed; this is what was paid, and the register has // to be able to state both. // // Keyed on the Stripe id, not on the amount being non-zero: a fully // discounted checkout charges zero, and reading that as "no amount // recorded" would file a free sale as though it had been paid for // in full. An order without a Stripe id was never charged through // a checkout at all, and has nothing to report. chargedGrossCents: $order->stripe_event_id !== null ? (int) $order->amount_cents : null, ); return $subscription; } }