mirror of
https://github.com/anikeen-com/id.git
synced 2026-11-06 23:58:35 +00:00
Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
556daadbbe | ||
|
|
70d6fae5a1 | ||
|
|
37e7e659e2 | ||
|
|
c5cb4b76c9 | ||
|
|
2b47be157b | ||
|
|
2796befc7d | ||
|
|
64ccb84987 | ||
|
|
7813e8fbaa | ||
|
|
27e868720f | ||
|
|
0dfc6f51fc | ||
|
|
dc9d54fc06 | ||
|
|
fb71b172f2 | ||
|
|
72f761b077
|
||
|
|
e8432df997
|
||
|
|
d99512a359
|
||
|
|
ade2970272
|
||
|
|
a54b5fe598
|
||
|
|
a68e9ed257
|
||
|
|
0ed6934da3 | ||
|
|
df7e506a5e
|
||
|
|
7f16155701
|
||
|
|
35ca9ddd2b
|
||
|
|
e45a871ca7
|
||
|
|
bd56f114da
|
||
|
|
db3c50af72
|
||
|
|
bf21142f72
|
||
|
|
5cc1a519c3
|
||
|
|
61385df92f | ||
|
|
57ce0b4a79
|
||
|
|
a4345e72ec | ||
|
|
ce820cd198
|
||
|
|
2faccac0f4
|
||
|
|
e3e59fb8a4
|
||
|
|
26716e7bba
|
||
|
|
2acbef72c8
|
||
|
|
396eb889c4 |
No files matched your search
@@ -0,0 +1,46 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 3.3.0 (2026-11-06)
|
||||||
|
|
||||||
|
App billing features; they need an Anikeen ID release that supports them.
|
||||||
|
|
||||||
|
- Free trials: `trial_days` / `trial_ends_at` (optional `trial_once`, `trial_payment_method` with
|
||||||
|
`TrialPaymentMethod::REQUIRED` / `OPTIONAL`) when creating subscriptions and checkout sessions;
|
||||||
|
`Subscription::isTrial()`.
|
||||||
|
- Discounts per billed period: `discount` with `percent_off` or `amount_off`, `duration` and `label`.
|
||||||
|
- Plan changes of running subscriptions: `AppSubscription::change()` (`apply: now` or
|
||||||
|
`period_end`) and `AppSubscription::cancelScheduledChange()`.
|
||||||
|
- App orders: order lines with subscription, period, net amount and discount;
|
||||||
|
`AppOrders::invoicePdf()`. Confirmable orders of trusted apps (`confirm: true`).
|
||||||
|
- Billing portal links that work without a login: `createBillingPortalLinkForUser()` and
|
||||||
|
`appBillingPortalUrl()`.
|
||||||
|
- Webhook events `subscription.trial_will_end`, `subscription.discount_ended`,
|
||||||
|
`subscription.updated` and `subscription.renewed` (`EventType::SUBSCRIPTION_*`);
|
||||||
|
`data.reason` with `CancellationReason::TRIAL_ENDED_WITHOUT_PAYMENT_METHOD`.
|
||||||
|
|
||||||
|
## 3.2.0 (2026-11-06)
|
||||||
|
|
||||||
|
Elapsed-period billing and user lookup; they need an Anikeen ID release that supports them.
|
||||||
|
|
||||||
|
- `AppSubscription::checkout()` takes `billElapsedPeriods` and `maxNetAmount`: a subscription
|
||||||
|
started more than one period ago is billed for its elapsed periods too, up to the given net
|
||||||
|
amount (409 `elapsed_amount_exceeded` with `net_amount`, `elapsed_periods_not_allowed`). Calls
|
||||||
|
without the new arguments send the same request as before.
|
||||||
|
- `ApiException::body()` returns the JSON body of Anikeen ID's error response, e.g. its
|
||||||
|
`net_amount`.
|
||||||
|
- Add `AnikeenId::findUserByEmail()` for trusted apps: looks up an account by email address
|
||||||
|
(regardless of case) without creating one, null when there is none.
|
||||||
|
- `createUser()` documents `name`, `password_confirmation` and `send_invitation` (a newly created
|
||||||
|
account gets an invitation mail to set a password) and the response fields `created` and
|
||||||
|
`invitation_sent`.
|
||||||
|
|
||||||
|
## 3.1.0 (2026-11-05)
|
||||||
|
|
||||||
|
- Add the scope `products:read` (`Scope::PRODUCTS_READ`) for read-only access to the product APIs
|
||||||
|
of the Anikeen Console.
|
||||||
|
- Add the reseller scopes `reseller-customers:read`, `reseller-customers`, `reseller-grants` and
|
||||||
|
`reseller-orders` (`Scope::RESELLER_CUSTOMERS_READ`, `Scope::RESELLER_CUSTOMERS`,
|
||||||
|
`Scope::RESELLER_GRANTS`, `Scope::RESELLER_ORDERS`) for the reseller API of the Anikeen Console.
|
||||||
|
- Document the scope schema and the new scopes in the README.
|
||||||
|
|
||||||
|
Older releases: see the [GitHub releases](https://github.com/anikeen-com/id/releases) and tags.
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
Guidance for Claude Code (and other contributors) working in this repository.
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
`anikeen/id` is the public PHP client for the Anikeen ID API, shipped as a Laravel package
|
||||||
|
(Laravel 11–13, PHP 8.2+). It covers OAuth/Socialite login, an API token guard, and the billing
|
||||||
|
API (subscriptions, orders, checkout sessions, shipments, invoices, webhooks). This is a public
|
||||||
|
repo published on Packagist: never commit secrets, internal hostnames or customer data.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```shell
|
||||||
|
composer install
|
||||||
|
composer test # vendor/bin/phpunit
|
||||||
|
vendor/bin/phpunit --filter AppSubscriptionsTest
|
||||||
|
composer docs # regenerate README.md from README.stub
|
||||||
|
```
|
||||||
|
|
||||||
|
CI (`.github/workflows/tests.yml`) runs PHPUnit on PHP 8.3 and 8.4.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `src/Id/AnikeenId.php` – the API client (singleton, facade `AnikeenId`). Reads
|
||||||
|
`config('services.anikeen.*')`; `mode=staging` switches to the staging base URL unless
|
||||||
|
`base_url` is set. `request()` wraps Guzzle and returns a `Result`.
|
||||||
|
- `src/Id/Billable.php` – trait for the app's user model; composes the `Concerns/Manages*` traits.
|
||||||
|
Its API caches are declared properties on purpose (undeclared ones would be treated as Eloquent
|
||||||
|
attributes and break `save()`). Add a new cache property there when a concern caches.
|
||||||
|
- `src/Id/Concerns/` – one trait per API area. Traits on `AnikeenId` act as the app/client;
|
||||||
|
traits on `Billable` act for one user.
|
||||||
|
- `src/Id/Resources/` – `BaseResource` (single object) and `BaseCollection` (lists, built via
|
||||||
|
`::builder()`). Failed requests throw `ApiException::fromResult()` (`CollectionException` for
|
||||||
|
lists), no response `::unreachable()`, `confirmation_required` a `ConfirmationRequiredException`.
|
||||||
|
All extend `ResourceException`.
|
||||||
|
- `src/Id/Resources/App*` – "app" variants that use the app's own client-credentials token
|
||||||
|
(`AnikeenId::asApp()`, `Support/AppRequest`) instead of the user's token, for trusted apps.
|
||||||
|
They must not send any request until a method is called.
|
||||||
|
- `src/Id/Auth/`, `Providers/AnikeenIdServiceProvider.php`, `Http/Middleware/` – the `anikeen`
|
||||||
|
guard driver and user provider, JWT validation (`Helpers/JwtParser.php` with the bundled
|
||||||
|
`oauth-public*.key`), scope middleware.
|
||||||
|
- `src/Id/Webhooks/` – signature verification (`Webhook::constructEvent`) and `EventType`
|
||||||
|
constants.
|
||||||
|
- `src/Support/Query.php` – query-string builder.
|
||||||
|
- `generator/generate-docs.php` – reflects the public methods of `AnikeenId` and `Billable` traits
|
||||||
|
into the README.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- **README:** edit `README.stub`, never `README.md` directly, then run `composer docs`. The
|
||||||
|
`<!-- GENERATED-DOCS -->` marker is replaced with the method reference. Commit both files.
|
||||||
|
- **New endpoints:** add a method to the matching `Concerns/Manages*` trait (or a resource class),
|
||||||
|
document request attributes with an `array{…}` PHPDoc shape and a short description per key,
|
||||||
|
and add an example to `README.stub` when it is a new feature.
|
||||||
|
- **Tests:** extend `Anikeen\Id\Tests\TestCase` (Orchestra Testbench). No live API: queue
|
||||||
|
responses with `$this->respond($status, $body)` (Guzzle `MockHandler`) and assert the sent
|
||||||
|
requests via `$this->sent` / `$this->sentJson($i)` – method, path, `Authorization` header and
|
||||||
|
JSON body. The app token is faked as `app-token`.
|
||||||
|
- **Compatibility:** this is a library used by several apps. Keep public method signatures
|
||||||
|
backwards compatible; add optional parameters instead of changing existing ones.
|
||||||
|
- Code, comments, docs and commit messages in English. Commit subjects are short, imperative,
|
||||||
|
sentence case (e.g. "Ship orders: shipments with delivery notes"). Work happens on feature
|
||||||
|
branches merged via PR into `main`.
|
||||||
+747
-145
File diff suppressed because it is too large.
Load diff
+5
-5
@@ -15,15 +15,15 @@
|
|||||||
"require": {
|
"require": {
|
||||||
"php": "^8.2",
|
"php": "^8.2",
|
||||||
"ext-json": "*",
|
"ext-json": "*",
|
||||||
"illuminate/support": "^11.0|^12.0|^13.0",
|
"illuminate/support": "^12.69|^13.0",
|
||||||
"illuminate/console": "^11.0|^12.0|^13.0",
|
"illuminate/console": "^12.69|^13.0",
|
||||||
"guzzlehttp/guzzle": "^7.8",
|
"guzzlehttp/guzzle": "^7.8",
|
||||||
"socialiteproviders/manager": "^4.6",
|
"socialiteproviders/manager": "^4.6",
|
||||||
"firebase/php-jwt": "^6.10|^7.0"
|
"firebase/php-jwt": "^7.0"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"laravel/framework": "^11.0|^12.0|^13.0",
|
"laravel/framework": "^12.69|^13.0",
|
||||||
"orchestra/testbench": "^9.0|^10.0|^11.0",
|
"orchestra/testbench": "^10.0|^11.0",
|
||||||
"phpunit/phpunit": "^11.0|^12.0"
|
"phpunit/phpunit": "^11.0|^12.0"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Anikeen\Id\Concerns;
|
||||||
|
|
||||||
|
use Anikeen\Id\Enums\SubscriptionStatus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The state of a subscription, derived from its fields the same way Anikeen ID derives `status`
|
||||||
|
* (so it also works with responses that only carry the fields).
|
||||||
|
*/
|
||||||
|
trait HasSubscriptionStatus
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* One of the SubscriptionStatus constants: draft, trial, active, paused, cancelling, expired
|
||||||
|
* or cancelled.
|
||||||
|
*/
|
||||||
|
public function status(): string
|
||||||
|
{
|
||||||
|
$active = (bool) $this->active;
|
||||||
|
$started = !empty($this->starts_at);
|
||||||
|
|
||||||
|
return match (true) {
|
||||||
|
(bool) $this->cancelled => SubscriptionStatus::CANCELLED,
|
||||||
|
!$active && !$started => SubscriptionStatus::DRAFT,
|
||||||
|
$active && !empty($this->cancels_at) => SubscriptionStatus::CANCELLING,
|
||||||
|
$active && !$this->autorenew => SubscriptionStatus::PAUSED,
|
||||||
|
$active && !empty($this->trial_ends_at) && strtotime($this->trial_ends_at) > time() => SubscriptionStatus::TRIAL,
|
||||||
|
$active => SubscriptionStatus::ACTIVE,
|
||||||
|
!$this->autorenew && $started => SubscriptionStatus::EXPIRED,
|
||||||
|
default => SubscriptionStatus::INACTIVE,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Not checked out or confirmed yet (third-party apps: send the user to confirmationUrl()).
|
||||||
|
*/
|
||||||
|
public function isDraft(): bool
|
||||||
|
{
|
||||||
|
return $this->status() === SubscriptionStatus::DRAFT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Running and paid: active, in trial, paused or with a scheduled cancellation. Grant access
|
||||||
|
* while this is true.
|
||||||
|
*/
|
||||||
|
public function isActive(): bool
|
||||||
|
{
|
||||||
|
return in_array($this->status(), [SubscriptionStatus::TRIAL, SubscriptionStatus::ACTIVE, SubscriptionStatus::PAUSED, SubscriptionStatus::CANCELLING], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In its free trial: running, nothing billed until trial_ends_at.
|
||||||
|
*/
|
||||||
|
public function isTrial(): bool
|
||||||
|
{
|
||||||
|
return $this->status() === SubscriptionStatus::TRIAL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paused: runs until the paid period ends, then expires (resume() to continue).
|
||||||
|
*/
|
||||||
|
public function isPaused(): bool
|
||||||
|
{
|
||||||
|
return $this->status() === SubscriptionStatus::PAUSED;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Running until a scheduled cancellation takes effect.
|
||||||
|
*/
|
||||||
|
public function isCancelling(): bool
|
||||||
|
{
|
||||||
|
return $this->status() === SubscriptionStatus::CANCELLING;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paused and ran out: resume() starts a new period.
|
||||||
|
*/
|
||||||
|
public function isExpired(): bool
|
||||||
|
{
|
||||||
|
return $this->status() === SubscriptionStatus::EXPIRED;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancelled for good.
|
||||||
|
*/
|
||||||
|
public function isCancelled(): bool
|
||||||
|
{
|
||||||
|
return $this->status() === SubscriptionStatus::CANCELLED;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace Anikeen\Id\Concerns;
|
namespace Anikeen\Id\Concerns;
|
||||||
|
|
||||||
|
use Anikeen\Id\AnikeenId;
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
use Anikeen\Id\Resources\AppCheckoutSessions;
|
use Anikeen\Id\Resources\AppCheckoutSessions;
|
||||||
use Anikeen\Id\Resources\AppOrders;
|
use Anikeen\Id\Resources\AppOrders;
|
||||||
use Anikeen\Id\Resources\AppSubscriptions;
|
use Anikeen\Id\Resources\AppSubscriptions;
|
||||||
@@ -65,4 +67,20 @@ trait ManagesSubscriptions
|
|||||||
{
|
{
|
||||||
return new AppOrders($this);
|
return new AppOrders($this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A link to the user's billing pages on Anikeen ID that needs no login, created with the app's
|
||||||
|
* own token (trusted apps only, scope subscriptions:client or orders:client), e.g. for a
|
||||||
|
* "Manage billing" button; see AnikeenId::createBillingPortalLinkForUser() for the attributes
|
||||||
|
* (return_url, group, flow). Single use and valid for about 15 minutes: create it when the
|
||||||
|
* user clicks and redirect right away.
|
||||||
|
*
|
||||||
|
* @param array{return_url?: null|string, group?: null|string, flow?: null|string} $attributes
|
||||||
|
*
|
||||||
|
* @throws ApiException
|
||||||
|
*/
|
||||||
|
public function appBillingPortalUrl(array $attributes = []): string
|
||||||
|
{
|
||||||
|
return app(AnikeenId::class)->createBillingPortalLinkForUser($this->appSubscriptions()->userId(), $attributes)->url;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
namespace Anikeen\Id\Concerns;
|
namespace Anikeen\Id\Concerns;
|
||||||
|
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
use Anikeen\Id\Resources\AppCheckoutSessions;
|
use Anikeen\Id\Resources\AppCheckoutSessions;
|
||||||
use Anikeen\Id\Resources\AppOrders;
|
use Anikeen\Id\Resources\AppOrders;
|
||||||
use Anikeen\Id\Result;
|
use Anikeen\Id\Result;
|
||||||
|
use Anikeen\Id\Support\AppRequest;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,11 +31,48 @@ trait ManagesUserBilling
|
|||||||
return new AppCheckoutSessions();
|
return new AppCheckoutSessions();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A link to a user's billing pages on Anikeen ID that needs no login, like Stripe's customer
|
||||||
|
* portal, e.g. for a "Manage billing" button of an app that bills another user's account (a
|
||||||
|
* team owner) without that user's token (trusted apps, scope subscriptions:client or
|
||||||
|
* orders:client). The link is single use and valid for about 15 minutes: create it when the
|
||||||
|
* user clicks and redirect right away, don't store it. It opens a portal session for that user
|
||||||
|
* only (no login, nobody signed in) with only the flow's billing pages and only what bills the
|
||||||
|
* app's subscriptions (of the group), leading back to return_url; it ends after an hour
|
||||||
|
* without activity.
|
||||||
|
*
|
||||||
|
* @param string $userId The user's Anikeen ID.
|
||||||
|
* @param array{
|
||||||
|
* return_url?: null|string,
|
||||||
|
* group?: null|string,
|
||||||
|
* flow?: null|string
|
||||||
|
* } $attributes return_url: "Back to the app" (same origin as one of the app's redirect URIs,
|
||||||
|
* 422 otherwise).
|
||||||
|
* group: only this group's subscriptions and the orders, invoices and
|
||||||
|
* transactions billing them.
|
||||||
|
* flow: overview (default), payment_method, payment_method_update (straight to
|
||||||
|
* replacing the payment method, e.g. after a failed payment), invoices,
|
||||||
|
* subscriptions or orders.
|
||||||
|
* @return object {object: "billing_portal_link", url, user_id, flow, group, return_url, expires_at}
|
||||||
|
*
|
||||||
|
* @throws ApiException 403 untrusted app or missing scope, 404 unknown user, 422 validation
|
||||||
|
*/
|
||||||
|
public function createBillingPortalLinkForUser(string $userId, array $attributes = []): object
|
||||||
|
{
|
||||||
|
return AppRequest::send('POST', sprintf('v1/client/users/%s/billing-portal', $userId), $attributes)->data;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create an order for a user (VAT from the billing address). With `checkout`, it is paid right
|
* Create an order for a user (VAT from the billing address). With `checkout`, it is paid right
|
||||||
* away: with the given `transaction` (a payment captured elsewhere) or by charging the user's
|
* away: with the given `transaction` (a payment captured elsewhere) or by charging the user's
|
||||||
* default payment method (402 when declined; the order stays pending and is retried).
|
* default payment method (402 when declined; the order stays pending and is retried).
|
||||||
*
|
*
|
||||||
|
* With `confirm`, the user confirms and pays it on Anikeen ID instead (e.g. a top-up): the
|
||||||
|
* order stays a draft with `confirmation_url` (send the user there) and is cancelled if not
|
||||||
|
* confirmed within 24 hours (`expires_at`; afterwards checking it out answers 409
|
||||||
|
* "confirmation_expired"). Webhooks: order.created, order.completed once paid, or
|
||||||
|
* order.cancelled when the user declines or it expires.
|
||||||
|
*
|
||||||
* @param string $userId The user's Anikeen ID.
|
* @param string $userId The user's Anikeen ID.
|
||||||
* @param array{
|
* @param array{
|
||||||
* group?: string,
|
* group?: string,
|
||||||
@@ -43,11 +82,18 @@ trait ManagesUserBilling
|
|||||||
* shipping_address?: array,
|
* shipping_address?: array,
|
||||||
* items: array<array{type: string, name: string, description?: string, image_url?: string, price?: float|string, gross_price?: float|string, unit: string, units: int}>,
|
* items: array<array{type: string, name: string, description?: string, image_url?: string, price?: float|string, gross_price?: float|string, unit: string, units: int}>,
|
||||||
* checkout?: bool,
|
* checkout?: bool,
|
||||||
|
* confirm?: bool,
|
||||||
|
* return_url?: null|string,
|
||||||
|
* metadata?: null|array,
|
||||||
* transaction_id?: string,
|
* transaction_id?: string,
|
||||||
* transaction?: array,
|
* transaction?: array,
|
||||||
* invoice_date?: string,
|
* invoice_date?: string,
|
||||||
* currency_iso?: string
|
* currency_iso?: string
|
||||||
* } $attributes
|
* } $attributes confirm: needs items, can't be combined with checkout or a transaction.
|
||||||
|
* return_url: where the user returns after confirming, with `status` and
|
||||||
|
* `order` (same origin as one of the app's redirect URIs, 422 otherwise).
|
||||||
|
* metadata: the app's own data (max. 50 keys), returned as is in the API and
|
||||||
|
* the order webhooks.
|
||||||
* @throws Throwable
|
* @throws Throwable
|
||||||
*/
|
*/
|
||||||
public function createOrderForUser(string $userId, array $attributes): Result
|
public function createOrderForUser(string $userId, array $attributes): Result
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ namespace Anikeen\Id\Concerns;
|
|||||||
|
|
||||||
use Anikeen\Id\ApiOperations\Get;
|
use Anikeen\Id\ApiOperations\Get;
|
||||||
use Anikeen\Id\ApiOperations\Post;
|
use Anikeen\Id\ApiOperations\Post;
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
use Anikeen\Id\Result;
|
use Anikeen\Id\Result;
|
||||||
|
use Anikeen\Id\Support\AppRequest;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
trait ManagesUsers
|
trait ManagesUsers
|
||||||
@@ -24,20 +26,32 @@ trait ManagesUsers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new user on behalf of the current user.
|
* Finds the account of an email address or creates it (trusted apps, app token). The email
|
||||||
|
* address is matched regardless of case; a new account stores it in lower case, unverified.
|
||||||
|
* An existing account is returned unchanged (only a missing name is filled in).
|
||||||
*
|
*
|
||||||
* @param array{
|
* @param array{
|
||||||
* first_name: null|string,
|
* name?: null|string,
|
||||||
* last_name: null|string,
|
* first_name?: null|string,
|
||||||
* username: null|string,
|
* last_name?: null|string,
|
||||||
|
* username?: null|string,
|
||||||
* email: string,
|
* email: string,
|
||||||
* password: null|string
|
* password?: null|string,
|
||||||
|
* password_confirmation?: null|string,
|
||||||
|
* send_invitation?: bool
|
||||||
* } $attributes The user data
|
* } $attributes The user data
|
||||||
* - first_name: The first name (optional)
|
* - name: The display name (optional)
|
||||||
* - last_name: The last name (optional)
|
* - first_name: The first name (optional, joined with last_name into name)
|
||||||
|
* - last_name: The last name (optional, joined with first_name into name)
|
||||||
* - username: The username (optional)
|
* - username: The username (optional)
|
||||||
* - email: The email (required)
|
* - email: The email (required)
|
||||||
* - password: The password (optional, can be reset by the user if not provided)
|
* - password: The password (optional, can be reset by the user if not provided)
|
||||||
|
* - password_confirmation: Defaults to password
|
||||||
|
* - send_invitation: Send the user an invitation mail with a link to set a password
|
||||||
|
* (optional, only when this call created the account without a
|
||||||
|
* password, never for an existing account)
|
||||||
|
* @return Result `data` is the user plus `created` (this call created the account) and
|
||||||
|
* `invitation_sent` (the invitation mail was sent); 201 when created, 200 when it existed
|
||||||
* @throws Throwable
|
* @throws Throwable
|
||||||
*/
|
*/
|
||||||
public function createUser(array $attributes): Result
|
public function createUser(array $attributes): Result
|
||||||
@@ -57,6 +71,30 @@ trait ManagesUsers
|
|||||||
return $this->asApp()->post('v1/admin/users', $attributes);
|
return $this->asApp()->post('v1/admin/users', $attributes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks up the account of an email address without creating or changing anything (trusted
|
||||||
|
* apps, app token). The email address is matched regardless of case.
|
||||||
|
*
|
||||||
|
* `data` is `object{id: string, name: ?string, email: string, email_verified: bool,
|
||||||
|
* has_billing_address: bool}`.
|
||||||
|
*
|
||||||
|
* @return Result|null null when no account uses the email address
|
||||||
|
* @throws ApiException when the request fails for another reason
|
||||||
|
*/
|
||||||
|
public function findUserByEmail(string $email): ?Result
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return AppRequest::send('POST', 'v1/admin/users/lookup', ['email' => $email]);
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
// only Anikeen ID's own answer means "no account", not e.g. an unknown route
|
||||||
|
if ($e->isNotFound() && $e->error === 'user_not_found') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Find the user of a social login or create it (trusted apps, app token).
|
* Find the user of a social login or create it (trusted apps, app token).
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Anikeen\Id\Enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `cancellation_reason` of a subscription (and `data.reason` of `subscription.cancelled`): why
|
||||||
|
* Anikeen ID's billing ended it. Null when the user, the app or an admin cancelled it.
|
||||||
|
*/
|
||||||
|
class CancellationReason
|
||||||
|
{
|
||||||
|
/** Its free trial (`trial_payment_method` optional) ended without a payment method: cancelled at the trial's end, nothing billed. */
|
||||||
|
const TRIAL_ENDED_WITHOUT_PAYMENT_METHOD = 'trial_ended_without_payment_method';
|
||||||
|
}
|
||||||
@@ -36,5 +36,16 @@ class Scope
|
|||||||
const SSH_KEYS = 'ssh-keys';
|
const SSH_KEYS = 'ssh-keys';
|
||||||
const SSH_KEYS_READ = 'ssh-keys:read';
|
const SSH_KEYS_READ = 'ssh-keys:read';
|
||||||
|
|
||||||
|
// Products of the Anikeen Console (servers, floating IPs, hosting, domains, zones, object storage),
|
||||||
|
// read-only. Changing products needs `user`; there is no full `products` scope.
|
||||||
|
const PRODUCTS_READ = 'products:read';
|
||||||
|
|
||||||
|
// Reseller API of the Anikeen Console. A full scope includes reading; `user` and `*` do not
|
||||||
|
// open these endpoints, a token must carry the reseller scope itself.
|
||||||
|
const RESELLER_CUSTOMERS = 'reseller-customers';
|
||||||
|
const RESELLER_CUSTOMERS_READ = 'reseller-customers:read';
|
||||||
|
const RESELLER_GRANTS = 'reseller-grants';
|
||||||
|
const RESELLER_ORDERS = 'reseller-orders';
|
||||||
|
|
||||||
const ADMIN = 'admin';
|
const ADMIN = 'admin';
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Anikeen\Id\Enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The state of a subscription, see Subscription::status() and AppSubscription::status().
|
||||||
|
*/
|
||||||
|
class SubscriptionStatus
|
||||||
|
{
|
||||||
|
/** Created, not checked out or confirmed by the user yet. */
|
||||||
|
const DRAFT = 'draft';
|
||||||
|
|
||||||
|
/** Running and billed, in its trial period. */
|
||||||
|
const TRIAL = 'trial';
|
||||||
|
|
||||||
|
/** Running and billed. */
|
||||||
|
const ACTIVE = 'active';
|
||||||
|
|
||||||
|
/** Paused: runs until its paid period ends, then expires. */
|
||||||
|
const PAUSED = 'paused';
|
||||||
|
|
||||||
|
/** Running until a scheduled cancellation takes effect. */
|
||||||
|
const CANCELLING = 'cancelling';
|
||||||
|
|
||||||
|
/** Paused and ran out: can be resumed (new period) or cancelled. */
|
||||||
|
const EXPIRED = 'expired';
|
||||||
|
|
||||||
|
/** Cancelled for good. */
|
||||||
|
const CANCELLED = 'cancelled';
|
||||||
|
|
||||||
|
/** None of the above. */
|
||||||
|
const INACTIVE = 'inactive';
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Anikeen\Id\Enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `trial_payment_method` of a subscription with a free trial: whether the user needs a payment
|
||||||
|
* method to confirm it. Null on subscriptions without a trial.
|
||||||
|
*/
|
||||||
|
class TrialPaymentMethod
|
||||||
|
{
|
||||||
|
/** A payment method is needed to confirm the trial (the default). */
|
||||||
|
const REQUIRED = 'required';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The trial can be confirmed without a payment method (if nothing else has to be paid). If the
|
||||||
|
* user still has none when the trial ends, the subscription is cancelled then instead of billed
|
||||||
|
* (`cancellation_reason` CancellationReason::TRIAL_ENDED_WITHOUT_PAYMENT_METHOD).
|
||||||
|
*/
|
||||||
|
const OPTIONAL = 'optional';
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace Anikeen\Id\Exceptions;
|
namespace Anikeen\Id\Exceptions;
|
||||||
|
|
||||||
|
use Anikeen\Id\Result;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,6 +21,48 @@ class ApiException extends ResourceException
|
|||||||
parent::__construct($message, $status, $previous);
|
parent::__construct($message, $status, $previous);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The exception for a failed request: Anikeen ID's message and error code, the HTTP status
|
||||||
|
* (0 when there was no response).
|
||||||
|
*/
|
||||||
|
public static function fromResult(Result $result): static
|
||||||
|
{
|
||||||
|
$body = is_object($result->data) ? $result->data : null;
|
||||||
|
|
||||||
|
return new static(
|
||||||
|
rtrim((string) ($body->message ?? $result->error()), '.'),
|
||||||
|
$result->response()?->getStatusCode() ?? 0,
|
||||||
|
$body->error ?? null,
|
||||||
|
$result->exception,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The exception for a request that got no response (network error, timeout).
|
||||||
|
*/
|
||||||
|
public static function unreachable(Throwable $previous): static
|
||||||
|
{
|
||||||
|
return new static(sprintf('Anikeen ID is not reachable: %s', $previous->getMessage()), 0, null, $previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The JSON body of Anikeen ID's error response, null without one. Some errors carry details,
|
||||||
|
* e.g. `net_amount` of "elapsed_amount_exceeded".
|
||||||
|
*/
|
||||||
|
public function body(): ?object
|
||||||
|
{
|
||||||
|
$previous = $this->getPrevious();
|
||||||
|
$response = $previous !== null && method_exists($previous, 'getResponse') ? $previous->getResponse() : null;
|
||||||
|
|
||||||
|
if (!$response instanceof ResponseInterface) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$body = json_decode((string) $response->getBody());
|
||||||
|
|
||||||
|
return is_object($body) ? $body : null;
|
||||||
|
}
|
||||||
|
|
||||||
public function isNotFound(): bool
|
public function isNotFound(): bool
|
||||||
{
|
{
|
||||||
return $this->status === 404;
|
return $this->status === 404;
|
||||||
|
|||||||
@@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
namespace Anikeen\Id\Exceptions;
|
namespace Anikeen\Id\Exceptions;
|
||||||
|
|
||||||
use Anikeen\Id\Result;
|
/**
|
||||||
use Exception;
|
* A list request failed. Like ApiException it carries the HTTP status (also as getCode()) and
|
||||||
|
* Anikeen ID's error code.
|
||||||
class CollectionException extends Exception
|
*/
|
||||||
|
class CollectionException extends ApiException
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -36,7 +36,12 @@ class AppCheckoutSessions
|
|||||||
* predecessor_id?: null|string,
|
* predecessor_id?: null|string,
|
||||||
* vat_rate?: float,
|
* vat_rate?: float,
|
||||||
* payload?: null|array,
|
* payload?: null|array,
|
||||||
* ends_at?: null|string
|
* ends_at?: null|string,
|
||||||
|
* trial_days?: null|int,
|
||||||
|
* trial_ends_at?: null|string,
|
||||||
|
* trial_once?: bool,
|
||||||
|
* trial_payment_method?: null|string,
|
||||||
|
* discount?: null|array{label: string, percent_off?: float|string, amount_off?: float|string, duration: string, duration_in_periods?: int}
|
||||||
* }>,
|
* }>,
|
||||||
* return_url?: null|string,
|
* return_url?: null|string,
|
||||||
* metadata?: null|array,
|
* metadata?: null|array,
|
||||||
@@ -45,6 +50,11 @@ class AppCheckoutSessions
|
|||||||
* } $attributes return_url must share scheme, host and port with one of the app's redirect
|
* } $attributes return_url must share scheme, host and port with one of the app's redirect
|
||||||
* URIs; the user comes back to it with `status` and `checkout_session`. A
|
* URIs; the user comes back to it with `status` and `checkout_session`. A
|
||||||
* repeated idempotency_key returns the first session instead of a new one.
|
* repeated idempotency_key returns the first session instead of a new one.
|
||||||
|
* trial_days / trial_ends_at give a subscription a free trial from the user's
|
||||||
|
* confirmation on; trial_once is allowed on one subscription per group.
|
||||||
|
* trial_payment_method `optional`: the session can be confirmed without a
|
||||||
|
* payment method only if all of its subscriptions are such trials.
|
||||||
|
* discount: see AppSubscriptions::create(); the confirmation page shows it.
|
||||||
*
|
*
|
||||||
* @throws ApiException 422 validation (e.g. return_url), 409 "idempotency_key_conflict"
|
* @throws ApiException 422 validation (e.g. return_url), 409 "idempotency_key_conflict"
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -13,9 +13,22 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
* scope orders:client) - of one user ($user->appOrders()) or of all users
|
* scope orders:client) - of one user ($user->appOrders()) or of all users
|
||||||
* (app(AnikeenId::class)->appOrders()). Nothing is requested until a method is called.
|
* (app(AnikeenId::class)->appOrders()). Nothing is requested until a method is called.
|
||||||
*
|
*
|
||||||
* Each order is an object with id, user_id, group, status (processing|pending|completed|cancelled),
|
* Each order is an object with id, user_id, oauth_client_id (the app that bills it: collective
|
||||||
* is_collective, net_total, vat_total, gross_total, currency_iso, created_at, paid_at,
|
* orders are kept per app, even for the same group; null on legacy orders that billed several
|
||||||
* payment_attempts, next_payment_attempt_at and last_payment_error ({code, message} or null).
|
* apps), group, metadata, status (processing|pending|completed|cancelled), is_collective,
|
||||||
|
* net_total, vat_total, gross_total, currency_iso, created_at, paid_at, payment_attempts,
|
||||||
|
* next_payment_attempt_at, last_payment_error ({code, message} or null), and
|
||||||
|
*
|
||||||
|
* - items: the order's lines of the app's subscriptions (all lines, except on legacy orders that
|
||||||
|
* also billed other apps), each {id, name, description, type, image_url, units, unit,
|
||||||
|
* price, vat_rate, subscription_id, meter, monthly_cap, discount, period_start, period_end,
|
||||||
|
* net_amount, vat_amount, gross_amount}. period_end is exclusive (the start of the next
|
||||||
|
* period); both are null for lines without a period. discount ({label, percent_off,
|
||||||
|
* amount_off}) marks the negative line of a subscription's discount, else null. The net amount
|
||||||
|
* a subscription was billed is the sum of net_amount of its lines.
|
||||||
|
* - invoice: null until the order is paid, then {id, number, type, status (pending while the PDF
|
||||||
|
* is being rendered, then completed), service_period_from, service_period_to, created_at,
|
||||||
|
* pdf_url}; see invoicePdf().
|
||||||
*/
|
*/
|
||||||
class AppOrders
|
class AppOrders
|
||||||
{
|
{
|
||||||
@@ -81,6 +94,22 @@ class AppOrders
|
|||||||
return !$this->billable || $order->user_id === $this->userId() ? $order : null;
|
return !$this->billable || $order->user_id === $this->userId() ? $order : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The PDF of an order's invoice (binary string, with the embedded e-invoice), the same as its
|
||||||
|
* `invoice.pdf_url` with the app's token.
|
||||||
|
*
|
||||||
|
* @throws ApiException 404 "order_not_found", 404 "invoice_not_found" (not paid yet),
|
||||||
|
* 409 "invoice_not_ready" (still being rendered, try again later)
|
||||||
|
*/
|
||||||
|
public function invoicePdf(string $orderId): string
|
||||||
|
{
|
||||||
|
if ($this->billable && !$this->find($orderId)) {
|
||||||
|
throw new ApiException('Order not found.', 404, 'order_not_found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return (string) AppRequest::send('GET', sprintf('v1/client/orders/%s/invoice', $orderId))->response()?->getBody();
|
||||||
|
}
|
||||||
|
|
||||||
private function userId(): string
|
private function userId(): string
|
||||||
{
|
{
|
||||||
return (new AppSubscriptions($this->billable))->userId();
|
return (new AppSubscriptions($this->billable))->userId();
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
namespace Anikeen\Id\Resources;
|
namespace Anikeen\Id\Resources;
|
||||||
|
|
||||||
|
use Anikeen\Id\Concerns\HasSubscriptionStatus;
|
||||||
use Anikeen\Id\Exceptions\ApiException;
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
use Anikeen\Id\Support\AppRequest;
|
use Anikeen\Id\Support\AppRequest;
|
||||||
use DateTimeInterface;
|
use DateTimeInterface;
|
||||||
|
use InvalidArgumentException;
|
||||||
use JsonSerializable;
|
use JsonSerializable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,7 +26,12 @@ use JsonSerializable;
|
|||||||
* @property bool $active
|
* @property bool $active
|
||||||
* @property bool $autorenew
|
* @property bool $autorenew
|
||||||
* @property bool $cancelled
|
* @property bool $cancelled
|
||||||
* @property ?string $status "active" or "inactive"
|
* @property ?string $status draft, trial, active, paused, cancelling, expired or cancelled, see status()
|
||||||
|
* @property ?string $cancels_at when a scheduled cancellation takes effect
|
||||||
|
* @property ?string $trial_ends_at
|
||||||
|
* @property ?string $trial_payment_method required or optional with a trial (TrialPaymentMethod), null without
|
||||||
|
* @property ?string $cancellation_reason why the billing cancelled it (CancellationReason), null otherwise
|
||||||
|
* @property ?object $discount {label, percent_off, amount_off, duration, duration_in_periods, periods_remaining}; periods_remaining is null for `forever`, 0 once it ended
|
||||||
* @property ?string $starts_at
|
* @property ?string $starts_at
|
||||||
* @property ?string $ends_at
|
* @property ?string $ends_at
|
||||||
* @property ?string $accounting_at
|
* @property ?string $accounting_at
|
||||||
@@ -33,9 +40,18 @@ use JsonSerializable;
|
|||||||
* @property ?array $payload
|
* @property ?array $payload
|
||||||
* @property ?string $idempotency_key
|
* @property ?string $idempotency_key
|
||||||
* @property ?string $checkout_session_id the checkout session the user confirms it in, if any
|
* @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
|
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)
|
public function __construct(protected object $data)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -54,6 +70,7 @@ class AppSubscription implements JsonSerializable
|
|||||||
* Change a subscription (send only what changes). Before checkout everything can change;
|
* 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
|
* 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'])`.
|
* on their bills, e.g. `$subscription->update(['description' => 'web-01.example.com'])`.
|
||||||
|
* Prices of running subscriptions change with change().
|
||||||
*
|
*
|
||||||
* @throws ApiException
|
* @throws ApiException
|
||||||
*/
|
*/
|
||||||
@@ -62,23 +79,99 @@ class AppSubscription implements JsonSerializable
|
|||||||
return $this->send('PUT', '', $attributes);
|
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.
|
* Activate the subscription and bill its first period.
|
||||||
*
|
*
|
||||||
* $startsAt (in the past) books a service that is already running, e.g. a domain registered
|
* $startsAt (in the past) books a service that is already running, e.g. a domain registered
|
||||||
* earlier: the first period runs from $startsAt, is billed now and renews when it ends.
|
* earlier: the first period runs from $startsAt, is billed now and renews when it ends.
|
||||||
*
|
*
|
||||||
* @throws ApiException 409 "already_active", "billing_address_missing", "period_already_ended", …
|
* A $startsAt older than one period is refused ("period_already_ended") unless
|
||||||
|
* $billElapsedPeriods is set: then the periods that have already ended are billed too, together
|
||||||
|
* with the running one, as long as they come to at most $maxNetAmount (net, up to two
|
||||||
|
* decimals) and $startsAt lies within the maximum age Anikeen ID accepts (about three years).
|
||||||
|
* The lines land on the current month's collective order, which is charged on the 1st of the
|
||||||
|
* next month. $billElapsedPeriods needs both $startsAt and $maxNetAmount.
|
||||||
|
*
|
||||||
|
* @throws ApiException 409 "already_active", "billing_address_missing", "period_already_ended",
|
||||||
|
* "elapsed_periods_not_allowed" (the elapsed periods can't be billed for this subscription),
|
||||||
|
* "elapsed_amount_exceeded" (they come to more than $maxNetAmount; the response body has
|
||||||
|
* the booked `net_amount`), …; 422 invalid input (e.g. a start older than the maximum age)
|
||||||
|
* @throws InvalidArgumentException $billElapsedPeriods without $startsAt or $maxNetAmount
|
||||||
*/
|
*/
|
||||||
public function checkout(DateTimeInterface|string|null $startsAt = null): self
|
public function checkout(
|
||||||
{
|
DateTimeInterface|string|null $startsAt = null,
|
||||||
|
bool $billElapsedPeriods = false,
|
||||||
|
float|string|null $maxNetAmount = null,
|
||||||
|
): self {
|
||||||
if ($startsAt instanceof DateTimeInterface) {
|
if ($startsAt instanceof DateTimeInterface) {
|
||||||
$startsAt = $startsAt->format(DateTimeInterface::ATOM);
|
$startsAt = $startsAt->format(DateTimeInterface::ATOM);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!$billElapsedPeriods) {
|
||||||
return $this->send('PUT', '/checkout', $startsAt === null ? null : ['starts_at' => $startsAt]);
|
return $this->send('PUT', '/checkout', $startsAt === null ? null : ['starts_at' => $startsAt]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($startsAt === null || $startsAt === '') {
|
||||||
|
throw new InvalidArgumentException('Billing elapsed periods needs a start date ($startsAt).');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($maxNetAmount === null || $maxNetAmount === '') {
|
||||||
|
throw new InvalidArgumentException('Billing elapsed periods needs a maximum net amount ($maxNetAmount).');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->send('PUT', '/checkout', [
|
||||||
|
'starts_at' => $startsAt,
|
||||||
|
'bill_elapsed_periods' => true,
|
||||||
|
// floats from calculations may carry binary noise (e.g. 59.970000000000006)
|
||||||
|
'max_net_amount' => is_float($maxNetAmount) ? round($maxNetAmount, 2) : $maxNetAmount,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cancel the subscription. With $refund (only within 14 days of its start), its not yet
|
* Cancel the subscription. With $refund (only within 14 days of its start), its not yet
|
||||||
* charged usage is credited.
|
* charged usage is credited.
|
||||||
|
|||||||
@@ -49,6 +49,11 @@ class AppSubscriptions
|
|||||||
* vat_rate?: float,
|
* vat_rate?: float,
|
||||||
* payload?: null|array,
|
* payload?: null|array,
|
||||||
* ends_at?: null|string,
|
* ends_at?: null|string,
|
||||||
|
* trial_days?: null|int,
|
||||||
|
* trial_ends_at?: null|string,
|
||||||
|
* trial_once?: bool,
|
||||||
|
* trial_payment_method?: null|string,
|
||||||
|
* discount?: null|array{label: string, percent_off?: float|string, amount_off?: float|string, duration: string, duration_in_periods?: int},
|
||||||
* idempotency_key?: null|string
|
* idempotency_key?: null|string
|
||||||
* } $attributes With an idempotency_key (max. 191 characters), a retried call returns the
|
* } $attributes With an idempotency_key (max. 191 characters), a retried call returns the
|
||||||
* subscription created by the first one instead of a duplicate.
|
* subscription created by the first one instead of a duplicate.
|
||||||
@@ -56,8 +61,21 @@ class AppSubscriptions
|
|||||||
* at most 2 decimals, not below price; null = no cap).
|
* at most 2 decimals, not below price; null = no cap).
|
||||||
* predecessor_id: the subscription this one replaces (a resize; same user and
|
* predecessor_id: the subscription this one replaces (a resize; same user and
|
||||||
* app, checked out, not cancelled): both share the monthly cap within a month.
|
* app, checked out, not cancelled): both share the monthly cap within a month.
|
||||||
|
* trial_days: a free trial of 1–365 days from the checkout on (status `trial`,
|
||||||
|
* nothing billed; the first period is billed when it ends), or
|
||||||
|
* trial_ends_at: a fixed end of the trial (ISO 8601, in the future), not both.
|
||||||
|
* trial_once: refuse the trial if the user already had one with the app in the
|
||||||
|
* same group (422 here, 409 "trial_already_used" on checkout).
|
||||||
|
* trial_payment_method: TrialPaymentMethod::REQUIRED (default) or ::OPTIONAL,
|
||||||
|
* only with a trial: with `optional` the user may confirm it without a payment
|
||||||
|
* method, and without one at the trial's end it is cancelled instead of billed.
|
||||||
|
* discount: e.g. a coupon, as a negative line next to each billed period:
|
||||||
|
* label (shown to the user, max. 100 characters), percent_off (0.01–100) or
|
||||||
|
* amount_off (net per period, at most the price), duration `once` (the first
|
||||||
|
* billed period), `repeating` (duration_in_periods billed periods) or
|
||||||
|
* `forever`. Not combinable with a monthly_cap.
|
||||||
*
|
*
|
||||||
* @throws ApiException
|
* @throws ApiException 422 validation, 409 "idempotency_key_conflict", …
|
||||||
*/
|
*/
|
||||||
public function create(array $attributes): AppSubscription
|
public function create(array $attributes): AppSubscription
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use Anikeen\Id\Exceptions\CollectionException;
|
|||||||
use Anikeen\Id\Helpers\Paginator;
|
use Anikeen\Id\Helpers\Paginator;
|
||||||
use Anikeen\Id\Result;
|
use Anikeen\Id\Result;
|
||||||
use Closure;
|
use Closure;
|
||||||
|
use GuzzleHttp\Exception\GuzzleException;
|
||||||
use GuzzleHttp\Psr7\Response;
|
use GuzzleHttp\Psr7\Response;
|
||||||
use JsonSerializable;
|
use JsonSerializable;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
@@ -34,10 +35,15 @@ abstract class BaseCollection implements JsonSerializable
|
|||||||
*/
|
*/
|
||||||
protected function __construct(callable $callable)
|
protected function __construct(callable $callable)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$this->result = $callable();
|
$this->result = $callable();
|
||||||
|
} catch (GuzzleException $e) {
|
||||||
|
// no response at all (connection refused, timeout)
|
||||||
|
throw CollectionException::unreachable($e);
|
||||||
|
}
|
||||||
|
|
||||||
if (!$this->result->success()) {
|
if (!$this->result->success()) {
|
||||||
throw new CollectionException(sprintf('%s for collection [%s]', rtrim($this->result->data->message, '.'), get_called_class()), $this->result->response->getStatusCode());
|
throw CollectionException::fromResult($this->result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,10 @@
|
|||||||
|
|
||||||
namespace Anikeen\Id\Resources;
|
namespace Anikeen\Id\Resources;
|
||||||
|
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
|
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
|
||||||
use Anikeen\Id\Exceptions\ResourceException;
|
|
||||||
use Anikeen\Id\Result;
|
use Anikeen\Id\Result;
|
||||||
|
use GuzzleHttp\Exception\GuzzleException;
|
||||||
use JsonSerializable;
|
use JsonSerializable;
|
||||||
|
|
||||||
#[\AllowDynamicProperties]
|
#[\AllowDynamicProperties]
|
||||||
@@ -13,11 +14,17 @@ abstract class BaseResource implements JsonSerializable
|
|||||||
public Result $result;
|
public Result $result;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @throws ResourceException
|
* @throws ApiException the request failed (status, error code; a ResourceException)
|
||||||
|
* @throws ConfirmationRequiredException the user has to confirm it on Anikeen ID
|
||||||
*/
|
*/
|
||||||
public function __construct(callable $callable)
|
public function __construct(callable $callable)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$this->result = $callable();
|
$this->result = $callable();
|
||||||
|
} catch (GuzzleException $e) {
|
||||||
|
// no response at all (connection refused, timeout)
|
||||||
|
throw ApiException::unreachable($e);
|
||||||
|
}
|
||||||
|
|
||||||
if (!$this->result->success()) {
|
if (!$this->result->success()) {
|
||||||
if (($this->result->data->error ?? null) === 'confirmation_required') {
|
if (($this->result->data->error ?? null) === 'confirmation_required') {
|
||||||
@@ -28,7 +35,7 @@ abstract class BaseResource implements JsonSerializable
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new ResourceException(sprintf('%s for resource [%s]', rtrim($this->result->data->message, '.'), get_called_class()), $this->result->response->getStatusCode());
|
throw ApiException::fromResult($this->result);
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($this->result->data as $key => $value) {
|
foreach ($this->result->data as $key => $value) {
|
||||||
|
|||||||
@@ -8,7 +8,14 @@ use Throwable;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @property string $id
|
* @property string $id
|
||||||
* @property null|string $confirmation_url where the user confirms it (third-party apps)
|
* @property null|string $confirmation_url where the user confirms it (third-party apps, or `confirm`)
|
||||||
|
* @property null|string $oauth_client_id the app that bills the order: the app that created it, or for a monthly
|
||||||
|
* (collective) order the app whose subscriptions it bills; collective orders
|
||||||
|
* are kept per app. null for Anikeen's own (and legacy orders of several apps)
|
||||||
|
* @property null|string $group
|
||||||
|
* @property null|object $metadata the app's own data, returned as is
|
||||||
|
* @property null|string $return_url where the user returns after confirming
|
||||||
|
* @property null|string $expires_at when a draft created with `confirm` is cancelled unless confirmed
|
||||||
*/
|
*/
|
||||||
class Order extends BaseResource
|
class Order extends BaseResource
|
||||||
{
|
{
|
||||||
@@ -53,10 +60,14 @@ class Order extends BaseResource
|
|||||||
* country_iso: string,
|
* country_iso: string,
|
||||||
* phone_number: null|string,
|
* phone_number: null|string,
|
||||||
* email: null|string
|
* email: null|string
|
||||||
* }
|
* },
|
||||||
|
* group?: null|string,
|
||||||
|
* metadata?: null|array
|
||||||
* } $attributes The order data:
|
* } $attributes The order data:
|
||||||
* - billing_address: Billing address (ISO 3166-1 alpha-2 country code)
|
* - billing_address: Billing address (ISO 3166-1 alpha-2 country code)
|
||||||
* - shipping_address: Shipping address for physical items (first name, last name, address, postal code, city, ISO 3166-1 alpha-2 country code)
|
* - shipping_address: Shipping address for physical items (first name, last name, address, postal code, city, ISO 3166-1 alpha-2 country code)
|
||||||
|
* - group: The app's group (optional)
|
||||||
|
* - metadata: The app's own data (max. 50 keys), only while the order is a draft (optional)
|
||||||
* @throws Throwable
|
* @throws Throwable
|
||||||
*/
|
*/
|
||||||
public function update(array $attributes = []): self
|
public function update(array $attributes = []): self
|
||||||
@@ -69,6 +80,8 @@ class Order extends BaseResource
|
|||||||
/**
|
/**
|
||||||
* Checkout given order from the current user.
|
* Checkout given order from the current user.
|
||||||
*
|
*
|
||||||
|
* A draft created with `confirm` can't be checked out once it expired (409 "confirmation_expired").
|
||||||
|
*
|
||||||
* @throws Throwable
|
* @throws Throwable
|
||||||
*/
|
*/
|
||||||
public function checkout(): self
|
public function checkout(): self
|
||||||
|
|||||||
@@ -48,6 +48,10 @@ class Orders extends BaseCollection
|
|||||||
* phone_number: null|string,
|
* phone_number: null|string,
|
||||||
* email: null|string
|
* email: null|string
|
||||||
* },
|
* },
|
||||||
|
* group?: null|string,
|
||||||
|
* confirm?: bool,
|
||||||
|
* return_url?: null|string,
|
||||||
|
* metadata?: null|array,
|
||||||
* items: array<array{
|
* items: array<array{
|
||||||
* type: string,
|
* type: string,
|
||||||
* name: string,
|
* name: string,
|
||||||
@@ -61,6 +65,10 @@ class Orders extends BaseCollection
|
|||||||
* } $attributes The order data:
|
* } $attributes The order data:
|
||||||
* - billing_address: Billing address (ISO 3166-1 alpha-2 country code)
|
* - billing_address: Billing address (ISO 3166-1 alpha-2 country code)
|
||||||
* - shipping_address: Shipping address for physical items (first name, last name, address, postal code, city, ISO 3166-1 alpha-2 country code)
|
* - shipping_address: Shipping address for physical items (first name, last name, address, postal code, city, ISO 3166-1 alpha-2 country code)
|
||||||
|
* - group: The app's group, e.g. a team (optional)
|
||||||
|
* - confirm: Trusted apps: leave confirming and paying to the user (confirmation_url, expires after 24 hours; optional)
|
||||||
|
* - return_url: Where the user returns after confirming (same origin as one of the app's redirect URIs; optional)
|
||||||
|
* - metadata: The app's own data (max. 50 keys), returned as is in the API and webhooks (optional)
|
||||||
* - items: Array of order items:
|
* - items: Array of order items:
|
||||||
* - type: digital, physical or physical-reduced (VAT category)
|
* - type: digital, physical or physical-reduced (VAT category)
|
||||||
* - price/gross_price: net or gross unit price, one of both
|
* - price/gross_price: net or gross unit price, one of both
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace Anikeen\Id\Resources;
|
|||||||
|
|
||||||
use Anikeen\Id\Concerns\HasBillable;
|
use Anikeen\Id\Concerns\HasBillable;
|
||||||
use Anikeen\Id\Concerns\HasConfirmationUrl;
|
use Anikeen\Id\Concerns\HasConfirmationUrl;
|
||||||
|
use Anikeen\Id\Concerns\HasSubscriptionStatus;
|
||||||
use Anikeen\Id\Contracts\AppTokenRepository;
|
use Anikeen\Id\Contracts\AppTokenRepository;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
@@ -18,13 +19,24 @@ use Throwable;
|
|||||||
* @property ?string $predecessor_id the subscription this one replaced (a resize); they share the monthly cap
|
* @property ?string $predecessor_id the subscription this one replaced (a resize); they share the monthly cap
|
||||||
* @property float $vat_rate
|
* @property float $vat_rate
|
||||||
* @property array $payload
|
* @property array $payload
|
||||||
|
* @property bool $active
|
||||||
|
* @property bool $autorenew
|
||||||
|
* @property bool $cancelled
|
||||||
|
* @property ?string $status draft, trial, active, paused, cancelling, expired or cancelled, see status()
|
||||||
|
* @property ?string $starts_at
|
||||||
* @property string $ends_at
|
* @property string $ends_at
|
||||||
|
* @property ?string $cancels_at when a scheduled cancellation takes effect
|
||||||
|
* @property ?string $trial_ends_at
|
||||||
|
* @property ?string $trial_payment_method required or optional with a trial (TrialPaymentMethod), null without
|
||||||
|
* @property ?string $cancellation_reason why the billing cancelled it (CancellationReason), null otherwise
|
||||||
|
* @property ?object $discount {label, percent_off, amount_off, duration, duration_in_periods, periods_remaining}; periods_remaining is null for `forever`, 0 once it ended
|
||||||
* @property null|string $confirmation_url where the user confirms it (third-party apps)
|
* @property null|string $confirmation_url where the user confirms it (third-party apps)
|
||||||
*/
|
*/
|
||||||
class Subscription extends BaseResource
|
class Subscription extends BaseResource
|
||||||
{
|
{
|
||||||
use HasBillable;
|
use HasBillable;
|
||||||
use HasConfirmationUrl;
|
use HasConfirmationUrl;
|
||||||
|
use HasSubscriptionStatus;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update a given subscription from the current user.
|
* Update a given subscription from the current user.
|
||||||
|
|||||||
@@ -24,7 +24,12 @@ class Subscriptions extends BaseCollection
|
|||||||
* predecessor_id?: null|string,
|
* predecessor_id?: null|string,
|
||||||
* vat_rate: float,
|
* vat_rate: float,
|
||||||
* payload: null|array,
|
* payload: null|array,
|
||||||
* ends_at: null|string
|
* ends_at: null|string,
|
||||||
|
* trial_days?: null|int,
|
||||||
|
* trial_ends_at?: null|string,
|
||||||
|
* trial_once?: bool,
|
||||||
|
* trial_payment_method?: null|string,
|
||||||
|
* discount?: null|array{label: string, percent_off?: float|string, amount_off?: float|string, duration: string, duration_in_periods?: int}
|
||||||
* } $attributes The subscription data:
|
* } $attributes The subscription data:
|
||||||
* - group: The group (optional)
|
* - group: The group (optional)
|
||||||
* - name: The name
|
* - name: The name
|
||||||
@@ -36,6 +41,11 @@ class Subscriptions extends BaseCollection
|
|||||||
* - vat_rate: The VAT rate (required when set)
|
* - vat_rate: The VAT rate (required when set)
|
||||||
* - payload: The payload (optional)
|
* - payload: The payload (optional)
|
||||||
* - ends_at: The end date (optional)
|
* - ends_at: The end date (optional)
|
||||||
|
* - trial_days: A free trial of 1–365 days from the user's confirmation on (optional)
|
||||||
|
* - trial_ends_at: Or a fixed end of the free trial (ISO 8601, in the future; optional)
|
||||||
|
* - trial_once: Refuse the trial if the user already had one with the app in the group (optional)
|
||||||
|
* - trial_payment_method: TrialPaymentMethod::REQUIRED (default) or ::OPTIONAL, only with a trial (optional)
|
||||||
|
* - discount: A discount per billed period, see AppSubscriptions::create() (optional)
|
||||||
* @throws Throwable
|
* @throws Throwable
|
||||||
*/
|
*/
|
||||||
public function create(array $attributes): Subscription
|
public function create(array $attributes): Subscription
|
||||||
|
|||||||
@@ -18,9 +18,34 @@ final class EventType
|
|||||||
public const SUBSCRIPTION_ACTIVATED = 'subscription.activated';
|
public const SUBSCRIPTION_ACTIVATED = 'subscription.activated';
|
||||||
public const SUBSCRIPTION_PAUSED = 'subscription.paused';
|
public const SUBSCRIPTION_PAUSED = 'subscription.paused';
|
||||||
public const SUBSCRIPTION_RESUMED = 'subscription.resumed';
|
public const SUBSCRIPTION_RESUMED = 'subscription.resumed';
|
||||||
|
/** `data.reason`: why the billing cancelled it (CancellationReason, e.g. a trial that ended without a payment method), else null. */
|
||||||
public const SUBSCRIPTION_CANCELLED = 'subscription.cancelled';
|
public const SUBSCRIPTION_CANCELLED = 'subscription.cancelled';
|
||||||
public const SUBSCRIPTION_EXPIRED = 'subscription.expired';
|
public const SUBSCRIPTION_EXPIRED = 'subscription.expired';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The free trial of a running subscription ends in a few days (see trial_ends_at); billing
|
||||||
|
* starts then. `data.payment_method_missing`: the user has no payment method yet (with
|
||||||
|
* trial_payment_method `optional` the subscription then ends with the trial).
|
||||||
|
*/
|
||||||
|
public const SUBSCRIPTION_TRIAL_WILL_END = 'subscription.trial_will_end';
|
||||||
|
|
||||||
|
/** 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';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A period of a subscription was booked on its collective order, the first one included;
|
||||||
|
* `data.period` describes it, `data.period.first_period` is true for the subscription's first
|
||||||
|
* paid period (checkout or the end of a free trial). Opt-in: only endpoints that select this
|
||||||
|
* event get it (not through `*`).
|
||||||
|
*/
|
||||||
|
public const SUBSCRIPTION_RENEWED = 'subscription.renewed';
|
||||||
|
|
||||||
/** The user confirmed a checkout session: all of its subscriptions are running (sent after their subscription.activated). */
|
/** The user confirmed a checkout session: all of its subscriptions are running (sent after their subscription.activated). */
|
||||||
public const CHECKOUT_COMPLETED = 'checkout.completed';
|
public const CHECKOUT_COMPLETED = 'checkout.completed';
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ namespace Anikeen\Id\Tests;
|
|||||||
|
|
||||||
use Anikeen\Id\AnikeenId;
|
use Anikeen\Id\AnikeenId;
|
||||||
use Anikeen\Id\Billable;
|
use Anikeen\Id\Billable;
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
|
use GuzzleHttp\Psr7\Response;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
class AppOrdersTest extends TestCase
|
class AppOrdersTest extends TestCase
|
||||||
@@ -68,4 +70,65 @@ class AppOrdersTest extends TestCase
|
|||||||
$this->assertNull($orders->find('o1'));
|
$this->assertNull($orders->find('o1'));
|
||||||
$this->assertSame('o1', $orders->find('o1')->id);
|
$this->assertSame('o1', $orders->find('o1')->id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_orders_list_their_lines_and_invoice(): void
|
||||||
|
{
|
||||||
|
$this->respond(200, ['data' => [
|
||||||
|
'id' => 'o1',
|
||||||
|
'user_id' => '01JUSER',
|
||||||
|
'group' => 'team-1',
|
||||||
|
'metadata' => ['topup' => '7'],
|
||||||
|
'items' => [
|
||||||
|
['id' => 'i1', 'subscription_id' => '01JSUB', 'units' => 1, 'price' => 10, 'period_start' => '2026-11-01T00:00:00+00:00', 'period_end' => '2026-12-01T00:00:00+00:00', 'net_amount' => 10, 'discount' => null],
|
||||||
|
['id' => 'i2', 'subscription_id' => '01JSUB', 'units' => 1, 'price' => -2, 'period_start' => '2026-11-01T00:00:00+00:00', 'period_end' => '2026-12-01T00:00:00+00:00', 'net_amount' => -2, 'discount' => ['label' => 'SUMMER20', 'percent_off' => 20, 'amount_off' => null]],
|
||||||
|
],
|
||||||
|
'invoice' => ['id' => 'inv1', 'number' => 'RE-2026-0001', 'status' => 'completed', 'pdf_url' => 'https://id.test/api/v1/client/orders/o1/invoice'],
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$order = $this->owner()->appOrders()->find('o1');
|
||||||
|
|
||||||
|
$this->assertSame('7', $order->metadata->topup);
|
||||||
|
$this->assertSame(8, array_sum(array_map(fn ($item) => $item->net_amount, array_filter($order->items, fn ($item) => $item->subscription_id === '01JSUB'))));
|
||||||
|
$this->assertSame('SUMMER20', $order->items[1]->discount->label);
|
||||||
|
$this->assertSame('RE-2026-0001', $order->invoice->number);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_the_invoice_pdf_is_downloaded_with_the_app_token(): void
|
||||||
|
{
|
||||||
|
$this->http->append(new Response(200, ['Content-Type' => 'application/pdf'], '%PDF-1.7 invoice'));
|
||||||
|
$this->respond(200, ['data' => ['id' => 'o1', 'user_id' => '01JUSER']]);
|
||||||
|
$this->http->append(new Response(200, ['Content-Type' => 'application/pdf'], '%PDF-1.7 invoice'));
|
||||||
|
|
||||||
|
$this->assertSame('%PDF-1.7 invoice', app(AnikeenId::class)->appOrders()->invoicePdf('o1'));
|
||||||
|
$this->assertSame('%PDF-1.7 invoice', $this->owner()->appOrders()->invoicePdf('o1'));
|
||||||
|
|
||||||
|
$calls = array_map(fn ($entry) => $entry['request']->getMethod() . ' ' . $entry['request']->getUri()->getPath() . ' ' . $entry['request']->getHeaderLine('Authorization'), $this->sent);
|
||||||
|
$this->assertSame([
|
||||||
|
'GET /api/v1/client/orders/o1/invoice Bearer app-token',
|
||||||
|
'GET /api/v1/client/orders/o1 Bearer app-token',
|
||||||
|
'GET /api/v1/client/orders/o1/invoice Bearer app-token',
|
||||||
|
], $calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_an_invoice_that_is_not_ready_is_a_conflict(): void
|
||||||
|
{
|
||||||
|
$this->respond(409, ['message' => 'The invoice document is still being created.', 'error' => 'invoice_not_ready']);
|
||||||
|
$this->respond(200, ['data' => ['id' => 'o1', 'user_id' => 'someone-else']]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
app(AnikeenId::class)->appOrders()->invoicePdf('o1');
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertTrue($e->isConflict());
|
||||||
|
$this->assertSame('invoice_not_ready', $e->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->owner()->appOrders()->invoicePdf('o1');
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertTrue($e->isNotFound());
|
||||||
|
$this->assertSame('order_not_found', $e->error);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@ namespace Anikeen\Id\Tests;
|
|||||||
|
|
||||||
use Anikeen\Id\AnikeenId;
|
use Anikeen\Id\AnikeenId;
|
||||||
use Anikeen\Id\Billable;
|
use Anikeen\Id\Billable;
|
||||||
|
use Anikeen\Id\Enums\CancellationReason;
|
||||||
|
use Anikeen\Id\Enums\TrialPaymentMethod;
|
||||||
use Anikeen\Id\Exceptions\ApiException;
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
|
use Anikeen\Id\Resources\AppSubscription;
|
||||||
use GuzzleHttp\Exception\ConnectException;
|
use GuzzleHttp\Exception\ConnectException;
|
||||||
use GuzzleHttp\Psr7\Request;
|
use GuzzleHttp\Psr7\Request;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -87,6 +90,87 @@ class AppSubscriptionsTest extends TestCase
|
|||||||
$this->assertSame(['starts_at' => '2026-05-19T11:33:58+00:00'], $this->sentJson(1));
|
$this->assertSame(['starts_at' => '2026-05-19T11:33:58+00:00'], $this->sentJson(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_a_checkout_without_arguments_sends_no_body(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$this->respond(200, $this->subscription(['active' => true]));
|
||||||
|
|
||||||
|
$this->owner()->appSubscriptions()->create(['name' => 'Server', 'unit' => 'hour', 'price' => 1])->checkout();
|
||||||
|
|
||||||
|
$request = $this->sent[1]['request'];
|
||||||
|
$this->assertSame('PUT /api/v1/client/subscriptions/01JSUB/checkout', $request->getMethod() . ' ' . $request->getUri()->getPath());
|
||||||
|
$this->assertSame('', (string) $request->getBody());
|
||||||
|
$this->assertFalse($request->hasHeader('Content-Type'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_checkout_from_a_date_sends_only_the_start(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$this->respond(200, $this->subscription(['active' => true]));
|
||||||
|
|
||||||
|
$this->owner()->appSubscriptions()->create(['name' => '.de TLD', 'unit' => 'year', 'price' => '5.19'])
|
||||||
|
->checkout('2026-05-19T11:33:58+00:00');
|
||||||
|
|
||||||
|
$this->assertSame('{"starts_at":"2026-05-19T11:33:58+00:00"}', (string) $this->sent[1]['request']->getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_elapsed_periods_are_billed_up_to_the_ceiling(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$this->respond(200, $this->subscription(['active' => true]));
|
||||||
|
|
||||||
|
$this->owner()->appSubscriptions()->create(['name' => '.de TLD', 'unit' => 'year', 'price' => '5.19'])
|
||||||
|
->checkout(new \DateTimeImmutable('2024-05-19 11:33:58', new \DateTimeZone('UTC')), billElapsedPeriods: true, maxNetAmount: '15.57');
|
||||||
|
|
||||||
|
$request = $this->sent[1]['request'];
|
||||||
|
$this->assertSame('PUT /api/v1/client/subscriptions/01JSUB/checkout', $request->getMethod() . ' ' . $request->getUri()->getPath());
|
||||||
|
$this->assertSame(['starts_at' => '2024-05-19T11:33:58+00:00', 'bill_elapsed_periods' => true, 'max_net_amount' => '15.57'], $this->sentJson(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_float_ceiling_is_sent_with_two_decimals(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$this->respond(200, $this->subscription(['active' => true]));
|
||||||
|
|
||||||
|
$this->owner()->appSubscriptions()->create(['name' => '.de TLD', 'unit' => 'year', 'price' => 19.99])
|
||||||
|
->checkout('2024-05-19', true, 19.99 * 3);
|
||||||
|
|
||||||
|
$this->assertSame(['starts_at' => '2024-05-19', 'bill_elapsed_periods' => true, 'max_net_amount' => 59.97], $this->sentJson(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_billing_elapsed_periods_needs_a_start_and_a_ceiling(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$subscription = $this->owner()->appSubscriptions()->create(['name' => '.de TLD', 'unit' => 'year', 'price' => '5.19']);
|
||||||
|
|
||||||
|
foreach ([[null, '10.00'], ['2024-05-19', null], ['', '10.00'], ['2024-05-19', '']] as [$startsAt, $maxNetAmount]) {
|
||||||
|
try {
|
||||||
|
$subscription->checkout($startsAt, billElapsedPeriods: true, maxNetAmount: $maxNetAmount);
|
||||||
|
$this->fail('Expected an InvalidArgumentException.');
|
||||||
|
} catch (InvalidArgumentException) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->assertCount(1, $this->sent);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_an_exceeded_ceiling_carries_the_net_amount(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$this->respond(409, ['message' => 'The elapsed periods come to 20.76 net, more than 15.57.', 'error' => 'elapsed_amount_exceeded', 'net_amount' => '20.76']);
|
||||||
|
|
||||||
|
$subscription = $this->owner()->appSubscriptions()->create(['name' => '.de TLD', 'unit' => 'year', 'price' => '5.19']);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$subscription->checkout('2024-05-19', billElapsedPeriods: true, maxNetAmount: '15.57');
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertTrue($e->isConflict());
|
||||||
|
$this->assertSame('elapsed_amount_exceeded', $e->error);
|
||||||
|
$this->assertSame('20.76', $e->body()->net_amount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function test_errors_carry_status_and_error_code(): void
|
public function test_errors_carry_status_and_error_code(): void
|
||||||
{
|
{
|
||||||
$this->respond(409, ['message' => 'Product subscription has already been cancelled.', 'error' => 'already_cancelled']);
|
$this->respond(409, ['message' => 'Product subscription has already been cancelled.', 'error' => 'already_cancelled']);
|
||||||
@@ -174,6 +258,99 @@ class AppSubscriptionsTest extends TestCase
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_a_subscription_starts_with_a_free_trial(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$this->respond(200, $this->subscription(['active' => true, 'autorenew' => true, 'status' => 'trial', 'starts_at' => '2026-11-04T10:00:00+00:00', 'trial_ends_at' => date(DATE_ATOM, time() + 14 * 86400)]));
|
||||||
|
|
||||||
|
$subscription = $this->owner()->appSubscriptions()->create(['group' => 'team-1', 'name' => 'Pro', 'unit' => 'month', 'price' => '9.99', 'trial_days' => 14, 'trial_once' => true]);
|
||||||
|
$subscription->checkout();
|
||||||
|
|
||||||
|
$this->assertSame(['group' => 'team-1', 'name' => 'Pro', 'unit' => 'month', 'price' => '9.99', 'trial_days' => 14, 'trial_once' => true, 'user_id' => '01JUSER'], $this->sentJson(0));
|
||||||
|
$this->assertTrue($subscription->isTrial());
|
||||||
|
$this->assertTrue($subscription->isActive());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_trial_can_be_confirmed_without_a_payment_method_and_end_cancelled(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription(['trial_days' => 14, 'trial_payment_method' => 'optional']));
|
||||||
|
$this->respond(200, $this->subscription(['active' => false, 'cancelled' => true, 'status' => 'cancelled', 'starts_at' => '2026-11-04T10:00:00+00:00', 'trial_ends_at' => '2026-11-18T10:00:00+00:00', 'cancels_at' => '2026-11-18T10:00:00+00:00', 'trial_payment_method' => 'optional', 'cancellation_reason' => 'trial_ended_without_payment_method']));
|
||||||
|
|
||||||
|
$subscription = $this->owner()->appSubscriptions()->create(['name' => 'Pro', 'unit' => 'month', 'price' => '9.99', 'trial_days' => 14, 'trial_payment_method' => TrialPaymentMethod::OPTIONAL]);
|
||||||
|
|
||||||
|
$this->assertSame('optional', $this->sentJson(0)['trial_payment_method']);
|
||||||
|
$this->assertSame(TrialPaymentMethod::OPTIONAL, $subscription->trial_payment_method);
|
||||||
|
|
||||||
|
$ended = $this->owner()->appSubscriptions()->find('01JSUB');
|
||||||
|
$this->assertTrue($ended->isCancelled());
|
||||||
|
$this->assertSame(CancellationReason::TRIAL_ENDED_WITHOUT_PAYMENT_METHOD, $ended->cancellation_reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_used_trial_is_refused_on_checkout(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->subscription());
|
||||||
|
$this->respond(409, ['message' => 'The user already had a free trial.', 'error' => 'trial_already_used']);
|
||||||
|
|
||||||
|
$subscription = $this->owner()->appSubscriptions()->create(['name' => 'Pro', 'unit' => 'month', 'price' => '9.99', 'trial_ends_at' => '2026-12-01T00:00:00+01:00', 'trial_once' => true]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$subscription->checkout();
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertTrue($e->isConflict());
|
||||||
|
$this->assertSame('trial_already_used', $e->error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_subscription_is_created_with_a_discount(): void
|
||||||
|
{
|
||||||
|
$discount = ['label' => 'SUMMER20', 'percent_off' => 20, 'duration' => 'repeating', 'duration_in_periods' => 3];
|
||||||
|
$this->respond(201, $this->subscription(['discount' => [...$discount, 'amount_off' => null, 'periods_remaining' => 3]]));
|
||||||
|
|
||||||
|
$subscription = $this->owner()->appSubscriptions()->create(['name' => 'Pro', 'unit' => 'month', 'price' => '9.99', 'discount' => $discount]);
|
||||||
|
|
||||||
|
$this->assertSame($discount, $this->sentJson(0)['discount']);
|
||||||
|
$this->assertSame('SUMMER20', $subscription->discount->label);
|
||||||
|
$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
|
public function test_a_missing_user_id_is_reported(): void
|
||||||
{
|
{
|
||||||
$this->expectException(InvalidArgumentException::class);
|
$this->expectException(InvalidArgumentException::class);
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
namespace Anikeen\Id\Tests;
|
namespace Anikeen\Id\Tests;
|
||||||
|
|
||||||
|
use Anikeen\Id\AnikeenId;
|
||||||
use Anikeen\Id\Billable;
|
use Anikeen\Id\Billable;
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
|
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
@@ -60,4 +62,44 @@ class CheckoutConfirmationTest extends TestCase
|
|||||||
$this->assertSame('https://id.anikeen.com/checkout/subscriptions/01JSUB', $e->confirmationUrl);
|
$this->assertSame('https://id.anikeen.com/checkout/subscriptions/01JSUB', $e->confirmationUrl);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_a_trusted_app_lets_the_user_confirm_its_order(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, ['data' => ['id' => '01JORD', 'status' => 'draft', 'group' => 'team-1', 'metadata' => ['topup' => '7'], 'expires_at' => '2026-11-05T10:00:00+00:00', 'confirmation_url' => 'https://id.anikeen.com/checkout/orders/01JORD']]);
|
||||||
|
|
||||||
|
$result = app(AnikeenId::class)->createOrderForUser('01JUSER', [
|
||||||
|
'group' => 'team-1',
|
||||||
|
'confirm' => true,
|
||||||
|
'return_url' => 'https://console.test/billing/topup',
|
||||||
|
'metadata' => ['topup' => '7'],
|
||||||
|
'items' => [['type' => 'digital', 'name' => 'Credit', 'unit' => 'onetime', 'units' => 1, 'gross_price' => '10.00']],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame('POST /api/v1/admin/orders Bearer app-token', $this->sent[0]['request']->getMethod() . ' ' . $this->sent[0]['request']->getUri()->getPath() . ' ' . $this->sent[0]['request']->getHeaderLine('Authorization'));
|
||||||
|
$this->assertTrue($this->sentJson(0)['confirm']);
|
||||||
|
$this->assertSame('https://console.test/billing/topup', $this->sentJson(0)['return_url']);
|
||||||
|
$this->assertSame(['topup' => '7'], $this->sentJson(0)['metadata']);
|
||||||
|
$this->assertSame('01JUSER', $this->sentJson(0)['user_id']);
|
||||||
|
$this->assertSame('https://id.anikeen.com/checkout/orders/01JORD', $result->data->confirmation_url);
|
||||||
|
$this->assertSame('7', $result->data->metadata->topup);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_an_expired_confirmation_is_a_conflict(): void
|
||||||
|
{
|
||||||
|
$this->respond(200, ['data' => []]);
|
||||||
|
$this->respond(201, ['data' => ['id' => '01JORD', 'status' => 'draft', 'confirmation_url' => 'https://id.anikeen.com/checkout/orders/01JORD']]);
|
||||||
|
$this->respond(409, ['message' => 'The order was not confirmed in time.', 'error' => 'confirmation_expired']);
|
||||||
|
|
||||||
|
$order = $this->owner()->orders()->create(['confirm' => true, 'return_url' => 'https://shop.test/done', 'metadata' => ['cart' => 1], 'items' => []]);
|
||||||
|
|
||||||
|
$this->assertSame(['confirm' => true, 'return_url' => 'https://shop.test/done', 'metadata' => ['cart' => 1], 'items' => []], $this->sentJson(1));
|
||||||
|
|
||||||
|
try {
|
||||||
|
$order->checkout();
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertTrue($e->isConflict());
|
||||||
|
$this->assertSame('confirmation_expired', $e->error);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -139,6 +139,32 @@ class CheckoutSessionsTest extends TestCase
|
|||||||
$this->assertNull($user->checkoutSessions()->find('unknown'));
|
$this->assertNull($user->checkoutSessions()->find('unknown'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_session_subscriptions_carry_a_free_trial(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->sessionData());
|
||||||
|
|
||||||
|
$this->owner()->appCheckoutSessions()->create(['subscriptions' => [
|
||||||
|
['group' => 'team-1', 'name' => 'Pro', 'unit' => 'month', 'price' => '9.99', 'trial_days' => 14, 'trial_once' => true],
|
||||||
|
['group' => 'team-1', 'name' => 'Backup', 'unit' => 'month', 'price' => '1.99', 'trial_ends_at' => '2026-12-01T00:00:00+00:00'],
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$this->assertSame(14, $this->sentJson(0)['subscriptions'][0]['trial_days']);
|
||||||
|
$this->assertTrue($this->sentJson(0)['subscriptions'][0]['trial_once']);
|
||||||
|
$this->assertSame('2026-12-01T00:00:00+00:00', $this->sentJson(0)['subscriptions'][1]['trial_ends_at']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_session_subscriptions_carry_a_discount(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, $this->sessionData());
|
||||||
|
|
||||||
|
$this->owner()->checkoutSessions()->create(['subscriptions' => [
|
||||||
|
['name' => 'Pro', 'unit' => 'month', 'price' => 4.99, 'discount' => ['label' => 'WELCOME', 'amount_off' => '1.00', 'duration' => 'once']],
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$this->assertSame('POST /api/v1/checkout-sessions Bearer user-token', $this->request(0));
|
||||||
|
$this->assertSame(['label' => 'WELCOME', 'amount_off' => '1.00', 'duration' => 'once'], $this->sentJson(0)['subscriptions'][0]['discount']);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_nothing_is_requested_until_a_method_is_called(): void
|
public function test_nothing_is_requested_until_a_method_is_called(): void
|
||||||
{
|
{
|
||||||
$this->owner()->checkoutSessions();
|
$this->owner()->checkoutSessions();
|
||||||
@@ -159,5 +185,8 @@ class CheckoutSessionsTest extends TestCase
|
|||||||
$this->assertSame(['01JS1', '01JS2'], $event['data']['object']['subscription_ids']);
|
$this->assertSame(['01JS1', '01JS2'], $event['data']['object']['subscription_ids']);
|
||||||
$this->assertContains('checkout.expired', EventType::all());
|
$this->assertContains('checkout.expired', EventType::all());
|
||||||
$this->assertContains('subscription.activated', EventType::all());
|
$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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@ namespace Anikeen\Id\Tests;
|
|||||||
|
|
||||||
use Anikeen\Id\AnikeenId;
|
use Anikeen\Id\AnikeenId;
|
||||||
use Anikeen\Id\Billable;
|
use Anikeen\Id\Billable;
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,6 +91,52 @@ class EndpointsTest extends TestCase
|
|||||||
$this->assertSame(['email' => 'erika@example.com', 'password' => 'secret-123', 'name' => 'Erika Mustermann', 'password_confirmation' => 'secret-123'], $this->sentJson(0));
|
$this->assertSame(['email' => 'erika@example.com', 'password' => 'secret-123', 'name' => 'Erika Mustermann', 'password_confirmation' => 'secret-123'], $this->sentJson(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_create_user_can_send_an_invitation(): void
|
||||||
|
{
|
||||||
|
$this->respond(201, ['data' => ['id' => '01JNEW', 'email' => 'erika@example.com', 'created' => true, 'invitation_sent' => true]]);
|
||||||
|
|
||||||
|
$result = app(AnikeenId::class)->createUser(['name' => 'Erika Mustermann', 'email' => 'erika@example.com', 'send_invitation' => true]);
|
||||||
|
|
||||||
|
$this->assertSame('POST /api/v1/admin/users Bearer app-token', $this->sentCall(0));
|
||||||
|
$this->assertSame(['name' => 'Erika Mustermann', 'email' => 'erika@example.com', 'send_invitation' => true], $this->sentJson(0));
|
||||||
|
$this->assertTrue($result->data->created);
|
||||||
|
$this->assertTrue($result->data->invitation_sent);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_find_user_by_email_uses_the_lookup_endpoint(): void
|
||||||
|
{
|
||||||
|
$this->respond(200, ['data' => ['id' => '01JUSER', 'name' => 'Erika', 'email' => 'erika@example.com', 'email_verified' => true, 'has_billing_address' => false]]);
|
||||||
|
|
||||||
|
$result = app(AnikeenId::class)->findUserByEmail('Erika@Example.com');
|
||||||
|
|
||||||
|
$this->assertSame('POST /api/v1/admin/users/lookup Bearer app-token', $this->sentCall(0));
|
||||||
|
$this->assertSame(['email' => 'Erika@Example.com'], $this->sentJson(0));
|
||||||
|
$this->assertSame('01JUSER', $result->data->id);
|
||||||
|
$this->assertFalse($result->data->has_billing_address);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_find_user_by_email_returns_null_without_an_account(): void
|
||||||
|
{
|
||||||
|
$this->respond(404, ['message' => 'User not found.', 'error' => 'user_not_found']);
|
||||||
|
|
||||||
|
$this->assertNull(app(AnikeenId::class)->findUserByEmail('nobody@example.com'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_find_user_by_email_throws_other_failures(): void
|
||||||
|
{
|
||||||
|
$this->respond(404, ['message' => 'Not found.']); // e.g. an Anikeen ID without the lookup
|
||||||
|
$this->respond(500, ['message' => 'Server Error']);
|
||||||
|
|
||||||
|
foreach ([404, 500] as $status) {
|
||||||
|
try {
|
||||||
|
app(AnikeenId::class)->findUserByEmail('erika@example.com');
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertSame($status, $e->status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function test_email_check_and_socialite_users(): void
|
public function test_email_check_and_socialite_users(): void
|
||||||
{
|
{
|
||||||
$this->respond(200, ['data' => ['exists' => true]]);
|
$this->respond(200, ['data' => ['exists' => true]]);
|
||||||
@@ -199,6 +246,35 @@ class EndpointsTest extends TestCase
|
|||||||
$this->assertSame('POST /api/v1/admin/transactions Bearer app-token', $this->sentCall(1));
|
$this->assertSame('POST /api/v1/admin/transactions Bearer app-token', $this->sentCall(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_billing_portal_links_for_users_use_the_app_token(): void
|
||||||
|
{
|
||||||
|
$link = ['object' => 'billing_portal_link', 'url' => 'https://id.test/billing/portal/01JUSER?signature=x', 'user_id' => '01JUSER', 'flow' => 'invoices', 'group' => 'team-1', 'return_url' => 'https://console.test/billing', 'expires_at' => '2026-11-04T10:15:00+00:00'];
|
||||||
|
$this->respond(201, ['data' => $link]);
|
||||||
|
$this->respond(201, ['data' => $link]);
|
||||||
|
|
||||||
|
$created = app(AnikeenId::class)->createBillingPortalLinkForUser('01JUSER', ['return_url' => 'https://console.test/billing', 'group' => 'team-1', 'flow' => 'invoices']);
|
||||||
|
$url = $this->owner()->appBillingPortalUrl(['flow' => 'payment_method_update']);
|
||||||
|
|
||||||
|
$this->assertSame('billing_portal_link', $created->object);
|
||||||
|
$this->assertSame($link['url'], $url);
|
||||||
|
$this->assertSame('POST /api/v1/client/users/01JUSER/billing-portal Bearer app-token', $this->sentCall(0));
|
||||||
|
$this->assertSame(['return_url' => 'https://console.test/billing', 'group' => 'team-1', 'flow' => 'invoices'], $this->sentJson(0));
|
||||||
|
$this->assertSame('POST /api/v1/client/users/01JUSER/billing-portal Bearer app-token', $this->sentCall(1));
|
||||||
|
$this->assertSame(['flow' => 'payment_method_update'], $this->sentJson(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_refused_billing_portal_link_is_an_api_exception(): void
|
||||||
|
{
|
||||||
|
$this->respond(422, ['message' => 'The return URL has to point to one of the app\'s redirect URIs.', 'errors' => ['return_url' => ['…']]]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->owner()->appBillingPortalUrl(['return_url' => 'https://elsewhere.test']);
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertSame(422, $e->status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function test_order_preview_maps_the_country_into_the_billing_address(): void
|
public function test_order_preview_maps_the_country_into_the_billing_address(): void
|
||||||
{
|
{
|
||||||
$this->respond(200, ['data' => ['gross_total' => 11.9]]);
|
$this->respond(200, ['data' => ['gross_total' => 11.9]]);
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Anikeen\Id\Tests;
|
||||||
|
|
||||||
|
use Anikeen\Id\Enums\Scope;
|
||||||
|
use PHPUnit\Framework\Attributes\DataProvider;
|
||||||
|
use ReflectionClass;
|
||||||
|
|
||||||
|
class ScopeTest extends TestCase
|
||||||
|
{
|
||||||
|
public static function newScopes(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'products:read' => [Scope::PRODUCTS_READ, 'products:read'],
|
||||||
|
'reseller-customers' => [Scope::RESELLER_CUSTOMERS, 'reseller-customers'],
|
||||||
|
'reseller-customers:read' => [Scope::RESELLER_CUSTOMERS_READ, 'reseller-customers:read'],
|
||||||
|
'reseller-grants' => [Scope::RESELLER_GRANTS, 'reseller-grants'],
|
||||||
|
'reseller-orders' => [Scope::RESELLER_ORDERS, 'reseller-orders'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
#[DataProvider('newScopes')]
|
||||||
|
public function test_the_product_and_reseller_scopes_have_their_names(string $constant, string $expected): void
|
||||||
|
{
|
||||||
|
$this->assertSame($expected, $constant);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_there_is_no_full_products_scope_the_console_would_not_accept(): void
|
||||||
|
{
|
||||||
|
// the Console's product APIs accept `user`, `user:read` and `products:read` only
|
||||||
|
$this->assertNotContains('products', (new ReflectionClass(Scope::class))->getConstants());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_every_scope_follows_the_resource_and_level_schema(): void
|
||||||
|
{
|
||||||
|
$scopes = array_values((new ReflectionClass(Scope::class))->getConstants());
|
||||||
|
|
||||||
|
$this->assertSame($scopes, array_values(array_unique($scopes)), 'scope values must be unique');
|
||||||
|
|
||||||
|
foreach ($scopes as $scope) {
|
||||||
|
// "resource" (full access), "resource:read" or "resource:client"; Anikeen ID groups by resource
|
||||||
|
$this->assertMatchesRegularExpression('/^[a-z]+(-[a-z]+)*(:(read|client))?$/', $scope);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_each_reseller_resource_is_its_own_group(): void
|
||||||
|
{
|
||||||
|
$groups = collect((new ReflectionClass(Scope::class))->getConstants())
|
||||||
|
->filter(fn (string $scope) => str_starts_with($scope, 'reseller-'))
|
||||||
|
->groupBy(fn (string $scope) => explode(':', $scope)[0])
|
||||||
|
->map(fn ($scopes) => $scopes->sort()->values()->all())
|
||||||
|
->all();
|
||||||
|
|
||||||
|
$this->assertSame([
|
||||||
|
'reseller-customers' => ['reseller-customers', 'reseller-customers:read'],
|
||||||
|
'reseller-grants' => ['reseller-grants'],
|
||||||
|
'reseller-orders' => ['reseller-orders'],
|
||||||
|
], $groups);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Anikeen\Id\Tests;
|
||||||
|
|
||||||
|
use Anikeen\Id\Billable;
|
||||||
|
use Anikeen\Id\Enums\SubscriptionStatus;
|
||||||
|
use Anikeen\Id\Resources\AppSubscription;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use PHPUnit\Framework\Attributes\DataProvider;
|
||||||
|
|
||||||
|
class SubscriptionStatusTest extends TestCase
|
||||||
|
{
|
||||||
|
private const BASE = ['id' => '01JSUB', 'active' => false, 'autorenew' => true, 'cancelled' => false, 'starts_at' => null, 'cancels_at' => null, 'trial_ends_at' => null];
|
||||||
|
|
||||||
|
public static function states(): array
|
||||||
|
{
|
||||||
|
$started = ['starts_at' => '2026-10-01T00:00:00+00:00'];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'draft' => [[], SubscriptionStatus::DRAFT, false],
|
||||||
|
'active' => [['active' => true, ...$started], SubscriptionStatus::ACTIVE, true],
|
||||||
|
'trial' => [['active' => true, 'trial_ends_at' => date(DATE_ATOM, time() + 86400), ...$started], SubscriptionStatus::TRIAL, true],
|
||||||
|
'trial over' => [['active' => true, 'trial_ends_at' => '2026-01-01T00:00:00+00:00', ...$started], SubscriptionStatus::ACTIVE, true],
|
||||||
|
'paused' => [['active' => true, 'autorenew' => false, ...$started], SubscriptionStatus::PAUSED, true],
|
||||||
|
'cancelling' => [['active' => true, 'cancels_at' => '2027-01-01T00:00:00+00:00', ...$started], SubscriptionStatus::CANCELLING, true],
|
||||||
|
'expired' => [['autorenew' => false, ...$started], SubscriptionStatus::EXPIRED, false],
|
||||||
|
'cancelled' => [['autorenew' => false, 'cancelled' => true, ...$started], SubscriptionStatus::CANCELLED, false],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
#[DataProvider('states')]
|
||||||
|
public function test_the_status_follows_the_fields(array $fields, string $status, bool $running): void
|
||||||
|
{
|
||||||
|
$data = [...self::BASE, ...$fields];
|
||||||
|
|
||||||
|
$this->respond(200, ['data' => [$data]]); // subscriptions() loads the list
|
||||||
|
$this->respond(200, ['data' => $data]);
|
||||||
|
$owner = new class extends Model {
|
||||||
|
use Billable;
|
||||||
|
};
|
||||||
|
$owner->anikeen_id_access_token = 'user-token';
|
||||||
|
$subscription = $owner->subscriptions()->find('01JSUB');
|
||||||
|
|
||||||
|
$app = new AppSubscription((object) $data);
|
||||||
|
|
||||||
|
foreach ([$subscription, $app] as $resource) {
|
||||||
|
$this->assertSame($status, $resource->status());
|
||||||
|
$this->assertSame($running, $resource->isActive());
|
||||||
|
$this->assertSame($status === SubscriptionStatus::DRAFT, $resource->isDraft());
|
||||||
|
$this->assertSame($status === SubscriptionStatus::TRIAL, $resource->isTrial());
|
||||||
|
$this->assertSame($status === SubscriptionStatus::PAUSED, $resource->isPaused());
|
||||||
|
$this->assertSame($status === SubscriptionStatus::CANCELLING, $resource->isCancelling());
|
||||||
|
$this->assertSame($status === SubscriptionStatus::EXPIRED, $resource->isExpired());
|
||||||
|
$this->assertSame($status === SubscriptionStatus::CANCELLED, $resource->isCancelled());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Anikeen\Id\Tests;
|
||||||
|
|
||||||
|
use Anikeen\Id\Billable;
|
||||||
|
use Anikeen\Id\Exceptions\ApiException;
|
||||||
|
use Anikeen\Id\Exceptions\CollectionException;
|
||||||
|
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
|
||||||
|
use Anikeen\Id\Exceptions\ResourceException;
|
||||||
|
use GuzzleHttp\Exception\ConnectException;
|
||||||
|
use GuzzleHttp\Psr7\Request;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class UserApiExceptionsTest extends TestCase
|
||||||
|
{
|
||||||
|
private function user(): Model
|
||||||
|
{
|
||||||
|
$user = new class extends Model {
|
||||||
|
use Billable;
|
||||||
|
};
|
||||||
|
$user->anikeen_id_access_token = 'user-token';
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_refused_request_carries_status_and_error_code(): void
|
||||||
|
{
|
||||||
|
$this->respond(200, ['data' => []]); // orders() loads the list
|
||||||
|
$this->respond(422, ['message' => 'The billing address is missing.', 'error' => 'billing_address_missing']);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->user()->orders()->create(['items' => []]);
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertInstanceOf(ResourceException::class, $e, 'existing catch (ResourceException) blocks keep working');
|
||||||
|
$this->assertSame(422, $e->status);
|
||||||
|
$this->assertSame(422, $e->getCode());
|
||||||
|
$this->assertSame('billing_address_missing', $e->error);
|
||||||
|
$this->assertSame('The billing address is missing', $e->getMessage());
|
||||||
|
$this->assertFalse($e->isTemporary());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_an_unknown_id_is_not_found(): void
|
||||||
|
{
|
||||||
|
$this->respond(200, ['data' => []]);
|
||||||
|
$this->respond(404, ['message' => 'Not found.']);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->user()->orders()->find('01JMISSING');
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertTrue($e->isNotFound());
|
||||||
|
$this->assertNull($e->error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_failed_list_is_an_api_exception_too(): void
|
||||||
|
{
|
||||||
|
$this->respond(503, ['message' => 'Maintenance.']);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->user()->invoices();
|
||||||
|
$this->fail('Expected a CollectionException.');
|
||||||
|
} catch (CollectionException $e) {
|
||||||
|
$this->assertInstanceOf(ApiException::class, $e);
|
||||||
|
$this->assertSame(503, $e->status);
|
||||||
|
$this->assertTrue($e->isTemporary());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_no_response_is_temporary_with_status_zero(): void
|
||||||
|
{
|
||||||
|
$this->respond(200, ['data' => []]);
|
||||||
|
$this->http->append(new ConnectException('Connection refused', new Request('GET', 'v1/orders/01J')));
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->user()->orders()->find('01J');
|
||||||
|
$this->fail('Expected an ApiException.');
|
||||||
|
} catch (ApiException $e) {
|
||||||
|
$this->assertSame(0, $e->status);
|
||||||
|
$this->assertTrue($e->isTemporary());
|
||||||
|
$this->assertInstanceOf(ConnectException::class, $e->getPrevious());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_confirmation_required_stays_its_own_exception(): void
|
||||||
|
{
|
||||||
|
$this->respond(200, ['data' => []]);
|
||||||
|
$this->respond(200, ['data' => ['id' => '01JORDER', 'status' => 'draft']]);
|
||||||
|
$this->respond(403, ['message' => 'Confirm it on Anikeen ID.', 'error' => 'confirmation_required', 'confirmation_url' => 'https://id.test/confirm/01JORDER']);
|
||||||
|
|
||||||
|
$this->expectException(ConfirmationRequiredException::class);
|
||||||
|
|
||||||
|
$this->user()->orders()->find('01JORDER')->checkout();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace Anikeen\Id\Tests;
|
namespace Anikeen\Id\Tests;
|
||||||
|
|
||||||
use Anikeen\Id\Exceptions\SignatureVerificationException;
|
use Anikeen\Id\Exceptions\SignatureVerificationException;
|
||||||
|
use Anikeen\Id\Webhooks\EventType;
|
||||||
use Anikeen\Id\Webhooks\Webhook;
|
use Anikeen\Id\Webhooks\Webhook;
|
||||||
|
|
||||||
class WebhookTest extends TestCase
|
class WebhookTest extends TestCase
|
||||||
@@ -53,4 +54,31 @@ class WebhookTest extends TestCase
|
|||||||
|
|
||||||
Webhook::constructEvent($this->payload, null, $this->secret);
|
Webhook::constructEvent($this->payload, null, $this->secret);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_a_renewal_carries_the_booked_period(): void
|
||||||
|
{
|
||||||
|
$this->payload = json_encode(['id' => '01JEVT', 'type' => EventType::SUBSCRIPTION_RENEWED, 'created' => time(), 'data' => [
|
||||||
|
'object' => ['id' => '01JSUB', 'status' => 'active'],
|
||||||
|
'period' => ['object' => 'subscription_period', 'subscription_id' => '01JSUB', 'period_start' => '2026-11-01T00:00:00+00:00', 'period_end' => '2026-12-01T00:00:00+00:00', 'periods' => 1, 'first_period' => true, 'unit' => 'month', 'order_id' => '01JORD', 'order_item_id' => '01JITEM', 'items' => [], 'currency_iso' => 'EUR', 'net_amount' => 8],
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$event = Webhook::constructEvent($this->payload, $this->header(), $this->secret);
|
||||||
|
|
||||||
|
$this->assertSame('subscription.renewed', $event['type']);
|
||||||
|
$this->assertSame('01JORD', $event['data']['period']['order_id']);
|
||||||
|
$this->assertTrue($event['data']['period']['first_period']);
|
||||||
|
$this->assertContains(EventType::SUBSCRIPTION_RENEWED, EventType::all());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_change_carries_the_previous_attributes(): void
|
||||||
|
{
|
||||||
|
$this->payload = json_encode(['id' => '01JEVT', 'type' => EventType::SUBSCRIPTION_UPDATED, 'created' => time(), 'data' => [
|
||||||
|
'object' => ['id' => '01JSUB', 'price' => 14.99],
|
||||||
|
'previous_attributes' => ['price' => 9.99],
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$event = Webhook::constructEvent($this->payload, $this->header(), $this->secret);
|
||||||
|
|
||||||
|
$this->assertSame(9.99, $event['data']['previous_attributes']['price']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user