diff --git a/README.md b/README.md index 21e45b4..cc8f690 100644 --- a/README.md +++ b/README.md @@ -562,7 +562,8 @@ subscriptions it created (plus those of clients delegated to it). Failures throw `Anikeen\Id\Exceptions\ApiException` with `status` (0 = not reachable), a stable `error` code (`already_active`, `already_cancelled`, `not_active`, `already_paused`, `already_resumed`, `billing_address_missing`, `not_changeable`, `subscription_not_found`, -`idempotency_key_conflict`, `in_checkout_session`, `trial_already_used`) and `isNotFound()`, `isConflict()`, `isTemporary()`: +`idempotency_key_conflict`, `in_checkout_session`, `trial_already_used`, `proration_not_possible`, +`credit_exceeds_bill`) and `isNotFound()`, `isConflict()`, `isTemporary()`: ```php try { @@ -578,6 +579,43 @@ try { } ``` +### Changing running subscriptions (trusted apps) + +`update()` changes a subscription before its checkout (afterwards only the description). +`change()` changes price, unit, name, description or discount of a running subscription, like a +plan change (send only what changes): + +```php +use Anikeen\Id\Resources\AppSubscription; + +// upgrade now, prorated: the unused rest of the period is credited, the new price charged for it +$subscription->change(['apply' => AppSubscription::APPLY_NOW, 'price' => '0.0274', 'name' => 'Cloud Server M']); + +// downgrade from the next period on +$subscription->change(['apply' => AppSubscription::APPLY_PERIOD_END, 'price' => '4.99']); +$subscription->scheduled_change; // {applies_at, name, description, unit, price, discount, created_at} +$subscription->cancelScheduledChange(); // keep the current values after all +``` + +- `now` credits the unused part of the current period at the rate it was billed at and charges + the rest at the new price, both on the user's open bill. A new `unit` starts a new, fully billed + period now. A downgrade whose credit would exceed the open bill is refused with 409 + `credit_exceeds_bill`: schedule it for the period end instead. 409 `proration_not_possible` when + the current period wasn't billed to the subscription (e.g. a takeover); `period_end` works. +- `period_end` changes nothing now; the next period is billed at the new values. A new + `period_end` change replaces the scheduled one, `now` drops it. +- During a free trial nothing was billed: both just change what the trial ends in. +- `discount` replaces the discount from the next billed period on, `null` ends it. When the unit + changes, a discount that counts in periods or an `amount_off` has to be sent again (422). +- Subscriptions with a monthly cap change only with `period_end`. +- Only running subscriptions can change: 409 `not_changeable` for drafts (use `update()`), paused, + cancelling, expired and cancelled ones. + +When a change takes effect (right away or at the period end), Anikeen ID sends +`subscription.updated` (`EventType::SUBSCRIPTION_UPDATED`) with the old values of the changed +fields in `$event['data']['previous_attributes']`. Telling the user about a price increase (and +getting consent where needed) is up to your app. + ### App orders (trusted apps, no user token) Orders that bill the app's subscriptions, read with the app's token (scope `orders:client`): diff --git a/README.stub b/README.stub index fc74eb8..df8e484 100644 --- a/README.stub +++ b/README.stub @@ -562,7 +562,8 @@ subscriptions it created (plus those of clients delegated to it). Failures throw `Anikeen\Id\Exceptions\ApiException` with `status` (0 = not reachable), a stable `error` code (`already_active`, `already_cancelled`, `not_active`, `already_paused`, `already_resumed`, `billing_address_missing`, `not_changeable`, `subscription_not_found`, -`idempotency_key_conflict`, `in_checkout_session`, `trial_already_used`) and `isNotFound()`, `isConflict()`, `isTemporary()`: +`idempotency_key_conflict`, `in_checkout_session`, `trial_already_used`, `proration_not_possible`, +`credit_exceeds_bill`) and `isNotFound()`, `isConflict()`, `isTemporary()`: ```php try { @@ -578,6 +579,43 @@ try { } ``` +### Changing running subscriptions (trusted apps) + +`update()` changes a subscription before its checkout (afterwards only the description). +`change()` changes price, unit, name, description or discount of a running subscription, like a +plan change (send only what changes): + +```php +use Anikeen\Id\Resources\AppSubscription; + +// upgrade now, prorated: the unused rest of the period is credited, the new price charged for it +$subscription->change(['apply' => AppSubscription::APPLY_NOW, 'price' => '0.0274', 'name' => 'Cloud Server M']); + +// downgrade from the next period on +$subscription->change(['apply' => AppSubscription::APPLY_PERIOD_END, 'price' => '4.99']); +$subscription->scheduled_change; // {applies_at, name, description, unit, price, discount, created_at} +$subscription->cancelScheduledChange(); // keep the current values after all +``` + +- `now` credits the unused part of the current period at the rate it was billed at and charges + the rest at the new price, both on the user's open bill. A new `unit` starts a new, fully billed + period now. A downgrade whose credit would exceed the open bill is refused with 409 + `credit_exceeds_bill`: schedule it for the period end instead. 409 `proration_not_possible` when + the current period wasn't billed to the subscription (e.g. a takeover); `period_end` works. +- `period_end` changes nothing now; the next period is billed at the new values. A new + `period_end` change replaces the scheduled one, `now` drops it. +- During a free trial nothing was billed: both just change what the trial ends in. +- `discount` replaces the discount from the next billed period on, `null` ends it. When the unit + changes, a discount that counts in periods or an `amount_off` has to be sent again (422). +- Subscriptions with a monthly cap change only with `period_end`. +- Only running subscriptions can change: 409 `not_changeable` for drafts (use `update()`), paused, + cancelling, expired and cancelled ones. + +When a change takes effect (right away or at the period end), Anikeen ID sends +`subscription.updated` (`EventType::SUBSCRIPTION_UPDATED`) with the old values of the changed +fields in `$event['data']['previous_attributes']`. Telling the user about a price increase (and +getting consent where needed) is up to your app. + ### App orders (trusted apps, no user token) Orders that bill the app's subscriptions, read with the app's token (scope `orders:client`): diff --git a/src/Id/Resources/AppSubscription.php b/src/Id/Resources/AppSubscription.php index 5ea2150..3c7f622 100644 --- a/src/Id/Resources/AppSubscription.php +++ b/src/Id/Resources/AppSubscription.php @@ -37,11 +37,18 @@ use JsonSerializable; * @property ?array $payload * @property ?string $idempotency_key * @property ?string $checkout_session_id the checkout session the user confirms it in, if any + * @property ?object $scheduled_change {applies_at, name, description, unit, price, discount, created_at}: a change() for the period end */ class AppSubscription implements JsonSerializable { use HasSubscriptionStatus; + /** change(): prorated, right away. */ + public const APPLY_NOW = 'now'; + + /** change(): from the next period on (scheduled_change until then). */ + public const APPLY_PERIOD_END = 'period_end'; + public function __construct(protected object $data) { } @@ -60,6 +67,7 @@ class AppSubscription implements JsonSerializable * Change a subscription (send only what changes). Before checkout everything can change; * afterwards only the description, which names what the customer pays for and is shown * on their bills, e.g. `$subscription->update(['description' => 'web-01.example.com'])`. + * Prices of running subscriptions change with change(). * * @throws ApiException */ @@ -68,6 +76,51 @@ class AppSubscription implements JsonSerializable return $this->send('PUT', '', $attributes); } + /** + * Change a running subscription (send only what changes), like a plan change: + * + * - `apply: now`: prorated – the unused rest of the current period is credited at the rate it + * was billed at and charged at the new price on the user's open bill. A new unit starts a + * new, fully billed period now. A downgrade whose credit exceeds the open bill is refused + * (409 "credit_exceeds_bill"): schedule it for the period end instead. + * - `apply: period_end`: nothing changes now; the subscription has `scheduled_change` and the + * next period is billed at the new values. A new scheduled change replaces the previous one. + * + * During a free trial nothing was billed, so both just change what the trial ends in. + * Webhook `subscription.updated` (with `data.previous_attributes`) when the change takes effect. + * + * @param array{ + * apply: string, + * price?: float|string, + * unit?: string, + * name?: string, + * description?: null|string, + * discount?: null|array{label: string, percent_off?: float|string, amount_off?: float|string, duration: string, duration_in_periods?: int} + * } $attributes apply: self::APPLY_NOW or self::APPLY_PERIOD_END. + * unit: a recurring unit (hour, day, week, month, year). + * discount: replaces the discount from the next billed period on, null ends it; + * required with a new unit when the current one counts in periods or is an + * amount_off. Subscriptions with a monthly cap change only at the period end. + * + * @throws ApiException 409 "not_changeable" (not running: draft, paused, cancelling, …), + * "proration_not_possible", "credit_exceeds_bill", + * "billing_address_missing"; 422 validation + */ + public function change(array $attributes): self + { + return $this->send('PUT', '/change', $attributes); + } + + /** + * Drop the change scheduled for the period end (nothing happens without one). + * + * @throws ApiException + */ + public function cancelScheduledChange(): self + { + return $this->send('DELETE', '/change'); + } + /** * Activate the subscription and bill its first period. * diff --git a/src/Id/Webhooks/EventType.php b/src/Id/Webhooks/EventType.php index 77208f2..d394cb9 100644 --- a/src/Id/Webhooks/EventType.php +++ b/src/Id/Webhooks/EventType.php @@ -27,6 +27,12 @@ final class EventType /** The last discounted period of a subscription was billed; the following ones are billed at the full price. */ public const SUBSCRIPTION_DISCOUNT_ENDED = 'subscription.discount_ended'; + /** + * The price, unit, name, description or discount of a running subscription changed (right away + * or at the period end); `data.previous_attributes` has the changed fields' old values. + */ + public const SUBSCRIPTION_UPDATED = 'subscription.updated'; + /** The user confirmed a checkout session: all of its subscriptions are running (sent after their subscription.activated). */ public const CHECKOUT_COMPLETED = 'checkout.completed'; diff --git a/tests/Id/AppSubscriptionsTest.php b/tests/Id/AppSubscriptionsTest.php index fbf1111..c9717e4 100644 --- a/tests/Id/AppSubscriptionsTest.php +++ b/tests/Id/AppSubscriptionsTest.php @@ -5,6 +5,7 @@ namespace Anikeen\Id\Tests; use Anikeen\Id\AnikeenId; use Anikeen\Id\Billable; use Anikeen\Id\Exceptions\ApiException; +use Anikeen\Id\Resources\AppSubscription; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Psr7\Request; use Illuminate\Database\Eloquent\Model; @@ -215,6 +216,43 @@ class AppSubscriptionsTest extends TestCase $this->assertSame(3, $subscription->discount->periods_remaining); } + public function test_a_running_subscription_is_changed_now_or_at_the_period_end(): void + { + $change = ['applies_at' => '2026-12-01T00:00:00+00:00', 'name' => 'Pro', 'description' => null, 'unit' => 'month', 'price' => 14.99, 'discount' => null, 'created_at' => '2026-11-04T10:00:00+00:00']; + $this->respond(200, $this->subscription(['active' => true, 'price' => 14.99])); + $this->respond(200, $this->subscription(['active' => true, 'price' => 14.99, 'scheduled_change' => $change])); + $this->respond(200, $this->subscription(['active' => true, 'price' => 14.99, 'scheduled_change' => null])); + + $subscription = new AppSubscription((object) $this->subscription(['active' => true])['data']); + + $this->assertSame(14.99, $subscription->change(['apply' => AppSubscription::APPLY_NOW, 'price' => '14.99', 'discount' => null])->price); + $this->assertSame('2026-12-01T00:00:00+00:00', $subscription->change(['apply' => AppSubscription::APPLY_PERIOD_END, 'unit' => 'month', 'name' => 'Pro'])->scheduled_change->applies_at); + $this->assertNull($subscription->cancelScheduledChange()->scheduled_change); + + $this->assertSame([ + 'PUT /api/v1/client/subscriptions/01JSUB/change Bearer app-token', + 'PUT /api/v1/client/subscriptions/01JSUB/change Bearer app-token', + 'DELETE /api/v1/client/subscriptions/01JSUB/change Bearer app-token', + ], array_map(fn ($entry) => $entry['request']->getMethod() . ' ' . $entry['request']->getUri()->getPath() . ' ' . $entry['request']->getHeaderLine('Authorization'), $this->sent)); + $this->assertSame(['apply' => 'now', 'price' => '14.99', 'discount' => null], $this->sentJson(0)); + $this->assertSame(['apply' => 'period_end', 'unit' => 'month', 'name' => 'Pro'], $this->sentJson(1)); + } + + public function test_a_refused_change_carries_its_error_code(): void + { + $this->respond(409, ['message' => 'The credit would exceed the open bill.', 'error' => 'credit_exceeds_bill']); + + $subscription = new AppSubscription((object) $this->subscription(['active' => true])['data']); + + try { + $subscription->change(['apply' => AppSubscription::APPLY_NOW, 'price' => '1.99']); + $this->fail('Expected an ApiException.'); + } catch (ApiException $e) { + $this->assertTrue($e->isConflict()); + $this->assertSame('credit_exceeds_bill', $e->error); + } + } + public function test_a_missing_user_id_is_reported(): void { $this->expectException(InvalidArgumentException::class); diff --git a/tests/Id/CheckoutSessionsTest.php b/tests/Id/CheckoutSessionsTest.php index 764c3a5..675adad 100644 --- a/tests/Id/CheckoutSessionsTest.php +++ b/tests/Id/CheckoutSessionsTest.php @@ -187,5 +187,6 @@ class CheckoutSessionsTest extends TestCase $this->assertContains('subscription.activated', EventType::all()); $this->assertContains('subscription.trial_will_end', EventType::all()); $this->assertContains('subscription.discount_ended', EventType::all()); + $this->assertContains('subscription.updated', EventType::all()); } }