Compare commits

...
Author SHA1 Message Date
Maurice PreußandClaude Opus 5.5 34f6854bdd Fix the checkout session return status docs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:35:25 +01:00
Maurice PreußandClaude Opus 5.5 3acd36ca29 Add checkout sessions and webhook event type constants
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:26:24 +01:00
envoyr a0470111fa Merge pull request #10 from anikeen-com/docs/shipment-mail
Document the shipment mail and notify_customer
2026-11-01 15:04:09 +01:00
Maurice PreußandClaude Opus 5.5 934b1c5c3f Document the shipment mail and notify_customer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:57:46 +01:00
envoyr 6a568a5354 Merge pull request #9 from anikeen-com/feature/shipments
Shipments: ship orders and download delivery notes
2026-11-01 14:20:32 +01:00
Maurice PreußandClaude Opus 5.5 5349ee81f6 Ship orders: shipments with delivery notes
$order->shipments()->create([...]) records a delivery of a paid order's goods on Anikeen ID,
which adds its delivery note to the user's order documents and sends order.shipped.
$shipment->deliveryNote() downloads the PDF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:01:45 +01:00
envoyr 60b4b80f17 Merge pull request #8 from anikeen-com/docs/subscription-description
Document changing the description of running app subscriptions
2026-11-01 13:52:30 +01:00
Maurice PreußandClaude Opus 5.5 1f645b50bc Document changing the description of running app subscriptions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:29:30 +01:00
envoyr 9731dd36ca Merge pull request #7 from anikeen-com/docs/order-shipping-address
Fix saving Billable models after API calls; document shipping addresses and item images
2026-11-01 13:05:01 +01:00
Maurice PreußandClaude Opus 5.5 be59602b30 Declare the billable's API caches, so Eloquent models can still be saved
The caches were undeclared properties: on an Eloquent model they went through
Model::__set into the attributes, and save() failed with "no such column: ordersCache".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 12:55:51 +01:00
Maurice PreußandClaude Opus 5.5 fd96e559af Document shipping address fields and item images on orders
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 12:36:26 +01:00
envoyr d6e6684d00 Merge pull request #6 from anikeen-com/feature/webhooks
Verify Anikeen ID webhooks
2026-11-01 11:48:51 +01:00
envoyr 68132e7026 Merge pull request #5 from anikeen-com/feature/checkout-confirmation
Third-party checkout confirmation
2026-11-01 11:48:16 +01:00
Maurice PreußandClaude Opus 5.5 5c09089822 Drop the unused per-subscription webhook fields
Apps receive events through their webhook endpoints now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:18:38 +01:00
Maurice PreußandClaude Opus 5.5 526b65cb5c Verify Anikeen ID webhooks
Webhook::constructEvent() checks the Anikeen-Signature header (HMAC-SHA256
of "t.body" with the endpoint's secret, 5-minute tolerance) and returns
the event, like Stripe's helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:14:42 +01:00
Maurice PreußandClaude Opus 5.5 f20a12e6da Support third-party checkout confirmation
Orders and subscriptions created by untrusted apps are confirmed by the
user on Anikeen ID. confirmationUrl($returnUrl) on Order and
Subscription builds the link with the return URL; checking out such a
draft throws ConfirmationRequiredException carrying the same URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:01:48 +01:00
envoyr 0fce38f48a Merge pull request #4 from anikeen-com/feature/backdated-checkout
checkout(startsAt:) for services that are already running
2026-10-25 19:04:57 +01:00
Maurice PreußandClaude Opus 5.5 c4a42b4ddc Check out a running service from its start
AppSubscription::checkout() takes an optional $startsAt (needs id-core
with starts_at support on PUT v1/client/subscriptions/{id}/checkout).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:03:47 +01:00
envoyr a1707e9189 Merge pull request #3 from anikeen-com/app-subscriptions
App orders: read the orders that bill the app's subscriptions
2026-10-25 18:18:57 +01:00
Maurice PreußandClaude Opus 5.5 820f1b37cc Read the orders that bill the app's subscriptions
$user->appOrders() and app(AnikeenId::class)->appOrders() read
v1/client/orders with the app's own token (scope orders:client):
all(), pending() and find(), paginated transparently, user scoped
when called on a billable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:14:40 +01:00
envoyr 9a6f40ad99 Merge pull request #2 from anikeen-com/app-subscriptions
Bring anikeen/id up to date: app subscriptions, fixed and missing endpoints, Laravel 11-13
2026-10-25 17:25:22 +01:00
Maurice PreußandClaude Opus 5.5 9613d31a8d Bring the package up to date with the Anikeen ID API
Fixed (called endpoints that don't exist):
- charge(): POST v1/billing/charge (Stripe options aren't passed through anymore)
- Invoice::getInvoiceTemporaryUrl(): GET instead of a non-existent PUT
- OrderItems::create(): POST v1/orders/{order}/items
- createUser() / isEmailExisting(): admin endpoints with the app token
- sshKeysByUserId(): app endpoint; no longer returns the first user's keys for every user
- createOrderPreview(): country_iso goes into billing_address as the API expects
- public endpoints (products, order preview) work without a token
- SshKeys::find() results can be deleted

Added:
- Billable: sshKeys() (create, update, delete), billingOverview(), PaymentMethod::delete()
- AnikeenId: products(), boxes(), shipping labels (list, show, pdf, issue, ship, price list),
  createOrderForUser(), createTransactionForUser(), findOrCreateSocialiteUser()

Requirements: PHP 8.2+, Laravel 11-13 (Laravel 10 and PHP 8.1 are end of life).
Docs generator handles union types; README regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:18:05 +01:00
Maurice PreußandClaude Opus 5.5 8de737641e App subscriptions: manage a user's subscriptions with the app's own token
- $user->appSubscriptions(): create (idempotency_key), find, all, checkout, revoke, pause,
  resume, update against /v1/client/subscriptions with a client credentials token, so apps don't
  depend on the user's login
- user id from the billable's anikeen_id (AnikeenId::useUserIdField())
- ApiException with status, stable error code, isNotFound/isConflict/isTemporary; network
  errors no longer escape as raw Guzzle exceptions
- rejected app tokens are renewed once; asApp() never changes the shared client's token
- tests (testbench + Guzzle mock) and CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:02:16 +01:00
René PreußandClaude Sonnet 4.6 9c3f9344a0 Add ManagesSocialiteUsers concern and resources for listing third-party connections
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 17:47:12 +02:00
Maurice Preuß a7ec7aa908 add set default payment method
Signed-off-by: Maurice Preuß <envoyr@froxlor.org>
2026-05-17 16:46:06 +02:00
envoyr 4555efa80c Update Laravel version requirements in composer.json
Updated Laravel version requirements to include 13.0.
2026-05-12 17:29:14 +02:00
Maurice Preuß 4f78e32af1 update composer.json
Signed-off-by: Maurice Preuß <envoyr@froxlor.org>
2026-05-08 16:27:18 +02:00
envoyr bc9c202c3b update composer.json 2025-09-21 17:15:45 +00:00
envoyr cecf8560ff Merge pull request #1 from anikeen-com/laravel-10
Update composer.json
2025-09-21 19:13:39 +02:00
envoyr 25248e7822 refactor code 2025-09-21 17:12:19 +00:00
envoyr c641ec725d add refund to revoke endpoint 2025-09-21 12:13:56 +00:00
envoyr 8eb0c25582 fix api path 2025-09-19 17:21:23 +00:00
envoyr 30ac4ae4f9 update provider 2025-09-19 16:37:22 +00:00
envoyr e1a6af11a3 introduce new scopes 2025-09-19 15:36:28 +00:00
envoyr bb5df7f115 fix mode
Signed-off-by: Maurice Preuß <hello@envoyr.com>
2025-09-18 19:28:08 +00:00
envoyr 297404b05d add AllowDynamicProperties attribute
Signed-off-by: Maurice Preuß <hello@envoyr.com>
2025-09-18 19:22:11 +00:00
envoyr 5ab57dcdfe add staging key
Signed-off-by: Maurice Preuß <hello@envoyr.com>
2025-09-18 19:17:50 +00:00
envoyr 0f14fa1b4c remove endpoint
Signed-off-by: Maurice Preuß <hello@envoyr.com>
2025-09-06 13:32:06 +00:00
envoyr 437e78770c fix typo
Signed-off-by: Maurice Preuß <hello@envoyr.com>
2025-09-06 13:23:00 +00:00
envoyr 0dbb27fc94 update transaction description
Signed-off-by: Maurice Preuß <hello@envoyr.com>
2025-09-06 13:22:23 +00:00
René Preuß 8232de4003 Update OauthTrait.php 2025-07-30 23:08:13 +02:00
René Preuß ac3e28f67f Update composer.json 2025-07-30 21:52:09 +02:00
envoyr 63e3f0a4a2 add refresh token method
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-05-02 07:29:43 +02:00
envoyr 1d2119a32b update resources
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-05-02 06:27:53 +02:00
envoyr 1725ec68de update subscriptions
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-05-01 18:16:51 +02:00
envoyr dcda4b990e update user provider
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-04-30 12:00:34 +02:00
envoyr 937fde603b update docs
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-04-30 10:03:27 +02:00
envoyr 80b1f003b2 update docs
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-04-30 10:02:53 +02:00
envoyr aff901de4e update docs
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-04-30 10:02:23 +02:00
envoyr 92eadcca08 update docs
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-04-30 10:00:27 +02:00
envoyr 8b874f540c update docs
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-04-30 09:08:29 +02:00
envoyr 3bcebd9d45 update subscription, add alias
Signed-off-by: Maurice Preuß (envoyr) <hello@envoyr.com>
2025-04-30 09:02:24 +02:00
88 changed files with 3818 additions and 682 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
name: tests
on:
push:
branches: [main]
pull_request:
jobs:
tests:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: ['8.3', '8.4']
steps:
- uses: actions/checkout@v6
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- run: composer update --no-interaction --prefer-dist --no-progress
- run: vendor/bin/phpunit
+320 -46
View File
@@ -93,6 +93,222 @@ class User extends Authenticatable
then, you can use the `Billable` trait methods in your user model. then, you can use the `Billable` trait methods in your user model.
### App subscriptions (trusted apps, no user token)
`subscriptions()` acts with the user's own access token and stops working when the user's login
expired. Trusted apps can manage a user's subscriptions with the app's own token (client
credentials, scope `subscriptions:client`) instead:
```php
$subscriptions = $team->owner->appSubscriptions(); // nothing is requested yet
$subscription = $subscriptions->create([
'group' => $team->id,
'name' => 'Cloud Server S',
'unit' => 'hour',
'price' => 0.0137,
'idempotency_key' => "server:{$pendingServer->id}", // retries return the same subscription
]);
$subscription->checkout(); // bill the first period
$subscription->checkout(startsAt: $domain->registered_at); // already running: bill the period that started then
$subscription->pause(); // expires when the paid period ends
$subscription->resume(); // expired subscriptions start a new period
$subscription->revoke(refund: false); // cancel
$subscriptions->find($id); // null if unknown or not this user's
$subscriptions->all(['group' => $team->id, 'active' => true]);
```
The user's Anikeen ID is read from the billable's `anikeen_id` attribute
(`AnikeenId::useUserIdField('…')` to change it). The app must be trusted by Anikeen ID; it sees the
subscriptions it created (plus those of clients delegated to it).
Failures throw `Anikeen\Id\Exceptions\ApiException` with `status` (0 = not reachable), a stable
`error` code (`already_active`, `already_cancelled`, `not_active`, `already_paused`,
`already_resumed`, `billing_address_missing`, `not_changeable`, `subscription_not_found`,
`idempotency_key_conflict`) and `isNotFound()`, `isConflict()`, `isTemporary()`:
```php
try {
$subscription->revoke();
} catch (ApiException $e) {
if ($e->isNotFound() || $e->error === 'already_cancelled') {
// already gone
} elseif ($e->isTemporary()) {
// retry later
} else {
throw $e;
}
}
```
### App orders (trusted apps, no user token)
Orders that bill the app's subscriptions, read with the app's token (scope `orders:client`):
```php
$team->owner->appOrders()->pending(); // unpaid orders of one user, oldest first
app(AnikeenId::class)->appOrders()->pending(); // of all users
$team->owner->appOrders()->find($orderId); // null if unknown or not this user's
```
Each order has `status` (`processing` = current month, still collecting; `pending` = closed and not
paid; `completed`; `cancelled`), the totals, `payment_attempts`, `next_payment_attempt_at` (null =
no more automatic retries) and `last_payment_error`.
### Checkout sessions (the user confirms several subscriptions at once)
Instead of checking subscriptions out itself, an app can let the user confirm them on Anikeen ID,
all of them in one step: a checkout session bundles new subscriptions (or existing drafts of the
app, `['id' => …]`) of one user. The user sees every item with its price and the total of the first
period, confirms (all subscriptions start, or none) or cancels, and returns to `return_url`.
Open sessions expire after 24 hours with their drafts. Trusted apps can still check out directly;
sessions are opt-in.
Example: the Console's builder ("Jetzt kaufen") with several products and coupon prices:
```php
use Anikeen\Id\Exceptions\ApiException;
$session = $request->user()->appCheckoutSessions()->create([ // app token; or ->checkoutSessions() with the user's token
'return_url' => route('builder.done'), // same origin as one of your redirect URIs
'metadata' => ['cart' => $cart->id], // returned as is
'idempotency_key' => "cart:{$cart->id}", // retries return the same session
'subscriptions' => $cart->items->map(fn ($item) => [
'group' => $team->id,
'name' => $item->product->name,
'description' => $item->label,
'unit' => $item->unit, // hour, day, week, month, year
'price' => $item->priceAfterCoupon(), // net, per unit
'payload' => ['cart_item' => $item->id],
])->all(),
]);
$cart->update(['checkout_session_id' => $session->id, 'subscription_ids' => $session->subscriptionIds()]);
return redirect($session->confirmationUrl());
// later: https://console.test/builder/done?status=completed&checkout_session=01K…
```
Provision when the webhook arrives (or after checking the session through the API; never trust the
query string):
```php
use Anikeen\Id\Webhooks\EventType;
match ($event['type']) {
EventType::CHECKOUT_COMPLETED => Provisioner::provision($event['data']['object']['subscriptions']), // all running
EventType::CHECKOUT_CANCELLED, EventType::CHECKOUT_EXPIRED => Cart::release($event['data']['object']['metadata']['cart'] ?? null),
default => null,
};
app(AnikeenId::class)->appCheckoutSessions()->find($id)?->isCompleted(); // any user's session
$session->refresh()->subscriptions(); // AppSubscription objects
$session->cancel(); // withdraw an open session and its drafts (e.g. the cart changed)
```
While a session is open, its subscriptions can't be checked out or repriced by the app (409
`in_checkout_session` / `not_changeable`). The session's `status` is `open`, `completed`,
`cancelled` or `expired` (`isOpen()`, `isCompleted()`, `isCancelled()` for cancelled or expired).
`subscription.activated` / `subscription.cancelled` are still sent per subscription, before the
`checkout.*` event of the session.
### Selling as a third-party app (user confirms on Anikeen ID)
Apps that are not trusted can create orders and subscriptions for the signed-in user (user token),
but can't charge them. The user confirms on Anikeen ID and comes back to your `return_url`:
```php
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
$order = $user->orders()->create([
'billing_address_id' => $addressId,
'items' => [['type' => 'digital', 'name' => 'Sticker pack', 'unit' => 'piece', 'units' => 1, 'gross_price' => '9.99']],
]);
return redirect($order->confirmationUrl(route('shop.done')));
// later: https://your-app.test/shop/done?status=completed&order=01J…
```
`return_url` must have the origin of one of your app's redirect URIs. `status` is `completed`,
`pending` (payment still processing) or `cancelled`; check it with `$user->orders()->find($id)`
instead of trusting the query string. Subscriptions work the same way
(`$user->subscriptions()->create([...])->confirmationUrl(...)`, `&subscription=…`).
Unconfirmed bookings are cancelled after 24 hours.
Physical goods need a shipping address (`first_name`, `last_name`, `address`, `postal_code`,
`city`, `country_iso`). The user can change both addresses on the confirmation page, so read the
shipping address from the order (or the `order.completed` webhook) before you ship. An item's
`image_url` is copied to Anikeen ID and stays visible on the order and invoice:
```php
$order = $user->orders()->create([
'billing_address_id' => $addressId,
'shipping_address' => ['first_name' => 'Ada', 'last_name' => 'Lovelace', 'address' => 'Main St', 'house_number' => '1', 'postal_code' => '10115', 'city' => 'Berlin', 'country_iso' => 'DE'],
'items' => [
['type' => 'physical', 'name' => 'T-shirt', 'unit' => 'piece', 'units' => 1, 'gross_price' => '24.90', 'image_url' => 'https://shop.test/img/shirt.png'],
['type' => 'physical-reduced', 'name' => 'Artbook', 'unit' => 'piece', 'units' => 1, 'gross_price' => '19.95'],
],
]);
```
Once a paid order is sent, create a shipment. Anikeen ID adds its delivery note to the user's
order documents (with the tracking link), mails it to the user (`'notify_customer' => false` if
your shop sends its own mail) and sends `order.shipped` to your webhook endpoints.
Without `items`, everything physical that is left is shipped; partial deliveries name the items:
```php
$order = $user->orders()->find($orderId);
$shipment = $order->shipments()->create([
'carrier' => 'DHL',
'tracking_number' => '00340434161234567890',
'tracking_url' => 'https://www.dhl.de/…?piececode=00340434161234567890',
// 'items' => [['order_item_id' => $itemId, 'units' => 1]],
]);
$shipment->number; // LS-2026-0001
$shipment->deliveryNote(); // the delivery note as PDF
```
Only the app that created the order (or a trusted app) can ship it, and only once it is paid.
`checkout()` on such a draft throws `ConfirmationRequiredException`; its `confirmationUrl`
points to the same page. Trusted apps keep checking out directly.
### Webhooks
Anikeen ID sends `order.*`, `subscription.*` and `checkout.*` events to the webhook endpoints of your app (set up
in the Anikeen ID admin panel, which also shows the signing secret `whsec_…`). Verify each request
with the raw body and answer 2xx within 10 seconds; failed deliveries are retried for about three days.
```php
use Anikeen\Id\Exceptions\SignatureVerificationException;
use Anikeen\Id\Webhooks\EventType;
use Anikeen\Id\Webhooks\Webhook;
Route::post('webhooks/anikeen', function (Request $request) {
try {
$event = Webhook::constructEvent($request->getContent(), $request->header('Anikeen-Signature'), config('services.anikeen.webhook_secret'));
} catch (SignatureVerificationException) {
abort(400);
}
match ($event['type']) {
EventType::ORDER_COMPLETED => Shop::fulfil($event['data']['object']['id']),
EventType::SUBSCRIPTION_CANCELLED => Panel::suspend($event['data']['object']['id']),
EventType::CHECKOUT_COMPLETED => Panel::provision($event['data']['object']['subscription_ids']),
default => null,
};
return response()->noContent();
})->withoutMiddleware(VerifyCsrfToken::class);
```
Events can arrive more than once or out of order: use `$event['id']` to skip duplicates, and
reload the object through the API when the current state matters.
### Change the default access token / refresh token field name ### Change the default access token / refresh token field name
If you access / refresh token fields differs from the default `anikeen_id_access_token` / `anikeen_id_refresh_token`, you can specify the field name in the `AppServiceProvider` boot method: If you access / refresh token fields differs from the default `anikeen_id_access_token` / `anikeen_id_refresh_token`, you can specify the field name in the `AppServiceProvider` boot method:
@@ -109,17 +325,18 @@ public function boot(): void
### Implementing Auth ### Implementing Auth
This method should typically be called in the `boot` method of your `AuthServiceProvider` class: This method should typically be called in the `boot` method of your `AppServiceProvider` class:
```php ```php
use Anikeen\Id\AnikeenId; use Anikeen\Id\AnikeenId;
use Anikeen\Id\Providers\AnikeenIdSsoUserProvider; use Anikeen\Id\Providers\AnikeenIdUserProvider;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
public function boot(): void public function boot(): void
{ {
Auth::provider('sso-users', function ($app, array $config) { Auth::provider('anikeen', function ($app, array $config) {
return new AnikeenIdSsoUserProvider( return new AnikeenIdUserProvider(
$app->make(AnikeenId::class), $app->make(AnikeenId::class),
$app->make(Request::class), $app->make(Request::class),
$config['model'], $config['model'],
@@ -140,7 +357,7 @@ reference the guard in the `guards` configuration of your `auth.php` configurati
'api' => [ 'api' => [
'driver' => 'anikeen', 'driver' => 'anikeen',
'provider' => 'sso-users', 'provider' => 'anikeen',
], ],
], ],
``` ```
@@ -154,8 +371,8 @@ reference the provider in the `providers` configuration of your `auth.php` confi
'model' => App\Models\User::class, 'model' => App\Models\User::class,
], ],
'sso-users' => [ 'anikeen' => [
'driver' => 'sso-users', 'driver' => 'anikeen',
'model' => App\Models\User::class, 'model' => App\Models\User::class,
'fields' => ['first_name', 'last_name', 'email'], 'fields' => ['first_name', 'last_name', 'email'],
], ],
@@ -291,12 +508,43 @@ public function retrievingToken(string $grantType, array $attributes): Result
public function createOrderPreview(array $attributes = []): Result public function createOrderPreview(array $attributes = []): Result
``` ```
### ManagesProducts
```php
public function products(): Result
public function boxes(): Result
```
### ManagesShippingLabels
```php
public function shippingLabels(array $parameters = []): Result
public function shippingLabel(string $id): Result
public function shippingLabelPdf(string $id): ?string
public function issueShippingLabel(array $attributes): Result
public function shipShippingLabel(array $hex): Result
public function shippingPriceList(): Result
```
### ManagesUserBilling
```php
public function appOrders(): AppOrders
public function appCheckoutSessions(): AppCheckoutSessions
public function createOrderForUser(string $userId, array $attributes): Result
public function createTransactionForUser(string $userId, array $attributes): Result
```
### ManagesSocialiteUsers
```php
public function socialiteUsers(): SocialiteUsers
```
### ManagesSshKeys ### ManagesSshKeys
```php ```php
public function sshKeysByUserId(string $sskKeyId): Result public function sshKeysByUserId(string $userId): SshKeys
public function createSshKey(string $publicKey, ?string $name = null): Result
public function deleteSshKey(int $sshKeyId): Result
``` ```
### ManagesUsers ### ManagesUsers
@@ -304,7 +552,11 @@ public function deleteSshKey(int $sshKeyId): Result
```php ```php
public function getAuthedUser(): Result public function getAuthedUser(): Result
public function createUser(array $attributes): Result public function createUser(array $attributes): Result
public function findOrCreateSocialiteUser(string $provider, string $providerId, ?string $email = null, ?string $name = null): Result
public function refreshToken(string $storedRefreshToken, string $scope = ''): Result
public function isEmailExisting(string $email): Result public function isEmailExisting(string $email): Result
public function setParent(mixed $parent): self
public function getParent()
``` ```
@@ -313,11 +565,10 @@ public function isEmailExisting(string $email): Result
### ManagesAddresses ### ManagesAddresses
```php ```php
public function addresses(): Result public function addresses(): Addresses
public function createAddress(array $attributes = []): Result public function hasDefaultBillingAddress(): bool
public function address(string $addressId): Result public function setBillable(Billable|Model $billable): self
public function updateAddress(string $addressId, array $attributes = []): Result public function getBillable(): Billable
public function deleteAddress(string $addressId): Result
``` ```
### ManagesBalance ### ManagesBalance
@@ -325,69 +576,92 @@ public function deleteAddress(string $addressId): Result
```php ```php
public function balance(): float public function balance(): float
public function charges(): float public function charges(): float
public function charge(float $amount, string $paymentMethodId, array $options = []): Result public function billingOverview(): object
public function charge(string|float $amount, string $paymentMethodId, array $options = []): Transaction
public function setBillable(Billable|Model $billable): self
public function getBillable(): Billable
```
### ManagesCountries
```php
public function countries(): Countries
public function setBillable(Billable|Model $billable): self
public function getBillable(): Billable
``` ```
### ManagesInvoices ### ManagesInvoices
```php ```php
public function invoices(): Result public function invoices(array $parameters = []): Invoices
public function invoice(string $invoiceId): Result public function setBillable(Billable|Model $billable): self
public function getInvoiceTemporaryUrl(string $invoiceId): string public function getBillable(): Billable
``` ```
### ManagesOrders ### ManagesOrders
```php ```php
public function orders(): Result public function orders(array $parameters = []): Orders
public function createOrder(array $attributes = []): Result public function setBillable(Billable|Model $billable): self
public function order(string $orderId): Result public function getBillable(): Billable
public function updateOrder(string $orderId, array $attributes = []): Result
public function checkoutOrder(string $orderId): Result
public function revokeOrder(string $orderId): Result
public function deleteOrder(string $orderId): Result
public function orderItems(string $orderId): Result
public function createOrderItem(string $orderId, array $attributes = []): Result
public function orderItem(string $orderId, string $orderItemId): Result
public function updateOrderItem(string $orderId, string $orderItemId, array $attributes = []): Result
public function deleteOrderItem(string $orderId, string $orderItemId): Result
``` ```
### ManagesPaymentMethods ### ManagesPaymentMethods
```php ```php
public function hasPaymentMethod(): bool public function paymentMethods(): PaymentMethods
public function paymentMethods(): Result public function hasPaymentMethod(): ?PaymentMethod
public function defaultPaymentMethod(): ?PaymentMethod
public function hasDefaultPaymentMethod(): bool public function hasDefaultPaymentMethod(): bool
public function defaultPaymentMethod(): Result public function setDefaultPaymentMethod(string $id): PaymentMethod
public function billingPortalUrl(string $returnUrl, array $options): string public function billingPortalUrl(?string $returnUrl = null, array $options = []): string
public function createSetupIntent(array $options = []): Result public function createSetupIntent(array $options = []): Result
public function setBillable(Billable|Model $billable): self
public function getBillable(): Billable
```
### ManagesProfile
```php
public function profilePortalUrl(?string $returnUrl = null, array $options = []): string
public function setBillable(Billable|Model $billable): self
public function getBillable(): Billable
``` ```
### ManagesSubscriptions ### ManagesSubscriptions
```php ```php
public function subscriptions(): Result public function subscriptions(): Subscriptions
public function subscription(string $subscriptionId): Result public function appSubscriptions(): AppSubscriptions
public function createSubscription(array $attributes): Result public function appCheckoutSessions(): AppCheckoutSessions
public function checkoutSubscription(string $subscriptionId): Result public function checkoutSessions(): CheckoutSessions
public function revokeSubscription(string $subscriptionId): Result public function appOrders(): AppOrders
public function resumeSubscription(string $subscriptionId): Result public function setBillable(Billable|Model $billable): self
public function deleteSubscription(string $subscriptionId): Result public function getBillable(): Billable
``` ```
### ManagesTaxation ### ManagesTaxation
```php ```php
public function vat(): float public function vatRate(): float
public function setBillable(Billable|Model $billable): self
public function getBillable(): Billable
``` ```
### ManagesTransactions ### ManagesTransactions
```php ```php
public function transactions(): Result public function transactions(): Transactions
public function createTransaction(array $attributes = []): Result public function setBillable(Billable|Model $billable): self
public function transaction(string $transactionId): Result public function getBillable(): Billable
```
### ManagesUserSshKeys
```php
public function sshKeys(): SshKeys
public function setBillable(Billable|Model $billable): self
public function getBillable(): Billable
``` ```
+187 -7
View File
@@ -93,6 +93,185 @@ class User extends Authenticatable
then, you can use the `Billable` trait methods in your user model. then, you can use the `Billable` trait methods in your user model.
### App subscriptions (trusted apps, no user token)
`subscriptions()` acts with the user's own access token and stops working when the user's login
expired. Trusted apps can manage a user's subscriptions with the app's own token (client
credentials, scope `subscriptions:client`) instead:
```php
$subscriptions = $team->owner->appSubscriptions(); // nothing is requested yet
$subscription = $subscriptions->create([
'group' => $team->id,
'name' => 'Cloud Server S',
'unit' => 'hour',
'price' => 0.0137,
'idempotency_key' => "server:{$pendingServer->id}", // retries return the same subscription
]);
$subscription->checkout(); // bill the first period
$subscription->checkout(startsAt: $domain->registered_at); // already running: bill the period that started then
$subscription->pause(); // expires when the paid period ends
$subscription->resume(); // expired subscriptions start a new period
$subscription->revoke(refund: false); // cancel
$subscriptions->find($id); // null if unknown or not this user's
$subscriptions->all(['group' => $team->id, 'active' => true]);
```
The user's Anikeen ID is read from the billable's `anikeen_id` attribute
(`AnikeenId::useUserIdField('…')` to change it). The app must be trusted by Anikeen ID; it sees the
subscriptions it created (plus those of clients delegated to it).
Failures throw `Anikeen\Id\Exceptions\ApiException` with `status` (0 = not reachable), a stable
`error` code (`already_active`, `already_cancelled`, `not_active`, `already_paused`,
`already_resumed`, `billing_address_missing`, `not_changeable`, `subscription_not_found`,
`idempotency_key_conflict`) and `isNotFound()`, `isConflict()`, `isTemporary()`:
```php
try {
$subscription->revoke();
} catch (ApiException $e) {
if ($e->isNotFound() || $e->error === 'already_cancelled') {
// already gone
} elseif ($e->isTemporary()) {
// retry later
} else {
throw $e;
}
}
```
### App orders (trusted apps, no user token)
Orders that bill the app's subscriptions, read with the app's token (scope `orders:client`):
```php
$team->owner->appOrders()->pending(); // unpaid orders of one user, oldest first
app(AnikeenId::class)->appOrders()->pending(); // of all users
$team->owner->appOrders()->find($orderId); // null if unknown or not this user's
```
Each order has `status` (`processing` = current month, still collecting; `pending` = closed and not
paid; `completed`; `cancelled`), the totals, `payment_attempts`, `next_payment_attempt_at` (null =
no more automatic retries) and `last_payment_error`.
### Checkout sessions (the user confirms several subscriptions at once)
Instead of checking subscriptions out itself, an app can let the user confirm them on Anikeen ID,
all of them in one step: a checkout session bundles new subscriptions (or existing drafts of the
app, `['id' => …]`) of one user. The user sees every item with its price and the total of the first
period, confirms (all subscriptions start, or none) or cancels, and returns to `return_url`.
Open sessions expire after 24 hours with their drafts. Trusted apps can still check out directly;
sessions are opt-in.
Example: the Console's builder ("Jetzt kaufen") with several products and coupon prices:
```php
use Anikeen\Id\Exceptions\ApiException;
$session = $request->user()->appCheckoutSessions()->create([ // app token; or ->checkoutSessions() with the user's token
'return_url' => route('builder.done'), // same origin as one of your redirect URIs
'metadata' => ['cart' => $cart->id], // returned as is
'idempotency_key' => "cart:{$cart->id}", // retries return the same session
'subscriptions' => $cart->items->map(fn ($item) => [
'group' => $team->id,
'name' => $item->product->name,
'description' => $item->label,
'unit' => $item->unit, // hour, day, week, month, year
'price' => $item->priceAfterCoupon(), // net, per unit
'payload' => ['cart_item' => $item->id],
])->all(),
]);
$cart->update(['checkout_session_id' => $session->id, 'subscription_ids' => $session->subscriptionIds()]);
return redirect($session->confirmationUrl());
// later: https://console.test/builder/done?status=completed&checkout_session=01K…
```
Provision when the webhook arrives (or after checking the session through the API; never trust the
query string):
```php
use Anikeen\Id\Webhooks\EventType;
match ($event['type']) {
EventType::CHECKOUT_COMPLETED => Provisioner::provision($event['data']['object']['subscriptions']), // all running
EventType::CHECKOUT_CANCELLED, EventType::CHECKOUT_EXPIRED => Cart::release($event['data']['object']['metadata']['cart'] ?? null),
default => null,
};
app(AnikeenId::class)->appCheckoutSessions()->find($id)?->isCompleted(); // any user's session
$session->refresh()->subscriptions(); // AppSubscription objects
$session->cancel(); // withdraw an open session and its drafts (e.g. the cart changed)
```
While a session is open, its subscriptions can't be checked out or repriced by the app (409
`in_checkout_session` / `not_changeable`). The session's `status` is `open`, `completed`,
`cancelled` or `expired` (`isOpen()`, `isCompleted()`, `isCancelled()` for cancelled or expired).
`subscription.activated` / `subscription.cancelled` are still sent per subscription, before the
`checkout.*` event of the session.
### Selling as a third-party app (user confirms on Anikeen ID)
Apps that are not trusted can create orders and subscriptions for the signed-in user (user token),
but can't charge them. The user confirms on Anikeen ID and comes back to your `return_url`:
```php
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
$order = $user->orders()->create([
'billing_address_id' => $addressId,
'items' => [['type' => 'digital', 'name' => 'Sticker pack', 'unit' => 'piece', 'units' => 1, 'gross_price' => '9.99']],
]);
return redirect($order->confirmationUrl(route('shop.done')));
// later: https://your-app.test/shop/done?status=completed&order=01J…
```
`return_url` must have the origin of one of your app's redirect URIs. `status` is `completed`,
`pending` (payment still processing) or `cancelled`; check it with `$user->orders()->find($id)`
instead of trusting the query string. Subscriptions work the same way
(`$user->subscriptions()->create([...])->confirmationUrl(...)`, `&subscription=…`).
Unconfirmed bookings are cancelled after 24 hours.
`checkout()` on such a draft throws `ConfirmationRequiredException`; its `confirmationUrl`
points to the same page. Trusted apps keep checking out directly.
### Webhooks
Anikeen ID sends `order.*`, `subscription.*` and `checkout.*` events to the webhook endpoints of your app (set up
in the Anikeen ID admin panel, which also shows the signing secret `whsec_…`). Verify each request
with the raw body and answer 2xx within 10 seconds; failed deliveries are retried for about three days.
```php
use Anikeen\Id\Exceptions\SignatureVerificationException;
use Anikeen\Id\Webhooks\EventType;
use Anikeen\Id\Webhooks\Webhook;
Route::post('webhooks/anikeen', function (Request $request) {
try {
$event = Webhook::constructEvent($request->getContent(), $request->header('Anikeen-Signature'), config('services.anikeen.webhook_secret'));
} catch (SignatureVerificationException) {
abort(400);
}
match ($event['type']) {
EventType::ORDER_COMPLETED => Shop::fulfil($event['data']['object']['id']),
EventType::SUBSCRIPTION_CANCELLED => Panel::suspend($event['data']['object']['id']),
EventType::CHECKOUT_COMPLETED => Panel::provision($event['data']['object']['subscription_ids']),
default => null,
};
return response()->noContent();
})->withoutMiddleware(VerifyCsrfToken::class);
```
Events can arrive more than once or out of order: use `$event['id']` to skip duplicates, and
reload the object through the API when the current state matters.
### Change the default access token / refresh token field name ### Change the default access token / refresh token field name
If you access / refresh token fields differs from the default `anikeen_id_access_token` / `anikeen_id_refresh_token`, you can specify the field name in the `AppServiceProvider` boot method: If you access / refresh token fields differs from the default `anikeen_id_access_token` / `anikeen_id_refresh_token`, you can specify the field name in the `AppServiceProvider` boot method:
@@ -109,17 +288,18 @@ public function boot(): void
### Implementing Auth ### Implementing Auth
This method should typically be called in the `boot` method of your `AuthServiceProvider` class: This method should typically be called in the `boot` method of your `AppServiceProvider` class:
```php ```php
use Anikeen\Id\AnikeenId; use Anikeen\Id\AnikeenId;
use Anikeen\Id\Providers\AnikeenIdSsoUserProvider; use Anikeen\Id\Providers\AnikeenIdUserProvider;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
public function boot(): void public function boot(): void
{ {
Auth::provider('sso-users', function ($app, array $config) { Auth::provider('anikeen', function ($app, array $config) {
return new AnikeenIdSsoUserProvider( return new AnikeenIdUserProvider(
$app->make(AnikeenId::class), $app->make(AnikeenId::class),
$app->make(Request::class), $app->make(Request::class),
$config['model'], $config['model'],
@@ -140,7 +320,7 @@ reference the guard in the `guards` configuration of your `auth.php` configurati
'api' => [ 'api' => [
'driver' => 'anikeen', 'driver' => 'anikeen',
'provider' => 'sso-users', 'provider' => 'anikeen',
], ],
], ],
``` ```
@@ -154,8 +334,8 @@ reference the provider in the `providers` configuration of your `auth.php` confi
'model' => App\Models\User::class, 'model' => App\Models\User::class,
], ],
'sso-users' => [ 'anikeen' => [
'driver' => 'sso-users', 'driver' => 'anikeen',
'model' => App\Models\User::class, 'model' => App\Models\User::class,
'fields' => ['first_name', 'last_name', 'email'], 'fields' => ['first_name', 'last_name', 'email'],
], ],
+12 -10
View File
@@ -1,28 +1,30 @@
{ {
"name": "anikeen/id", "name": "anikeen/id",
"description": "PHP AnikeenId API Client for Laravel 10+", "description": "PHP Anikeen ID API client for Laravel 11+",
"license": "MIT", "license": "MIT",
"authors": [ "authors": [
{ {
"name": "René Preuß", "name": "Ren\u00e9 Preu\u00df",
"email": "rene@anikeen.com" "email": "rene@anikeen.com"
}, },
{ {
"name": "Maurice Preuß", "name": "Maurice Preu\u00df",
"email": "maurice@anikeen.com" "email": "maurice@anikeen.com"
} }
], ],
"require": { "require": {
"php": "^8.1", "php": "^8.2",
"ext-json": "*", "ext-json": "*",
"illuminate/support": "^11.0|^12.0", "illuminate/support": "^11.0|^12.0|^13.0",
"illuminate/console": "^11.0|^12.0", "illuminate/console": "^11.0|^12.0|^13.0",
"guzzlehttp/guzzle": "^6.3|^7.0", "guzzlehttp/guzzle": "^7.8",
"socialiteproviders/manager": "^3.4|^4.0.1", "socialiteproviders/manager": "^4.6",
"firebase/php-jwt": "^6.0" "firebase/php-jwt": "^6.10|^7.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^8.0|^9.0" "laravel/framework": "^11.0|^12.0|^13.0",
"orchestra/testbench": "^9.0|^10.0|^11.0",
"phpunit/phpunit": "^11.0|^12.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
+16 -8
View File
@@ -7,6 +7,20 @@ use Anikeen\Id\Billable;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Str; use Illuminate\Support\Str;
// short type name incl. union, intersection and nullable types
function typeName(ReflectionType $type): string
{
if ($type instanceof ReflectionUnionType || $type instanceof ReflectionIntersectionType) {
$separator = $type instanceof ReflectionUnionType ? '|' : '&';
return collect($type->getTypes())->map(fn (ReflectionType $t) => typeName($t))->implode($separator);
}
$name = Arr::last(explode('\\', $type->getName()));
return ($type->allowsNull() && !in_array($name, ['mixed', 'null'], true) ? '?' : '') . $name;
}
// Liste der Klassen, die ausgewertet werden sollen // Liste der Klassen, die ausgewertet werden sollen
$classes = [ $classes = [
AnikeenId::class, AnikeenId::class,
@@ -51,10 +65,7 @@ $allMarkdown = collect($classes)
// Typ-Hint // Typ-Hint
$typeHint = ''; $typeHint = '';
if ($p->hasType()) { if ($p->hasType()) {
$type = $p->getType(); $typeHint = typeName($p->getType()) . ' ';
$nullable = $type->allowsNull() ? '?' : '';
$name = Arr::last(explode('\\', $type->getName()));
$typeHint = $nullable . $name . ' ';
} }
// Parameter-Name // Parameter-Name
@@ -84,10 +95,7 @@ $allMarkdown = collect($classes)
// Rückgabetyp, falls vorhanden // Rückgabetyp, falls vorhanden
if ($method->hasReturnType()) { if ($method->hasReturnType()) {
$retType = $method->getReturnType(); $decl .= ': ' . typeName($method->getReturnType());
$nullable = $retType->allowsNull() ? '?' : '';
$typeName = Arr::last(explode('\\', $retType->getName()));
$decl .= ': ' . $nullable . $typeName;
} }
return $decl; return $decl;
+14
View File
@@ -0,0 +1,14 @@
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAi4Ta8r01zKaGSnGi1EiD
uMFWRXBlK4y/ZIfWBpElmS2ygv4mGeP3hT4Flm696Z2UMy56KC+c7CC/PQCiutLk
5NUphyX/t+0QS5Dqpw6FB33fLTNNY7GqSmGIUE4os8XYZRSyDQRgtOgq3R3vJkoV
7zoavTJmSCQlG5Qf0T//iMmzQ+b+6VZm1CJSz5nGx94u1DuXNyP5Epkk0wuHrtwy
kADR2lmydNodJzqpSD+8yQqnAhOZNtNF4qwQ3g13fRvHycBp3G2nlCfOn2g5PmYD
KYBKqvTq4PQH4E+K3pbbMz6zf/T6Dw7zTfksqHR4hqMgN6byRRxmwuBczIumcu9b
y7xbgoIGIVZXgJliALPFi+zTPTN7c8MedFs/xCBHCmzWYTCZfHgr8RPRewD19tCG
NSny5R0vlArpuZCTTgedPESDeGU4eNEddg4yXFzKlpE2nNuvzZ1Ohruc5ETOSU19
RTCBUBkjeL6ESZRd/yKGjbVx4dEYxZdIz4yBl+hZ2ZOIyG7L3zPrccAWrPpG56xr
E5IDBXxLFhaJ5LlyEAGQehB0ShEuCdkr88Xz7ba9PHpGqY83l4//ULrqPIZPAa4Z
E3AWHT1ZtXNPeA4SzZ9Y9Oij4M3chyHxqM0lL3kYP+dstZehTujStfElDIx2Ni10
73tILu4edYS0FxsL19m8gbsCAwEAAQ==
-----END PUBLIC KEY-----
+8 -21
View File
@@ -1,29 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
backupGlobals="false" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
backupStaticAttributes="false" bootstrap="vendor/autoload.php"
colors="true" colors="true">
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
printerClass="\Codedungeon\PHPUnitPrettyResultPrinter\Printer">
<testsuites> <testsuites>
<testsuite name="Unit"> <testsuite name="Unit">
<directory>tests</directory> <directory>tests</directory>
</testsuite> </testsuite>
</testsuites> </testsuites>
<filter> <source>
<whitelist processUncoveredFilesFromWhitelist="true"> <include>
<directory suffix=".php">src</directory> <directory suffix=".php">src</directory>
</whitelist> </include>
</filter> </source>
<php>
<env name="ANIKEEN_ID_KEY" value="38"/>
<env name="ANIKEEN_ID_SECRET" value="2goNRF8x37HPVZVaa28ySZGVXJuksvxnxM7TcGzM"/>
<env name="ANIKEEN_ID_BASE_URL" value="https://id.anikeen.com/api/"/>
<env name="CLIENT_ACCESS_TOKEN" value="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxNSIsImp0aSI6IjAxN2QxZDg0Y2MxNjAyZTYxOGZkNjYwZGViZWVjMDY4MTk2YmYzMDk1OGMzY2RiYzBjZmJkZWFjZjFhOTUxODQzZDU1YTk3OGY2YWIxY2YzIiwiaWF0IjoxNjY0NjIzMzA4LjQyODI4MSwibmJmIjoxNjY0NjIzMzA4LjQyODI4NCwiZXhwIjoxNjgwMzQ4MTA4LjQxNjc4MSwic3ViIjoiMzkiLCJzY29wZXMiOlsiYXBpIiwicmVhZF91c2VyIl0sImNsaWVudCI6eyJ0cnVzdGVkIjpmYWxzZX19.vxnzCaU4PpOrNVHa5AnGSS6gX_RCvxIERAnHFhjTrUzRafV9mr2Cvwd-BDVYoUr10wHvxa_TJSYfnAdDuhE-MEyDv13O3dL2XGTtJNa_Rg6L6CQ0JvC3wL-lWPvGPFax9pu-_lqbA3jm5B08hc3-7tq3f2nXcxjhtkqT6TTJv1-RCAppb2HCXiUDAqANzbhyInDjOH2WvFj1OGC_AI03J3W2KRWyeFLtUne8XKPFyr9XGcPuTrqogcuuXLeUt2kcf2bXbuIV1OlgIECrDiP1Ee0F2AzPs27ZVJ2z0R0JbT6AubKhGl5_Qi27cwjOH7hT2dmjcF1mLjzpN1uChLIdSnGSoStH8VzYHnHE2I8G-owW_aadG2UmGdnRY143q6g_28f3WIZNSucBSXkwFeS_t4fylsvpxhpjYJusf5qiEU_X3YbeawYMUCFUkSD2XTIypAqMJLNZQAeJ52eyL-9fln-Bv7n9v7K9G6ieR6Tm0tsJ1PRnaQi7rA1NTFwHoQmIOW9tfMycLzT7bgSoz3ra6Ez2J7ZNuWBZNKS0O-0YfSrAWyWK5U8YRfQuSVzP2VrIU63K6RGU2c284PfQGy11kgKUNQPykirb8p7MDQ8PwrxKaylBnD6hhDgjqEh2bfsr_43DfJA0R58L1HK3BmQnxgap0C77wK1e0yNlABpN28Q"/>
</php>
</phpunit> </phpunit>
+76 -25
View File
@@ -3,7 +3,11 @@
namespace Anikeen\Id; namespace Anikeen\Id;
use Anikeen\Id\Concerns\ManagesPricing; use Anikeen\Id\Concerns\ManagesPricing;
use Anikeen\Id\Concerns\ManagesProducts;
use Anikeen\Id\Concerns\ManagesShippingLabels;
use Anikeen\Id\Concerns\ManagesSocialiteUsers;
use Anikeen\Id\Concerns\ManagesSshKeys; use Anikeen\Id\Concerns\ManagesSshKeys;
use Anikeen\Id\Concerns\ManagesUserBilling;
use Anikeen\Id\Concerns\ManagesUsers; use Anikeen\Id\Concerns\ManagesUsers;
use Anikeen\Id\Exceptions\RequestRequiresAuthenticationException; use Anikeen\Id\Exceptions\RequestRequiresAuthenticationException;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
@@ -20,6 +24,10 @@ class AnikeenId
{ {
use OauthTrait; use OauthTrait;
use ManagesPricing; use ManagesPricing;
use ManagesProducts;
use ManagesShippingLabels;
use ManagesUserBilling;
use ManagesSocialiteUsers;
use ManagesSshKeys; use ManagesSshKeys;
use ManagesUsers; use ManagesUsers;
@@ -46,16 +54,6 @@ class AnikeenId
*/ */
public static bool $unserializesCookies = false; public static bool $unserializesCookies = false;
/**
* The base URL for Anikeen ID API.
*/
private static string $baseUrl = 'https://id.anikeen.com/api/';
/**
* The staging base URL for Anikeen ID API.
*/
private static string $stagingBaseUrl = 'https://staging.id.anikeen.com/api/';
/** /**
* The key for the access token. * The key for the access token.
*/ */
@@ -66,6 +64,8 @@ class AnikeenId
*/ */
private static string $refreshTokenField = 'anikeen_id_refresh_token'; private static string $refreshTokenField = 'anikeen_id_refresh_token';
private static string $userIdField = 'anikeen_id';
/** /**
* Guzzle is used to make http requests. * Guzzle is used to make http requests.
*/ */
@@ -96,6 +96,16 @@ class AnikeenId
*/ */
protected ?string $redirectUri = null; protected ?string $redirectUri = null;
/**
* The base URL for Anikeen ID.
*/
protected string $baseUrl = 'https://id.anikeen.com';
/**
* The staging base URL for Anikeen ID.
*/
protected string $stagingBaseUrl = 'https://staging.id.anikeen.com';
/** /**
* Constructor. * Constructor.
*/ */
@@ -110,25 +120,25 @@ class AnikeenId
if ($redirectUri = config('services.anikeen.redirect')) { if ($redirectUri = config('services.anikeen.redirect')) {
$this->setRedirectUri($redirectUri); $this->setRedirectUri($redirectUri);
} }
if (config('services.anikeen.mode') === 'staging') { if (self::getMode() === 'staging' && !config('services.anikeen.base_url')) {
self::setBaseUrl(self::$stagingBaseUrl); self::setBaseUrl($this->stagingBaseUrl);
} }
if ($baseUrl = config('services.anikeen.base_url')) { if ($baseUrl = config('services.anikeen.base_url')) {
self::setBaseUrl($baseUrl); self::setBaseUrl($baseUrl);
} }
$this->client = new Client([ $this->client = new Client([
'base_uri' => self::$baseUrl, 'base_uri' => $this->baseUrl . '/api/',
]); ]);
} }
/** protected function setBaseUrl(string $baseUrl): void
* @param string $baseUrl
*
* @internal only for internal and debug purposes.
*/
public static function setBaseUrl(string $baseUrl): void
{ {
self::$baseUrl = $baseUrl; $this->baseUrl = $baseUrl;
}
public function getBaseUrl(): string
{
return rtrim($this->baseUrl, '/');
} }
public static function useAccessTokenField(string $accessTokenField): void public static function useAccessTokenField(string $accessTokenField): void
@@ -141,6 +151,46 @@ class AnikeenId
return self::$accessTokenField; return self::$accessTokenField;
} }
/**
* Attribute of the billable model that holds the user's Anikeen ID (used by app requests,
* e.g. appSubscriptions(), which act on behalf of a user without the user's token).
*/
public static function useUserIdField(string $userIdField): void
{
self::$userIdField = $userIdField;
}
public static function getUserIdField(): string
{
return self::$userIdField;
}
/**
* A copy that uses the app's own access token (client credentials) instead of a user's token.
* The shared instance keeps its token, so app rights never leak into other requests.
*
* @throws Exceptions\RequestFreshAccessTokenException
*/
public function asApp(): static
{
return (clone $this)->withToken(app(Contracts\AppTokenRepository::class)->getAccessToken());
}
/**
* Replace the HTTP client, e.g. with one using a Guzzle MockHandler in tests.
*/
public function setHttpClient(Client $client): static
{
$this->client = $client;
return $this;
}
public static function getMode(): string
{
return config('services.anikeen.mode') ?: 'production';
}
public static function useRefreshTokenField(string $refreshTokenField): void public static function useRefreshTokenField(string $refreshTokenField): void
{ {
self::$refreshTokenField = $refreshTokenField; self::$refreshTokenField = $refreshTokenField;
@@ -322,7 +372,7 @@ class AnikeenId
* @throws GuzzleException * @throws GuzzleException
* @throws RequestRequiresClientIdException * @throws RequestRequiresClientIdException
*/ */
public function request(string $method, string $path, null|array $payload = null, array $parameters = [], ?Paginator $paginator = null): Result public function request(string $method, string $path, null|array $payload = null, array $parameters = [], ?Paginator $paginator = null, bool $useClientSecret = false): Result
{ {
if ($paginator !== null) { if ($paginator !== null) {
$parameters[$paginator->action] = $paginator->cursor(); $parameters[$paginator->action] = $paginator->cursor();
@@ -330,7 +380,7 @@ class AnikeenId
try { try {
$response = $this->client->request($method, $path, [ $response = $this->client->request($method, $path, [
'headers' => $this->buildHeaders((bool)$payload), 'headers' => $this->buildHeaders((bool)$payload, $useClientSecret),
'query' => Query::build($parameters), 'query' => Query::build($parameters),
'json' => $payload ?: null, 'json' => $payload ?: null,
]); ]);
@@ -348,14 +398,15 @@ class AnikeenId
* *
* @throws RequestRequiresClientIdException * @throws RequestRequiresClientIdException
*/ */
private function buildHeaders(bool $json = false): array private function buildHeaders(bool $json = false, bool $useClientSecret = false): array
{ {
$headers = [ $headers = [
'Client-ID' => $this->getClientId(), 'Client-ID' => $this->getClientId(),
'Accept' => 'application/json', 'Accept' => 'application/json',
]; ];
if ($this->token) { // public endpoints (products, order preview, …) work without a token
$headers['Authorization'] = 'Bearer ' . $this->token; if ($bearerToken = $useClientSecret ? $this->getClientSecret() : $this->token) {
$headers['Authorization'] = 'Bearer ' . $bearerToken;
} }
if ($json) { if ($json) {
$headers['Content-Type'] = 'application/json'; $headers['Content-Type'] = 'application/json';
+26 -21
View File
@@ -2,7 +2,6 @@
namespace Anikeen\Id; namespace Anikeen\Id;
use Anikeen\Id\ApiOperations\Request;
use Anikeen\Id\Concerns\ManagesAddresses; use Anikeen\Id\Concerns\ManagesAddresses;
use Anikeen\Id\Concerns\ManagesBalance; use Anikeen\Id\Concerns\ManagesBalance;
use Anikeen\Id\Concerns\ManagesCountries; use Anikeen\Id\Concerns\ManagesCountries;
@@ -13,10 +12,8 @@ use Anikeen\Id\Concerns\ManagesProfile;
use Anikeen\Id\Concerns\ManagesSubscriptions; use Anikeen\Id\Concerns\ManagesSubscriptions;
use Anikeen\Id\Concerns\ManagesTaxation; use Anikeen\Id\Concerns\ManagesTaxation;
use Anikeen\Id\Concerns\ManagesTransactions; use Anikeen\Id\Concerns\ManagesTransactions;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Anikeen\Id\Concerns\ManagesUserSshKeys;
use Anikeen\Id\Helpers\Paginator; use Throwable;
use GuzzleHttp\Exception\GuzzleException;
use stdClass;
trait Billable trait Billable
{ {
@@ -30,35 +27,43 @@ trait Billable
use ManagesSubscriptions; use ManagesSubscriptions;
use ManagesTaxation; use ManagesTaxation;
use ManagesTransactions; use ManagesTransactions;
use Request; use ManagesUserSshKeys;
protected stdClass|null $userData = null; /*
* API results cached per instance. Declared, so Eloquent models don't take them for
* attributes (an undeclared property goes through Model::__set and save() then fails
* with "no such column").
*/
protected mixed $addressesCache = null;
protected mixed $countriesCache = null;
protected mixed $defaultPaymentMethodCache = null;
protected mixed $invoicesCache = null;
protected mixed $ordersCache = null;
protected mixed $paymentMethodsCache = null;
protected mixed $subscriptionsCache = null;
protected mixed $transactionsCache = null;
protected mixed $userDataCache = null;
/** /**
* Get the currently authenticated user. * Get the currently authenticated user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function getUserData(): stdClass public function getUserData(): object
{ {
if (!$this->userData) { if (!isset($this->userDataCache)) {
$this->userData = $this->request('GET', 'v1/user')->data; $this->userDataCache = $this->anikeenId()->request('GET', 'v1/user')->data;
} }
return $this->userData; return $this->userDataCache;
} }
/** /**
* Make a request to the Anikeen API. * Get the AnikeenId class.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function request(string $method, string $path, null|array $payload = null, array $parameters = [], ?Paginator $paginator = null): Result public function anikeenId(): AnikeenId
{ {
$anikeenId = new AnikeenId(); return app(AnikeenId::class)->withToken($this->{AnikeenId::getAccessTokenField()});
$anikeenId->withToken($this->{AnikeenId::getAccessTokenField()});
return $anikeenId->request($method, $path, $payload, $parameters, $paginator);
} }
} }
+6 -3
View File
@@ -2,18 +2,21 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\Contracts\Billable;
use Illuminate\Database\Eloquent\Model;
trait HasBillable trait HasBillable
{ {
public mixed $billable; public Billable|Model $billable;
public function setBillable(mixed $billable): self public function setBillable(Billable|Model $billable): self
{ {
$this->billable = $billable; $this->billable = $billable;
return $this; return $this;
} }
public function getBillable(): mixed public function getBillable(): Billable
{ {
return $this->billable; return $this->billable;
} }
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Anikeen\Id\Concerns;
/**
* Orders and subscriptions created by third-party apps are confirmed by the user on Anikeen ID.
*/
trait HasConfirmationUrl
{
/**
* Where the user confirms (or cancels) this booking, or null once it was checked out.
*
* Afterwards the user is sent back to $returnUrl with `status` (completed, pending or
* cancelled) and `order` or `subscription`. The return URL must have the origin of one of
* the app's redirect URIs. Check the status through the API; don't trust the query string.
*/
public function confirmationUrl(?string $returnUrl = null): ?string
{
$url = $this->confirmation_url ?? null;
if (!$url || !$returnUrl) {
return $url ?: null;
}
return $url . (str_contains($url, '?') ? '&' : '?') . http_build_query(['return_url' => $returnUrl]);
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace Anikeen\Id\Concerns;
/**
* Reading a checkout session (see AppCheckoutSession and CheckoutSession).
*/
trait IsCheckoutSession
{
/**
* Where the user confirms (or cancels) all of the session's subscriptions, or null once the
* session is no longer open. The user then returns to the session's `return_url` with
* `status` (completed or cancelled when confirming or cancelling; expired only from the
* "back to app" link of a session that had expired) and `checkout_session` (the id). Check the
* status through the API or the checkout.* webhooks; don't trust the query string.
*/
public function confirmationUrl(): ?string
{
return $this->confirmation_url ?: null;
}
public function isOpen(): bool
{
return $this->status === self::STATUS_OPEN;
}
/**
* Confirmed: all of its subscriptions are running.
*/
public function isCompleted(): bool
{
return $this->status === self::STATUS_COMPLETED;
}
/**
* Cancelled or expired: all of its drafts were cancelled.
*/
public function isCancelled(): bool
{
return in_array($this->status, [self::STATUS_CANCELLED, self::STATUS_EXPIRED], true);
}
/**
* @return list<string>
*/
public function subscriptionIds(): array
{
return array_values((array) ($this->subscription_ids ?? []));
}
}
-39
View File
@@ -1,39 +0,0 @@
<?php
namespace Anikeen\Id\Concerns;
use stdClass;
trait MagicProperties
{
protected function setMagicProperties(stdClass|array $data): void
{
foreach ((object)$data as $key => $value) {
if (!property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
/**
* Magic getter: return null for undefined properties
*
* @param string $name
* @return mixed|null
*/
public function __get(string $name)
{
return null;
}
/**
* Magic isset: return false for undefined properties
*
* @param string $name
* @return bool
*/
public function __isset(string $name): bool
{
return false;
}
}
+21 -8
View File
@@ -2,24 +2,37 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\Addresses; use Anikeen\Id\Resources\Addresses;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesAddresses trait ManagesAddresses
{ {
use Request; use HasBillable;
/** /**
* Get addresses from the current user. * Get addresses from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function addresses(): Addresses public function addresses(): Addresses
{ {
return (new Addresses($this->request('GET', 'v1/addresses'))) if (!isset($this->addressesCache)) {
->setBillable($this); $this->addressesCache = Addresses::builder(fn() => $this->anikeenId()
->request('GET', 'v1/addresses'))
->setBillable($this);
}
return $this->addressesCache;
}
/**
* Check if the current user has a default billing address.
*
* @throws Throwable
* @see \Anikeen\Id\Resources\Addresses::hasDefaultBillingAddress()
*/
public function hasDefaultBillingAddress(): bool
{
return $this->addresses()->hasDefaultBillingAddress();
} }
} }
+27 -21
View File
@@ -2,21 +2,17 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\Transaction; use Anikeen\Id\Resources\Transaction;
use Anikeen\Id\Result; use Throwable;
use GuzzleHttp\Exception\GuzzleException;
trait ManagesBalance trait ManagesBalance
{ {
use Request; use HasBillable;
/** /**
* Get balance from the current user. * Get balance from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function balance(): float public function balance(): float
{ {
@@ -26,8 +22,7 @@ trait ManagesBalance
/** /**
* Get charges from the current user. * Get charges from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function charges(): float public function charges(): float
{ {
@@ -35,20 +30,31 @@ trait ManagesBalance
} }
/** /**
* Charge given amount from bank to current user. * Billing overview of the current user: current_balance, current_charges, vat_rate,
* has_billing_address, has_default_payment_method, open_orders.
* *
* @param float $amount Amount to charge in euros. * @throws Throwable
* @param string $paymentMethodId Payment method ID.
* @param array $options Additional options for the charge.
* @throws RequestRequiresClientIdException
* @throws GuzzleException
*/ */
public function charge(float $amount, string $paymentMethodId, array $options = []): Transaction public function billingOverview(): object
{ {
return new Transaction($this->request('POST', 'billing/charge', [ return $this->anikeenId()->request('GET', 'v1/billing')->data;
'amount' => $amount, }
'payment_method_id' => $paymentMethodId,
'options' => $options, /**
])); * Charge given amount (deposit) from one of the current user's payment methods.
*
* @param float|string $amount Amount in euros (0.50 to 10,000, at most 2 decimals).
* @param string $paymentMethodId Stripe payment method ID (pm_…).
* @param array $options Ignored; Stripe options can no longer be passed through.
* @throws Throwable
*/
public function charge(float|string $amount, string $paymentMethodId, array $options = []): Transaction
{
return (new Transaction(fn() => $this->anikeenId()
->request('POST', 'v1/billing/charge', [
'amount' => $amount,
'payment_method_id' => $paymentMethodId,
])))
->setBillable($this);
} }
}␍ }␍
+10 -8
View File
@@ -2,24 +2,26 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\Countries; use Anikeen\Id\Resources\Countries;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesCountries trait ManagesCountries
{ {
use Request; use HasBillable;
/** /**
* Get available countries for the current user. * Get available countries for the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function countries(): Countries public function countries(): Countries
{ {
return (new Countries($this->request('GET', 'v1/countries'))) if (!isset($this->countriesCache)) {
->setBillable($this); $this->countriesCache = Countries::builder(fn() => $this->anikeenId()
->request('GET', 'v1/countries'))
->setBillable($this);
}
return $this->countriesCache;
} }
} }
+10 -8
View File
@@ -2,24 +2,26 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\Invoices; use Anikeen\Id\Resources\Invoices;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesInvoices trait ManagesInvoices
{ {
use Request; use HasBillable;
/** /**
* Get invoices from the current user. * Get invoices from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function invoices(array $parameters = []): Invoices public function invoices(array $parameters = []): Invoices
{ {
return (new Invoices($this->request('GET', 'v1/invoices', [], $parameters))) if (!isset($this->invoicesCache)) {
->setBillable($this); $this->invoicesCache = Invoices::builder(fn() => $this->anikeenId()
->request('GET', 'v1/invoices', [], $parameters))
->setBillable($this);
}
return $this->invoicesCache;
} }
} }
+10 -9
View File
@@ -2,25 +2,26 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\Orders; use Anikeen\Id\Resources\Orders;
use Anikeen\Id\Result; use Throwable;
use GuzzleHttp\Exception\GuzzleException;
trait ManagesOrders trait ManagesOrders
{ {
use Request; use HasBillable;
/** /**
* Get orders from the current user. * Get orders from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function orders(array $parameters = []): Orders public function orders(array $parameters = []): Orders
{ {
return (new Orders($this->request('GET', 'v1/orders', [], $parameters))) if (!isset($this->ordersCache)) {
->setBillable($this); $this->ordersCache = Orders::builder(fn() => $this->anikeenId()
->request('GET', 'v1/orders', [], $parameters))
->setBillable($this);
}
return $this->ordersCache;
} }
} }
+70 -19
View File
@@ -2,26 +2,75 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request; use Anikeen\Id\Resources\PaymentMethod;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\PaymentMethods; use Anikeen\Id\Resources\PaymentMethods;
use Anikeen\Id\Result; use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesPaymentMethods trait ManagesPaymentMethods
{ {
use Request; use HasBillable;
/** /**
* Get payment methods from the current user. * Get payment methods from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function paymentMethods(): PaymentMethods public function paymentMethods(): PaymentMethods
{ {
return (new PaymentMethods($this->request('GET', 'v1/payment-methods'))) if (!isset($this->paymentMethodsCache)) {
->setBillable($this); $this->paymentMethodsCache = PaymentMethods::builder(fn() => $this->anikeenId()
->request('GET', 'v1/payment-methods'))
->setBillable($this);
}
return $this->paymentMethodsCache;
}
/**
* Check if current user has at least one payment method.
*
* @throws Throwable
* @see \Anikeen\Id\Resources\PaymentMethods::hasPaymentMethod()
*/
public function hasPaymentMethod(): ?PaymentMethod
{
return $this->paymentMethods()->hasPaymentMethod();
}
/**
* Get default payment method from the current user.
*
* @throws Throwable
* @see \Anikeen\Id\Resources\PaymentMethods::defaultPaymentMethod()
*/
public function defaultPaymentMethod(): ?PaymentMethod
{
return $this->paymentMethods()->defaultPaymentMethod();
}
/**
* Check if the current user has a default payment method.
*
* @throws Throwable
* @see \Anikeen\Id\Resources\PaymentMethods::hasDefaultPaymentMethod()
*/
public function hasDefaultPaymentMethod(): bool
{
return $this->paymentMethods()->hasDefaultPaymentMethod();
}
/**
* Set the default payment method for the current user.
*
* @throws Throwable
* @see \Anikeen\Id\Resources\PaymentMethods::setDefault()
*/
public function setDefaultPaymentMethod(string $id): PaymentMethod
{
unset($this->paymentMethodsCache);
return $this->paymentMethods()->setDefault($id);
} }
/** /**
@@ -29,28 +78,30 @@ trait ManagesPaymentMethods
* *
* @param string|null $returnUrl The URL to redirect to after the user has finished in the billing portal. * @param string|null $returnUrl The URL to redirect to after the user has finished in the billing portal.
* @param array $options Additional options for the billing portal. * @param array $options Additional options for the billing portal.
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function billingPortalUrl(?string $returnUrl = null, array $options = []): string public function billingPortalUrl(?string $returnUrl = null, array $options = []): string
{ {
return $this->request('POST', 'v1/billing/portal', [ return $this->anikeenId()
'return_url' => $returnUrl, ->request('POST', 'v1/billing/portal', [
'options' => $options, 'return_url' => $returnUrl,
])->data->url; 'options' => $options,
])
->data
->url;
} }
/** /**
* Create a new setup intent. * Create a new setup intent.
* *
* @param array $options Additional options for the setup intent. * @param array $options Additional options for the setup intent.
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function createSetupIntent(array $options = []): Result public function createSetupIntent(array $options = []): Result
{ {
return $this->request('POST', 'v1/payment-methods', [ return $this->anikeenId()
'options' => $options, ->request('POST', 'v1/payment-methods', [
]); 'options' => $options,
]);
} }
} }
+8 -4
View File
@@ -3,9 +3,8 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Post; use Anikeen\Id\ApiOperations\Post;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Result; use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesPricing trait ManagesPricing
{ {
@@ -29,11 +28,16 @@ trait ManagesPricing
* } $attributes The order data: * } $attributes The order data:
* - country_iso: ISO 3166-1 alpha-2 country code * - country_iso: ISO 3166-1 alpha-2 country code
* - items: Array of order items (each with type, name, price, unit, units, and quantity) * - items: Array of order items (each with type, name, price, unit, units, and quantity)
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function createOrderPreview(array $attributes = []): Result public function createOrderPreview(array $attributes = []): Result
{ {
// the API expects the country as part of the billing address
if (isset($attributes['country_iso']) && !isset($attributes['billing_address'])) {
$attributes['billing_address'] = ['country_iso' => $attributes['country_iso']];
unset($attributes['country_iso']);
}
return $this->post('v1/orders/preview', $attributes); return $this->post('v1/orders/preview', $attributes);
} }
}␍ }␍
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace Anikeen\Id\Concerns;
use Anikeen\Id\Result;
use Throwable;
trait ManagesProducts
{
/**
* Public product catalogue.
*
* @throws Throwable
*/
public function products(): Result
{
return $this->request('GET', 'v1/products');
}
/**
* Shipping boxes (for shipping labels).
*
* @throws Throwable
*/
public function boxes(): Result
{
return $this->request('GET', 'v1/boxes');
}
}
+4 -8
View File
@@ -2,14 +2,11 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request; use Throwable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
trait ManagesProfile trait ManagesProfile
{ {
use Request; use HasBillable;
/** /**
* Get the profile url for the current user. * Get the profile url for the current user.
@@ -17,12 +14,11 @@ trait ManagesProfile
* @param string|null $returnUrl The URL to redirect to after the user has completed their profile. * @param string|null $returnUrl The URL to redirect to after the user has completed their profile.
* @param array $options Additional options for the profile URL. * @param array $options Additional options for the profile URL.
* @return string * @return string
* @throws GuzzleException * @throws Throwable
* @throws RequestRequiresClientIdException
*/ */
public function profilePortalUrl(?string $returnUrl = null, array $options = []): string public function profilePortalUrl(?string $returnUrl = null, array $options = []): string
{ {
return $this->request('POST', 'v1/user/profile', [ return $this->anikeenId()->request('POST', 'v1/user/profile', [
'return_url' => $returnUrl, 'return_url' => $returnUrl,
'options' => $options, 'options' => $options,
])->data->url; ])->data->url;
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace Anikeen\Id\Concerns;
use Anikeen\Id\Result;
use Throwable;
/**
* Shipping labels (Deutsche Post Internetmarke). Trusted apps only, sent with the app's token.
*/
trait ManagesShippingLabels
{
/**
* Latest shipping labels (100 per page).
*
* @throws Throwable
*/
public function shippingLabels(array $parameters = []): Result
{
return $this->asApp()->request('GET', 'v1/admin/shipping-labels', null, $parameters);
}
/**
* @throws Throwable
*/
public function shippingLabel(string $id): Result
{
return $this->asApp()->request('GET', sprintf('v1/admin/shipping-labels/%s', $id));
}
/**
* The label as PDF (binary string), null if there is none.
*
* @throws Throwable
*/
public function shippingLabelPdf(string $id): ?string
{
$result = $this->asApp()->request('GET', sprintf('v1/admin/shipping-labels/%s/pdf', $id));
return $result->success() ? (string) $result->response()->getBody() : null;
}
/**
* Buy a shipping label; the postage is billed to the given user.
*
* @param array{
* box: array,
* weight: int,
* address: array,
* billed_user_id: string,
* test?: bool
* } $attributes
* - box: barcode, id, common_name or size of the box
* - weight: in grams
* - address: recipient address
* - billed_user_id: Anikeen ID of the user who pays the postage
* - test: validate only, no real label is bought
* @throws Throwable
*/
public function issueShippingLabel(array $attributes): Result
{
return $this->asApp()->request('POST', 'v1/admin/shipping-labels/issue', $attributes);
}
/**
* Mark the label with the scanned matrix code as shipped.
*
* @param list<string> $hex Hex bytes of the scanned Internetmarke matrix code
* @throws Throwable
*/
public function shipShippingLabel(array $hex): Result
{
return $this->asApp()->request('POST', 'v1/admin/shipping-labels/ship', ['hex' => $hex]);
}
/**
* Prices of the available franking types.
*
* @throws Throwable
*/
public function shippingPriceList(): Result
{
return $this->asApp()->request('GET', 'v1/admin/shipping-labels/price-list');
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Get;
use Anikeen\Id\Resources\SocialiteUsers;
use Throwable;
trait ManagesSocialiteUsers
{
use Get;
/**
* Get all socialite connections for the authenticated user.
*
* @throws Throwable
*/
public function socialiteUsers(): SocialiteUsers
{
return SocialiteUsers::builder(fn() => $this->get('v1/user/socialite-users'))
->setParent($this);
}
}
+9 -8
View File
@@ -4,23 +4,24 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Get; use Anikeen\Id\ApiOperations\Get;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\SshKeys; use Anikeen\Id\Resources\SshKeys;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesSshKeys trait ManagesSshKeys
{ {
use Get; use Get;
/** /**
* Get currently authed user with Bearer Token. * SSH keys of a user, read with the app's own token (trusted apps, scope ssh-keys:read),
* e.g. to install them on a new server.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function sshKeysByUserId(string $sskKeyId): SshKeys public function sshKeysByUserId(string $userId): SshKeys
{ {
return (new SshKeys($this->get(sprintf('v1/users/%s/ssh-keys/json', $sskKeyId)))) $app = $this->asApp();
->setParent($this);
return SshKeys::builder(fn() => $app->get(sprintf('v1/client/users/%s/ssh-keys', $userId)))
->setParent($app);
} }
} }
+51 -8
View File
@@ -2,24 +2,67 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request; use Anikeen\Id\Resources\AppCheckoutSessions;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Anikeen\Id\Resources\AppOrders;
use Anikeen\Id\Resources\AppSubscriptions;
use Anikeen\Id\Resources\CheckoutSessions;
use Anikeen\Id\Resources\Subscriptions; use Anikeen\Id\Resources\Subscriptions;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesSubscriptions trait ManagesSubscriptions
{ {
use Request; use HasBillable;
/** /**
* Get subscriptions from the current user. * Get subscriptions from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function subscriptions(): Subscriptions public function subscriptions(): Subscriptions
{ {
return (new Subscriptions($this->request('GET', 'v1/subscriptions'))) if (!isset($this->subscriptionsCache)) {
->setBillable($this); $this->subscriptionsCache = Subscriptions::builder(fn() => $this->anikeenId()
->request('GET', 'v1/subscriptions'))
->setBillable($this);
}
return $this->subscriptionsCache;
}
/**
* The user's subscriptions, managed with the app's own token instead of the user's
* (trusted apps only, scope subscriptions:client). Use this in jobs and anywhere the user's
* login may have expired.
*/
public function appSubscriptions(): AppSubscriptions
{
return new AppSubscriptions($this);
}
/**
* Checkout sessions for the user, created with the app's own token (trusted apps only, scope
* subscriptions:client): the user confirms several subscriptions at once on Anikeen ID.
*/
public function appCheckoutSessions(): AppCheckoutSessions
{
return new AppCheckoutSessions($this);
}
/**
* Checkout sessions with the user's own access token (any app): the user confirms several
* subscriptions at once on Anikeen ID.
*/
public function checkoutSessions(): CheckoutSessions
{
return new CheckoutSessions($this);
}
/**
* The user's orders that bill the app's subscriptions, read with the app's own token
* (trusted apps only, scope orders:client), e.g. ->pending() for unpaid ones.
*/
public function appOrders(): AppOrders
{
return new AppOrders($this);
} }
} }
+5 -8
View File
@@ -2,22 +2,19 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request; use Throwable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use GuzzleHttp\Exception\GuzzleException;
trait ManagesTaxation trait ManagesTaxation
{ {
use Request; use HasBillable;
/** /**
* Get VAT for the current user. * Get VAT for the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function vat(): float public function vatRate(): float
{ {
return $this->getUserData()->vat; return $this->getUserData()->vat_rate;
} }
} }
+10 -9
View File
@@ -2,25 +2,26 @@
namespace Anikeen\Id\Concerns; namespace Anikeen\Id\Concerns;
use Anikeen\Id\ApiOperations\Request;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Resources\Transactions; use Anikeen\Id\Resources\Transactions;
use Anikeen\Id\Result; use Throwable;
use GuzzleHttp\Exception\GuzzleException;
trait ManagesTransactions trait ManagesTransactions
{ {
use Request; use HasBillable;
/** /**
* Get transactions from the current user. * Get transactions from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function transactions(): Transactions public function transactions(): Transactions
{ {
return (new Transactions($this->request('GET', 'v1/transactions'))) if (!isset($this->transactionsCache)) {
->setBillable($this);; $this->transactionsCache = Transactions::builder(fn() => $this->anikeenId()
->request('GET', 'v1/transactions'))
->setBillable($this);
}
return $this->transactionsCache;
} }
} }
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace Anikeen\Id\Concerns;
use Anikeen\Id\Resources\AppCheckoutSessions;
use Anikeen\Id\Resources\AppOrders;
use Anikeen\Id\Result;
use Throwable;
/**
* Orders and payments on behalf of a user. Trusted apps only, sent with the app's token.
*/
trait ManagesUserBilling
{
/**
* Orders of all users that bill the app's subscriptions (e.g. ->pending() for unpaid ones).
*/
public function appOrders(): AppOrders
{
return new AppOrders();
}
/**
* Checkout sessions of the app for any user, e.g. to look one up from a checkout.* webhook
* (create() then needs a user_id).
*/
public function appCheckoutSessions(): AppCheckoutSessions
{
return new AppCheckoutSessions();
}
/**
* 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
* default payment method (402 when declined; the order stays pending and is retried).
*
* @param string $userId The user's Anikeen ID.
* @param array{
* group?: string,
* billing_address_id?: string,
* billing_address?: array,
* shipping_address_id?: string,
* 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}>,
* checkout?: bool,
* transaction_id?: string,
* transaction?: array,
* invoice_date?: string,
* currency_iso?: string
* } $attributes
* @throws Throwable
*/
public function createOrderForUser(string $userId, array $attributes): Result
{
return $this->asApp()->request('POST', 'v1/admin/orders', [...$attributes, 'user_id' => $userId]);
}
/**
* Book a payment of a user that was captured elsewhere (e.g. PayPal, Ko-fi). The same
* provider/payment_intent can only be booked once (409 with the existing transaction_id).
*
* @param string $userId The user's Anikeen ID.
* @param array{
* payment_provider?: string,
* payment_intent?: string,
* status: string,
* type: string,
* amount: float|string,
* currency_iso: string,
* created_at: string,
* group?: string,
* invoice_id?: string
* } $attributes
* @throws Throwable
*/
public function createTransactionForUser(string $userId, array $attributes): Result
{
return $this->asApp()->request('POST', 'v1/admin/transactions', [...$attributes, 'user_id' => $userId]);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Anikeen\Id\Concerns;
use Anikeen\Id\Resources\SshKeys;
use Throwable;
trait ManagesUserSshKeys
{
use HasBillable;
/**
* SSH keys of the current user (user token).
*
* @throws Throwable
*/
public function sshKeys(): SshKeys
{
$anikeenId = $this->anikeenId();
return SshKeys::builder(fn() => $anikeenId->get('v1/ssh-keys'))->setParent($anikeenId);
}
}
+50 -10
View File
@@ -5,9 +5,8 @@ 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\RequestRequiresClientIdException;
use Anikeen\Id\Result; use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
trait ManagesUsers trait ManagesUsers
{ {
@@ -17,8 +16,7 @@ trait ManagesUsers
/** /**
* Get currently authed user with Bearer Token * Get currently authed user with Bearer Token
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function getAuthedUser(): Result public function getAuthedUser(): Result
{ {
@@ -40,24 +38,66 @@ trait ManagesUsers
* - 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)
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function createUser(array $attributes): Result public function createUser(array $attributes): Result
{ {
return $this->post('v1/users', $attributes); // the API takes a single display name
if (!isset($attributes['name']) && (isset($attributes['first_name']) || isset($attributes['last_name']))) {
$attributes['name'] = trim(($attributes['first_name'] ?? '') . ' ' . ($attributes['last_name'] ?? '')) ?: null;
}
if (isset($attributes['password']) && !isset($attributes['password_confirmation'])) {
$attributes['password_confirmation'] = $attributes['password'];
}
unset($attributes['first_name'], $attributes['last_name']);
// finds the user by email or creates it (trusted apps, app token)
return $this->asApp()->post('v1/admin/users', $attributes);
}
/**
* Find the user of a social login or create it (trusted apps, app token).
*
* @param string $provider The socialite driver, e.g. "twitch".
* @param string $providerId The user's ID at the provider.
* @throws Throwable
*/
public function findOrCreateSocialiteUser(string $provider, string $providerId, ?string $email = null, ?string $name = null): Result
{
return $this->asApp()->post('v1/admin/users/socialite', array_filter([
'provider' => $provider,
'provider_id' => $providerId,
'email' => $email,
'name' => $name,
], fn ($value) => $value !== null));
}
/**
* Refreshes the access token using the refresh token.
*/
public function refreshToken(string $storedRefreshToken, string $scope = ''): Result
{
return $this->post('../oauth/token', [
'grant_type' => 'refresh_token',
'refresh_token' => $storedRefreshToken,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'scope' => $scope,
]);
} }
/** /**
* Checks if the given email exists. * Checks if the given email exists.
* *
* @param string $email The email to check. * @param string $email The email to check.
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function isEmailExisting(string $email): Result public function isEmailExisting(string $email): Result
{ {
return $this->post('v1/users/check', [ // `data.exists` tells whether an account uses the email (trusted apps, app token)
return $this->asApp()->post('v1/admin/users/check', [
'email' => $email, 'email' => $email,
]); ]);
} }
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace Anikeen\Id\Contracts;
use Anikeen\Id\AnikeenId;
interface Billable
{
public function getUserData(): object;
public function anikeenId(): AnikeenId;
}
+28 -4
View File
@@ -6,11 +6,35 @@ class Scope
{ {
const USER = 'user'; const USER = 'user';
const USER_READ = 'user:read'; const USER_READ = 'user:read';
const ORDERS = 'orders';
const ORDERS_READ = 'orders:read'; const ADDRESSES = 'addresses';
const PRODUCTS = 'products'; const ADDRESSES_READ = 'addresses:read';
const PRODUCTS_READ = 'products:read';
const BILLING = 'billing'; const BILLING = 'billing';
const BILLING_READ = 'billing:read'; const BILLING_READ = 'billing:read';
const BILLING_CLIENT = 'billing:client';
const INVOICES = 'invoices';
const INVOICES_READ = 'invoices:read';
const INVOICES_CLIENT = 'invoices:client';
const ORDERS = 'orders';
const ORDERS_READ = 'orders:read';
const ORDERS_CLIENT = 'orders:client';
const PAYMENT_METHODS = 'payment-methods';
const PAYMENT_METHODS_READ = 'payment-methods:read';
const SUBSCRIPTIONS = 'subscriptions';
const SUBSCRIPTIONS_READ = 'subscriptions:read';
const SUBSCRIPTIONS_CLIENT = 'subscriptions:client';
const TRANSACTIONS = 'transactions';
const TRANSACTIONS_READ = 'transactions:read';
const TRANSACTIONS_CLIENT = 'transactions:client';
const SSH_KEYS = 'ssh-keys';
const SSH_KEYS_READ = 'ssh-keys:read';
const ADMIN = 'admin'; const ADMIN = 'admin';
} }
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace Anikeen\Id\Exceptions;
use Throwable;
/**
* A request to the ID service failed. `status` is the HTTP status (0 when the service could not
* be reached), `error` the service's stable error code when it sent one (e.g. "already_cancelled").
*/
class ApiException extends ResourceException
{
public function __construct(
string $message,
public readonly int $status = 0,
public readonly ?string $error = null,
?Throwable $previous = null,
) {
parent::__construct($message, $status, $previous);
}
public function isNotFound(): bool
{
return $this->status === 404;
}
public function isConflict(): bool
{
return $this->status === 409;
}
/**
* The ID service could not be reached (network error, timeout) or failed (5xx): retry later.
*/
public function isTemporary(): bool
{
return $this->status === 0 || $this->status >= 500 || $this->status === 429;
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Anikeen\Id\Exceptions;
use Anikeen\Id\Result;
use Exception;
class CollectionException extends Exception
{
}
@@ -0,0 +1,17 @@
<?php
namespace Anikeen\Id\Exceptions;
use Throwable;
/**
* Thrown when a third-party app tries to check out an order or subscription itself: the user has
* to confirm it on Anikeen ID. Send them to the confirmation URL instead.
*/
class ConfirmationRequiredException extends ResourceException
{
public function __construct(string $message, int $code, public readonly ?string $confirmationUrl = null, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Anikeen\Id\Exceptions;
use Anikeen\Id\Result;
use Exception;
class ResourceException extends Exception
{
//
}
@@ -0,0 +1,13 @@
<?php
namespace Anikeen\Id\Exceptions;
use Exception;
/**
* The webhook request was not signed by Anikeen ID with your endpoint's secret, or is too old.
*/
class SignatureVerificationException extends Exception
{
//
}
+4 -1
View File
@@ -2,6 +2,7 @@
namespace Anikeen\Id\Helpers; namespace Anikeen\Id\Helpers;
use Anikeen\Id\AnikeenId;
use Firebase\JWT\JWT; use Firebase\JWT\JWT;
use Firebase\JWT\Key; use Firebase\JWT\Key;
use Illuminate\Auth\AuthenticationException; use Illuminate\Auth\AuthenticationException;
@@ -30,6 +31,8 @@ class JwtParser
private function getOauthPublicKey(): bool|string private function getOauthPublicKey(): bool|string
{ {
return file_get_contents(dirname(__DIR__, 3) . '/oauth-public.key'); return AnikeenId::getMode() === 'staging'
? file_get_contents(dirname(__DIR__, 3) . '/oauth-public.staging.key')
: file_get_contents(dirname(__DIR__, 3) . '/oauth-public.key');
} }
} }
+1 -1
View File
@@ -9,7 +9,7 @@ use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use stdClass; use stdClass;
abstract class CheckCredentials abstract class CheckCredentials extends UseParameters
{ {
/** /**
* Handle an incoming request. * Handle an incoming request.
+1 -1
View File
@@ -8,7 +8,7 @@ use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
class CheckForAnyScope class CheckForAnyScope extends UseParameters
{ {
/** /**
* Handle the incoming request. * Handle the incoming request.
+1 -1
View File
@@ -8,7 +8,7 @@ use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
class CheckScopes class CheckScopes extends UseParameters
{ {
/** /**
* Handle the incoming request. * Handle the incoming request.
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace Anikeen\Id\Http\Middleware;
abstract class UseParameters
{
/**
* Specify the parameters for the middleware.
*
* @param string[]|string $param
*/
public static function using(array|string $param, string ...$params): string
{
if (is_array($param)) {
return static::class . ':' . implode(',', $param);
}
return static::class . ':' . implode(',', [$param, ...$params]);
}
}
+2 -4
View File
@@ -23,13 +23,11 @@ trait OauthTrait
], ],
]); ]);
$result = new Result($response, null); $result = new Result($response, null, $this);
} catch (RequestException $exception) { } catch (RequestException $exception) {
$result = new Result($exception->getResponse(), $exception); $result = new Result($exception->getResponse(), $exception, $this);
} }
$result->anikeenId = $this;
return $result; return $result;
} }
} }
@@ -1,113 +0,0 @@
<?php
namespace Anikeen\Id\Providers;
use Anikeen\Id\AnikeenId;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
class AnikeenIdSsoUserProvider implements UserProvider
{
private ?string $accessTokenField = null;
public function __construct(
private AnikeenId $anikeenId,
private Request $request,
private string $model,
private array $fields
)
{
$this->accessTokenField = AnikeenId::getAccessTokenField();
}
public function retrieveById(mixed $identifier): ?Authenticatable
{
$model = $this->createModel();
$token = $this->request->bearerToken();
$user = $this->newModelQuery($model)
->where($model->getAuthIdentifierName(), $identifier)
->first();
// Return user when found
if ($user) {
// Update access token when updated
if ($this->accessTokenField) {
$user[$this->accessTokenField] = $token;
if ($user->isDirty()) {
$user->save();
}
}
return $user;
}
// Create new user
$this->anikeenId->setToken($token);
$result = $this->anikeenId->getAuthedUser();
if (!$result->success()) {
return null;
}
$attributes = Arr::only((array)$result->data(), $this->fields);
$attributes[$model->getAuthIdentifierName()] = $result->data->id;
if ($this->accessTokenField) {
$attributes[$this->accessTokenField] = $token;
}
return $this->newModelQuery($model)->create($attributes);
}
/**
* Create a new instance of the model.
*/
public function createModel(): Model
{
$class = '\\' . ltrim($this->model, '\\');
return new $class;
}
/**
* Get a new query builder for the model instance.
*/
protected function newModelQuery(?Model $model = null): Builder
{
return is_null($model)
? $this->createModel()->newQuery()
: $model->newQuery();
}
public function retrieveByToken($identifier, $token)
{
return null;
}
public function updateRememberToken(Authenticatable $user, $token)
{
// void
}
public function retrieveByCredentials(array $credentials)
{
return null;
}
public function validateCredentials(Authenticatable $user, array $credentials): bool
{
return false;
}
public function rehashPasswordIfRequired(Authenticatable $user, #[\SensitiveParameter] array $credentials, bool $force = false)
{
// TODO: Implement rehashPasswordIfRequired() method.
}
}
+124
View File
@@ -0,0 +1,124 @@
<?php
namespace Anikeen\Id\Providers;
use Anikeen\Id\AnikeenId;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
class AnikeenIdUserProvider implements UserProvider
{
private ?string $accessTokenField;
public function __construct(
private AnikeenId $anikeenId,
private Request $request,
private string $model,
private array $fields = []
) {
$this->accessTokenField = AnikeenId::getAccessTokenField();
}
/**
* {@inheritDoc}
*/
public function retrieveByToken($identifier, $token): ?Authenticatable
{
// Token from request (if not already pass from $token):
$token = $token ?: $this->request->bearerToken();
if (! $token) {
return null;
}
// Set token in SSO client and request user info
$this->anikeenId->setToken($token);
$result = $this->anikeenId->getAuthedUser();
if (! $result->success()) {
return null;
}
// Only the desired fields
$data = Arr::only((array)$result->data(), $this->fields);
// Primary key (e.g. $user->id)
$pk = $this->createModel()->getAuthIdentifierName();
$data[$pk] = $result->data->id;
// Fill in access token field, if available
if ($this->accessTokenField) {
$data[$this->accessTokenField] = $token;
}
// Local eloquent model: either find or create a new one
/** @var Model $modelInstance */
$modelInstance = $this->newModelQuery()
->firstOrNew([$pk => $data[$pk]]);
$modelInstance->fill($data);
$modelInstance->save();
return $modelInstance;
}
/**
* {@inheritDoc}
*/
public function updateRememberToken(Authenticatable $user, $token): void
{
// no-op
}
/**
* {@inheritDoc}
*/
public function retrieveByCredentials(array $credentials): ?Authenticatable
{
return null;
}
/**
* {@inheritDoc}
*/
public function validateCredentials(Authenticatable $user, array $credentials): bool
{
return true;
}
/**
* {@inheritDoc}
*/
public function retrieveById($identifier): ?Authenticatable
{
return $this->newModelQuery()
->where($this->createModel()->getAuthIdentifierName(), $identifier)
->first();
}
/**
* {@inheritDoc}
*/
public function rehashPasswordIfRequired(Authenticatable $user, #[\SensitiveParameter] array $credentials, bool $force = false): void
{
// no-op
}
/**
* @return Model
*/
protected function createModel(): Model
{
$class = '\\' . ltrim($this->model, '\\');
return new $class;
}
/**
* @return Builder
*/
protected function newModelQuery(): Builder
{
return $this->createModel()->newQuery();
}
}
+8
View File
@@ -32,6 +32,14 @@ class AppTokenRepository implements Repository
return $this->requestFreshAccessToken('*'); return $this->requestFreshAccessToken('*');
} }
/**
* Drop the cached token, e.g. after the ID service rejected it.
*/
public function forgetAccessToken(): void
{
Cache::forget(self::ACCESS_TOKEN_CACHE_KEY);
}
/** /**
* @throws RequestFreshAccessTokenException * @throws RequestFreshAccessTokenException
*/ */
+7 -9
View File
@@ -3,9 +3,7 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
/** /**
* @property string $id * @property string $id
@@ -63,23 +61,23 @@ class Address extends BaseResource
* - email: Email address (optional, e.g. for delivery notifications) * - email: Email address (optional, e.g. for delivery notifications)
* - primary: Whether this address should be the primary address (optional) * - primary: Whether this address should be the primary address (optional)
* - primary_billing_address: Whether this address should be the primary billing address (optional) * - primary_billing_address: Whether this address should be the primary billing address (optional)
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function update(array $attributes = []): self public function update(array $attributes = []): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/addresses/%s', $this->id), $attributes))) return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/addresses/%s', $this->id), $attributes)))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Delete given address from the current user. * Delete given address from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function delete(): bool public function delete(): bool
{ {
return $this->billable->request('DELETE', sprintf('v1/addresses/%s', $this->id))->success(); return $this->billable->anikeenId()
->request('DELETE', sprintf('v1/addresses/%s', $this->id))->success();
} }
} }
+11 -17
View File
@@ -3,9 +3,7 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
class Addresses extends BaseCollection class Addresses extends BaseCollection
{ {
@@ -44,12 +42,12 @@ class Addresses extends BaseCollection
*   - email: Email address (optional, e.g. for delivery notifications) *   - email: Email address (optional, e.g. for delivery notifications)
*   - primary: Whether this address should be the primary address (optional) *   - primary: Whether this address should be the primary address (optional)
*   - primary_billing_address: Whether this address should be the primary billing address (optional) *   - primary_billing_address: Whether this address should be the primary billing address (optional)
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function create(array $attributes = []): Address public function create(array $attributes = []): Address
{ {
return (new Address($this->billable->request('POST', 'v1/addresses', $attributes))) return (new Address(fn() => $this->billable->anikeenId()
->request('POST', 'v1/addresses', $attributes)))
->setBillable($this->billable); ->setBillable($this->billable);
} }
@@ -58,31 +56,27 @@ class Addresses extends BaseCollection
*/ */
public function find(string $id): ?Address public function find(string $id): ?Address
{ {
$result = $this->billable->request('GET', sprintf('v1/addresses/%s', $id)); return (new Address(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/addresses/%s', $id))))
return $result->success() ? ->setBillable($this->billable);
(new Address($result))
->setBillable($this->billable)
: null;
} }
/** /**
* Get default address from the current user. * Get default address from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function defaultBillingAddress(): Address public function defaultBillingAddress(): Address
{ {
return (new Address($this->billable->request('GET', sprintf('v1/addresses/%s', $this->billable->getUserData()->billing_address_id)))) return (new Address(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/addresses/%s', $this->billable->getUserData()->billing_address_id))))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Check if the current user has a default billing address. * Check if the current user has a default billing address.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function hasDefaultBillingAddress(): bool public function hasDefaultBillingAddress(): bool
{ {
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\IsCheckoutSession;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Support\AppRequest;
use JsonSerializable;
/**
* A checkout session created with the app's own token, see AppCheckoutSessions.
*
* @property string $id
* @property string $user_id
* @property ?string $oauth_client_id
* @property string $status open, completed, cancelled or expired
* @property ?string $return_url
* @property ?object $metadata
* @property ?string $confirmation_url
* @property list<string> $subscription_ids
* @property list<object> $subscriptions
* @property ?string $expires_at
* @property ?string $completed_at
* @property ?string $cancelled_at
* @property ?string $created_at
*/
class AppCheckoutSession implements JsonSerializable
{
use IsCheckoutSession;
public const STATUS_OPEN = 'open';
public const STATUS_COMPLETED = 'completed';
public const STATUS_CANCELLED = 'cancelled';
public const STATUS_EXPIRED = 'expired';
public function __construct(protected object $data)
{
}
public function __get(string $name): mixed
{
return $this->data->{$name} ?? null;
}
public function __isset(string $name): bool
{
return isset($this->data->{$name});
}
/**
* The session's subscriptions (drafts until the user confirms).
*
* @return list<AppSubscription>
*/
public function subscriptions(): array
{
return array_map(fn (object $subscription) => new AppSubscription($subscription), array_values((array) ($this->data->subscriptions ?? [])));
}
/**
* Withdraw an open session (e.g. the cart changed): it and its drafts are cancelled.
*
* @throws ApiException 409 "checkout_session_completed", "checkout_session_cancelled", "checkout_session_expired"
*/
public function cancel(): self
{
return $this->send('POST', '/cancel');
}
/**
* @throws ApiException
*/
public function refresh(): self
{
return $this->send('GET', '');
}
public function toArray(): array
{
return (array) $this->data;
}
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* @throws ApiException
*/
private function send(string $method, string $action): self
{
$this->data = AppRequest::send($method, sprintf('v1/client/checkout-sessions/%s%s', $this->id, $action))->data;
return $this;
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Contracts\Billable;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Support\AppRequest;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
/**
* Checkout sessions created with the app's own token (trusted apps, scope `subscriptions:client`):
* several subscriptions of one user that the user confirms together on Anikeen ID, instead of the
* app checking them out itself. For one user ($user->appCheckoutSessions()) or, to look sessions
* up e.g. from a webhook, for all users (app(AnikeenId::class)->appCheckoutSessions()).
* Nothing is requested until a method is called.
*/
class AppCheckoutSessions
{
public function __construct(protected Billable|Model|null $billable = null)
{
}
/**
* Open a checkout session with new subscriptions (their attributes, like
* AppSubscriptions::create()) and/or existing drafts of the app (`['id' => …]`).
*
* @param array{
* subscriptions: list<array{id: string}|array{
* group?: null|string,
* name: string,
* description?: null|string,
* unit: string,
* price: float|string,
* vat_rate?: float,
* payload?: null|array,
* ends_at?: null|string
* }>,
* return_url?: null|string,
* metadata?: null|array,
* idempotency_key?: null|string,
* user_id?: string
* } $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
* repeated idempotency_key returns the first session instead of a new one.
*
* @throws ApiException 422 validation (e.g. return_url), 409 "idempotency_key_conflict"
*/
public function create(array $attributes): AppCheckoutSession
{
if ($this->billable) {
$attributes['user_id'] = (new AppSubscriptions($this->billable))->userId();
} elseif (empty($attributes['user_id'])) {
throw new InvalidArgumentException('A checkout session needs a user: use $user->appCheckoutSessions() or pass user_id.');
}
return new AppCheckoutSession(AppRequest::send('POST', 'v1/client/checkout-sessions', $attributes)->data);
}
/**
* A session of the app; null when it doesn't exist (or belongs to another user).
*
* @throws ApiException
*/
public function find(string $id): ?AppCheckoutSession
{
try {
$session = new AppCheckoutSession(AppRequest::send('GET', sprintf('v1/client/checkout-sessions/%s', $id))->data);
} catch (ApiException $e) {
if ($e->isNotFound()) {
return null;
}
throw $e;
}
return !$this->billable || $session->user_id === (new AppSubscriptions($this->billable))->userId() ? $session : null;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Contracts\Billable;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Support\AppRequest;
use Illuminate\Database\Eloquent\Model;
/**
* Orders that bill the app's subscriptions, read with the app's own token (trusted apps,
* scope orders:client) - of one user ($user->appOrders()) or of all users
* (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),
* is_collective, net_total, vat_total, gross_total, currency_iso, created_at, paid_at,
* payment_attempts, next_payment_attempt_at and last_payment_error ({code, message} or null).
*/
class AppOrders
{
public function __construct(protected Billable|Model|null $billable = null)
{
}
/**
* All matching orders, oldest first.
*
* @param array{status?: string, group?: string} $filters
* @return list<object>
*
* @throws ApiException
*/
public function all(array $filters = []): array
{
$orders = [];
$page = 1;
do {
$result = AppRequest::send('GET', 'v1/client/orders', null, [
...$filters,
...($this->billable ? ['user_id' => $this->userId()] : []),
'per_page' => 100,
'page' => $page,
]);
array_push($orders, ...$result->data);
$lastPage = (int) ($result->meta->last_page ?? $page);
} while ($page++ < $lastPage);
return $orders;
}
/**
* Closed orders that aren't paid (yet), oldest first.
*
* @return list<object>
*
* @throws ApiException
*/
public function pending(array $filters = []): array
{
return $this->all([...$filters, 'status' => 'pending']);
}
/**
* @throws ApiException
*/
public function find(string $id): ?object
{
try {
$order = AppRequest::send('GET', sprintf('v1/client/orders/%s', $id))->data;
} catch (ApiException $e) {
if ($e->isNotFound()) {
return null;
}
throw $e;
}
return !$this->billable || $order->user_id === $this->userId() ? $order : null;
}
private function userId(): string
{
return (new AppSubscriptions($this->billable))->userId();
}
}
+137
View File
@@ -0,0 +1,137 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Support\AppRequest;
use DateTimeInterface;
use JsonSerializable;
/**
* A subscription managed by the app itself (client credentials), see AppSubscriptions.
*
* @property string $id
* @property string $user_id
* @property ?string $group
* @property string $name
* @property ?string $description
* @property string $unit
* @property float $price
* @property ?float $vat_rate
* @property bool $active
* @property bool $autorenew
* @property bool $cancelled
* @property ?string $status "active" or "inactive"
* @property ?string $starts_at
* @property ?string $ends_at
* @property ?string $accounting_at
* @property bool $is_past_due
* @property int $failed_renewal_retries
* @property ?array $payload
* @property ?string $idempotency_key
* @property ?string $checkout_session_id the checkout session the user confirms it in, if any
*/
class AppSubscription implements JsonSerializable
{
public function __construct(protected object $data)
{
}
public function __get(string $name): mixed
{
return $this->data->{$name} ?? null;
}
public function __isset(string $name): bool
{
return isset($this->data->{$name});
}
/**
* Change a subscription (send only what changes). Before checkout everything can change;
* afterwards only the description, which names what the customer pays for and is shown
* on their bills, e.g. `$subscription->update(['description' => 'web-01.example.com'])`.
*
* @throws ApiException
*/
public function update(array $attributes): self
{
return $this->send('PUT', '', $attributes);
}
/**
* Activate the subscription and bill its first period.
*
* $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.
*
* @throws ApiException 409 "already_active", "billing_address_missing", "period_already_ended", …
*/
public function checkout(DateTimeInterface|string|null $startsAt = null): self
{
if ($startsAt instanceof DateTimeInterface) {
$startsAt = $startsAt->format(DateTimeInterface::ATOM);
}
return $this->send('PUT', '/checkout', $startsAt === null ? null : ['starts_at' => $startsAt]);
}
/**
* Cancel the subscription. With $refund (only within 14 days of its start), its not yet
* charged usage is credited.
*
* @throws ApiException 409 "already_cancelled", 404 "subscription_not_found", …
*/
public function revoke(bool $refund = false): self
{
return $this->send('PUT', '/revoke', ['refund' => $refund]);
}
/**
* Stop renewing; the subscription expires when its paid period ends.
*
* @throws ApiException
*/
public function pause(): self
{
return $this->send('PUT', '/pause');
}
/**
* Renew again (an expired subscription starts a new period).
*
* @throws ApiException
*/
public function resume(): self
{
return $this->send('PUT', '/resume');
}
/**
* @throws ApiException
*/
public function refresh(): self
{
return $this->send('GET', '');
}
public function toArray(): array
{
return (array) $this->data;
}
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* @throws ApiException
*/
private function send(string $method, string $action, ?array $payload = null): self
{
$this->data = AppRequest::send($method, sprintf('v1/client/subscriptions/%s%s', $this->id, $action), $payload)->data;
return $this;
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Contracts\Billable;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Support\AppRequest;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
/**
* Subscriptions of a user, managed with the app's own token (client credentials, scope
* `subscriptions:client`) instead of the user's token, so they keep working when the user's
* login expired. The app has to be trusted by the ID service. Nothing is requested until a
* method is called.
*/
class AppSubscriptions
{
public function __construct(protected Billable|Model $billable)
{
}
/**
* The user's Anikeen ID (see AnikeenId::useUserIdField()).
*/
public function userId(): string
{
$userId = $this->billable->{AnikeenId::getUserIdField()} ?? null;
if (empty($userId)) {
throw new InvalidArgumentException(sprintf('The billable has no Anikeen ID in [%s].', AnikeenId::getUserIdField()));
}
return (string) $userId;
}
/**
* Create a subscription for the user (it is billed only after checkout()).
*
* @param array{
* group?: null|string,
* name: string,
* description?: null|string,
* unit: string,
* price: float|string,
* vat_rate?: float,
* payload?: null|array,
* ends_at?: null|string,
* idempotency_key?: null|string
* } $attributes With an idempotency_key (max. 191 characters), a retried call returns the
* subscription created by the first one instead of a duplicate.
*
* @throws ApiException
*/
public function create(array $attributes): AppSubscription
{
return new AppSubscription(AppRequest::send('POST', 'v1/client/subscriptions', [
...$attributes,
'user_id' => $this->userId(),
])->data);
}
/**
* Find one of the user's subscriptions; null when it doesn't exist (or belongs to someone else).
*
* @throws ApiException
*/
public function find(string $id): ?AppSubscription
{
try {
$subscription = new AppSubscription(AppRequest::send('GET', sprintf('v1/client/subscriptions/%s', $id))->data);
} catch (ApiException $e) {
if ($e->isNotFound()) {
return null;
}
throw $e;
}
return $subscription->user_id === $this->userId() ? $subscription : null;
}
/**
* All of the user's subscriptions, optionally filtered.
*
* @param array{group?: string, active?: bool, cancelled?: bool} $filters
* @return list<AppSubscription>
*
* @throws ApiException
*/
public function all(array $filters = []): array
{
$subscriptions = [];
$page = 1;
do {
$result = AppRequest::send('GET', 'v1/client/subscriptions', null, [
...array_map(fn ($value) => is_bool($value) ? (int) $value : $value, $filters),
'user_id' => $this->userId(),
'per_page' => 100,
'page' => $page,
]);
foreach ($result->data as $data) {
$subscriptions[] = new AppSubscription($data);
}
$lastPage = (int) ($result->meta->last_page ?? $page);
} while ($page++ < $lastPage);
return $subscriptions;
}
}
+48 -4
View File
@@ -2,17 +2,51 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\MagicProperties; use Anikeen\Id\AnikeenId;
use Anikeen\Id\Exceptions\CollectionException;
use Anikeen\Id\Helpers\Paginator;
use Anikeen\Id\Result; use Anikeen\Id\Result;
use Closure;
use GuzzleHttp\Psr7\Response;
use JsonSerializable; use JsonSerializable;
use Throwable;
/**
* @property bool $success
* @property mixed $data
* @property int $total
* @property int $status
* @property null|array $links
* @property null|array $meta
* @property null|Paginator $paginator
* @property AnikeenId $anikeenId
* @property Response $response
* @property null|Throwable $exception
*/
#[\AllowDynamicProperties]
abstract class BaseCollection implements JsonSerializable abstract class BaseCollection implements JsonSerializable
{ {
use MagicProperties; private Closure $callable;
public ?Result $result = null;
public function __construct(protected Result $result) /**
* @throws CollectionException
*/
protected function __construct(callable $callable)
{ {
// $this->result = $callable();
if (!$this->result->success()) {
throw new CollectionException(sprintf('%s for collection [%s]', rtrim($this->result->data->message, '.'), get_called_class()), $this->result->response->getStatusCode());
}
}
/**
* @throws CollectionException
*/
public static function builder(callable $callable): static
{
return new static($callable, false);
} }
/** /**
@@ -43,4 +77,14 @@ abstract class BaseCollection implements JsonSerializable
* Returns the Resource based on the ID. * Returns the Resource based on the ID.
*/ */
abstract public function find(string $id): ?BaseResource; abstract public function find(string $id): ?BaseResource;
public function __get(string $name)
{
return $this->result->{$name} ?? null;
}
public function __isset(string $name): bool
{
return isset($this->result->{$name});
}
} }
+42 -9
View File
@@ -2,17 +2,48 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\MagicProperties; use Anikeen\Id\Exceptions\ConfirmationRequiredException;
use Anikeen\Id\Exceptions\ResourceException;
use Anikeen\Id\Result; use Anikeen\Id\Result;
use JsonSerializable; use JsonSerializable;
#[\AllowDynamicProperties]
abstract class BaseResource implements JsonSerializable abstract class BaseResource implements JsonSerializable
{ {
use MagicProperties; public Result $result;
public function __construct(protected Result $result) /**
* @throws ResourceException
*/
public function __construct(callable $callable)
{ {
$this->setMagicProperties($this->result->data); $this->result = $callable();
if (!$this->result->success()) {
if (($this->result->data->error ?? null) === 'confirmation_required') {
throw new ConfirmationRequiredException(
$this->result->data->message ?? 'The user has to confirm this on Anikeen ID.',
$this->result->response->getStatusCode(),
$this->result->data->confirmation_url ?? null,
);
}
throw new ResourceException(sprintf('%s for resource [%s]', rtrim($this->result->data->message, '.'), get_called_class()), $this->result->response->getStatusCode());
}
foreach ($this->result->data as $key => $value) {
if (!property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
/**
* Returns the collection of resources as a JSON string.
*/
public function jsonSerialize(): array
{
return $this->toArray();
} }
/** /**
@@ -23,11 +54,13 @@ abstract class BaseResource implements JsonSerializable
return (array)$this->result->data; return (array)$this->result->data;
} }
/** public function __get(string $name)
* Returns the collection of resources as a JSON string.
*/
public function jsonSerialize(): array
{ {
return $this->toArray(); return null;
}
public function __isset(string $name): bool
{
return false;
} }
} }
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Concerns\IsCheckoutSession;
use Throwable;
/**
* A checkout session created with the user's access token, see CheckoutSessions.
*
* @property string $id
* @property string $user_id
* @property ?string $oauth_client_id
* @property string $status open, completed, cancelled or expired
* @property ?string $return_url
* @property ?object $metadata
* @property ?string $confirmation_url
* @property list<string> $subscription_ids
* @property list<object> $subscriptions
* @property ?string $expires_at
* @property ?string $completed_at
* @property ?string $cancelled_at
* @property ?string $created_at
*/
class CheckoutSession extends BaseResource
{
use HasBillable;
use IsCheckoutSession;
public const STATUS_OPEN = 'open';
public const STATUS_COMPLETED = 'completed';
public const STATUS_CANCELLED = 'cancelled';
public const STATUS_EXPIRED = 'expired';
/**
* Withdraw an open session: it and its drafts are cancelled.
*
* @throws Throwable
*/
public function cancel(): self
{
return (new self(fn () => $this->billable->anikeenId()
->request('POST', sprintf('v1/checkout-sessions/%s/cancel', $this->id))))
->setBillable($this->billable);
}
/**
* @throws Throwable
*/
public function refresh(): self
{
return (new self(fn () => $this->billable->anikeenId()
->request('GET', sprintf('v1/checkout-sessions/%s', $this->id))))
->setBillable($this->billable);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Contracts\Billable;
use Anikeen\Id\Exceptions\ResourceException;
use Illuminate\Database\Eloquent\Model;
use Throwable;
/**
* Checkout sessions of the signed-in user, with the user's access token (any app): several
* subscriptions the user confirms together on Anikeen ID. Nothing is requested until a method is
* called.
*/
class CheckoutSessions
{
use HasBillable;
public function __construct(Billable|Model $billable)
{
$this->billable = $billable;
}
/**
* Open a checkout session with new subscriptions and/or existing drafts of the app
* (`['id' => …]`); see AppCheckoutSessions::create() for the attributes (no user_id here,
* vat_rate only for trusted apps).
*
* @throws Throwable
*/
public function create(array $attributes): CheckoutSession
{
return (new CheckoutSession(fn () => $this->billable->anikeenId()
->request('POST', 'v1/checkout-sessions', $attributes)))
->setBillable($this->billable);
}
/**
* A session the app created for the user; null when it doesn't exist.
*
* @throws Throwable
*/
public function find(string $id): ?CheckoutSession
{
try {
return (new CheckoutSession(fn () => $this->billable->anikeenId()
->request('GET', sprintf('v1/checkout-sessions/%s', $id))))
->setBillable($this->billable);
} catch (ResourceException $e) {
if ($e->getCode() === 404) {
return null;
}
throw $e;
}
}
}
+7 -6
View File
@@ -3,8 +3,7 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use GuzzleHttp\Exception\GuzzleException;
/** /**
* @property string $id * @property string $id
@@ -16,11 +15,13 @@ class Invoice extends BaseResource
/** /**
* Get temporary download url from given invoice. * Get temporary download url from given invoice.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function getInvoiceTemporaryUrl(): string public function getInvoiceTemporaryUrl(): ?string
{ {
return $this->billable->request('PUT', sprintf('v1/invoices/%s', $this->id))->data->temporary_url; return $this->billable->anikeenId()
->request('GET', sprintf('v1/invoices/%s', $this->id))
->data
->temporary_url ?? null;
} }
}␍ }␍
+3 -9
View File
@@ -3,9 +3,6 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
class Invoices extends BaseCollection class Invoices extends BaseCollection
{ {
@@ -16,11 +13,8 @@ class Invoices extends BaseCollection
*/ */
public function find(string $id): ?Invoice public function find(string $id): ?Invoice
{ {
$result = $this->billable->request('GET', sprintf('v1/invoices/%s', $id)); return (new Invoice(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/invoices/%s', $id))))
return $result->success() ->setBillable($this->billable);
? (new Invoice($result))
->setBillable($this->billable)
: null;
} }
} }
+39 -24
View File
@@ -3,15 +3,17 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Anikeen\Id\Concerns\HasConfirmationUrl;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
/** /**
* @property string $id * @property string $id
* @property null|string $confirmation_url where the user confirms it (third-party apps)
*/ */
class Order extends BaseResource class Order extends BaseResource
{ {
use HasBillable; use HasBillable;
use HasConfirmationUrl;
/** /**
* Update given order from the current user. * Update given order from the current user.
@@ -40,13 +42,13 @@ class Order extends BaseResource
* }, * },
* shipping_address: null|array{ * shipping_address: null|array{
* company_name: null|string, * company_name: null|string,
* first_name: string, * first_name: string,
* last_name: string, * last_name: string,
* address: null|string, * address: string,
* address_2: string, * address_2: null|string,
* house_number: null|string, * house_number: null|string,
* city: string, * city: string,
* state: string, * state: null|string,
* postal_code: string, * postal_code: string,
* country_iso: string, * country_iso: string,
* phone_number: null|string, * phone_number: null|string,
@@ -54,60 +56,73 @@ class Order extends BaseResource
* } * }
* } $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 (first name, last name, 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)
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function update(array $attributes = []): self public function update(array $attributes = []): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/orders/%s', $this->id), $attributes))) return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/orders/%s', $this->id), $attributes)))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Checkout given order from the current user. * Checkout given order from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function checkout(string $orderId): self public function checkout(): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/orders/%s/checkout', $this->id)))) return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/orders/%s/checkout', $this->id))))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Revoke given order from the current user. * Revoke given order from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function revoke(string $orderId): self public function revoke(): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/orders/%s/revoke', $this->id)))) return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/orders/%s/revoke', $this->id))))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Delete given order from the current user. * Delete given order from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function delete(): bool public function delete(): bool
{ {
return $this->billable->request('DELETE', sprintf('v1/orders/%s', $this->id))->success(); return $this->billable->anikeenId()
->request('DELETE', sprintf('v1/orders/%s', $this->id))->success();
}
/**
* Deliveries of this order's goods; `create()` ships them (see Shipments::create()).
*
* @throws Throwable
*/
public function shipments(): Shipments
{
return Shipments::builder(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/orders/%s/shipments', $this->id)))
->setBillable($this->billable)
->setParent($this);
} }
/** /**
* Get order items from given order. * Get order items from given order.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function orderItems(array $parameters = []): OrderItems public function orderItems(array $parameters = []): OrderItems
{ {
return (new OrderItems($this->billable->request('GET', sprintf('v1/orders/%s/items', $this->id), [], $parameters))) return OrderItems::builder(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/orders/%s/items', $this->id), [], $parameters))
->setBillable($this->billable) ->setBillable($this->billable)
->setParent($this); ->setParent($this);
} }
+7 -8
View File
@@ -4,8 +4,7 @@ namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Concerns\HasParent; use Anikeen\Id\Concerns\HasParent;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use GuzzleHttp\Exception\GuzzleException;
/** /**
* @property string $id * @property string $id
@@ -31,12 +30,12 @@ class OrderItem extends BaseResource
* }> * }>
* } $attributes The order data: * } $attributes The order data:
* - items: Array of order items, each with type, name, description, price, unit, and quantity * - items: Array of order items, each with type, name, description, price, unit, and quantity
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function update(array $attributes = []): self public function update(array $attributes = []): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/orders/%s/items/%s', $this->parent->id, $this->id), $attributes))) return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/orders/%s/items/%s', $this->parent->id, $this->id), $attributes)))
->setBillable($this->billable) ->setBillable($this->billable)
->setParent($this->parent); ->setParent($this->parent);
} }
@@ -44,11 +43,11 @@ class OrderItem extends BaseResource
/** /**
* Delete given order item from given order. * Delete given order item from given order.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function delete(): bool public function delete(): bool
{ {
return $this->billable->request('DELETE', sprintf('v1/orders/%s/items/%s', $this->parent->id, $this->id))->success(); return $this->billable->anikeenId()
->request('DELETE', sprintf('v1/orders/%s/items/%s', $this->parent->id, $this->id))->success();
} }
} }
+15 -14
View File
@@ -4,9 +4,7 @@ namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Concerns\HasParent; use Anikeen\Id\Concerns\HasParent;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
class OrderItems extends BaseCollection class OrderItems extends BaseCollection
{ {
@@ -30,12 +28,19 @@ class OrderItems extends BaseCollection
* }> * }>
* } $attributes The order data: * } $attributes The order data:
* - items: Array of order items, each with type, name, description, price, unit, and quantity * - items: Array of order items, each with type, name, description, price, unit, and quantity
* @throws RequestRequiresClientIdException *
* @throws GuzzleException * Only trusted apps may add items, and only to draft orders. Returns the first created item.
*
* @throws Throwable
*/ */
public function create(string $orderId, array $attributes = []): OrderItem public function create(string $orderId, array $attributes = []): OrderItem
{ {
return (new OrderItem($this->billable->request('POST', sprintf('v1/orders/%s', $orderId), $attributes))) return (new OrderItem(fn() => tap($this->billable->anikeenId()
->request('POST', sprintf('v1/orders/%s/items', $orderId), $attributes), function ($result) {
if (is_array($result->data)) {
$result->data = $result->data[0] ?? null;
}
})))
->setBillable($this->billable) ->setBillable($this->billable)
->setParent($this->parent); ->setParent($this->parent);
} }
@@ -45,13 +50,9 @@ class OrderItems extends BaseCollection
*/ */
public function find(string $id): ?OrderItem public function find(string $id): ?OrderItem
{ {
/** @var Result $result */ return (new OrderItem(fn() => $this->parent->anikeenId()
$result = $this->parent->request('GET', sprintf('v1/orders/%s/items/%s', $this->parent->id, $id)); ->request('GET', sprintf('v1/orders/%s/items/%s', $this->parent->id, $id))))
->setBillable($this->billable)
return $result->success() ? ->setParent($this->parent);
(new OrderItem($result))
->setBillable($this->billable)
->setParent($this->parent)
: null;
} }
}␍ }␍
+27 -27
View File
@@ -3,9 +3,7 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
class Orders extends BaseCollection class Orders extends BaseCollection
{ {
@@ -38,53 +36,55 @@ class Orders extends BaseCollection
* }, * },
* shipping_address: null|array{ * shipping_address: null|array{
* company_name: null|string, * company_name: null|string,
* first_name: string, * first_name: string,
* last_name: string, * last_name: string,
* address: null|string, * address: string,
* address_2: string, * address_2: null|string,
* house_number: null|string, * house_number: null|string,
* city: string, * city: string,
* state: string, * state: null|string,
* postal_code: string, * postal_code: string,
* country_iso: string, * country_iso: string,
* phone_number: null|string, * phone_number: null|string,
* email: null|string * email: null|string
* }, * },
* items: array<array{ * items: array<array{
* type: string, * type: string,
* name: string, * name: string,
* description: string, * description?: null|string,
* price: float|int, * image_url?: null|string,
* unit: string, * price?: float|int|string,
* units: int * gross_price?: float|int|string,
* unit: string,
* units: int
* }> * }>
* } $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 (first name, last name, 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)
* - items: Array of order items (each with type, name, price, unit, units, and quantity) * - items: Array of order items:
* @throws RequestRequiresClientIdException * - type: digital, physical or physical-reduced (VAT category)
* @throws GuzzleException * - price/gross_price: net or gross unit price, one of both
* - unit: hour, day, week, month, year, onetime or piece
* - image_url: http(s) URL of a product image; Anikeen ID copies it, so it stays
* visible on the order and invoice when the shop removes it later
* @throws Throwable
*/ */
public function create(array $attributes = []): Order public function create(array $attributes = []): Order
{ {
return (new Order($this->billable->request('POST', 'v1/orders', $attributes))) return (new Order(fn() => $this->billable->anikeenId()
->request('POST', 'v1/orders', $attributes)))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Get given order from the current user. * Get given order from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function find(string $id): ?Order public function find(string $id): ?Order
{ {
/** @var Result $result */ return (new Order(fn() => $this->billable->anikeenId()
$result = $this->billable->request('GET', sprintf('v1/orders/%s', $id)); ->request('GET', sprintf('v1/orders/%s', $id))))
->setBillable($this->billable);
return $result->success()
? (new Order($result))
->setBillable($this->billable)
: null;
} }
} }
+12
View File
@@ -10,4 +10,16 @@ use Anikeen\Id\Concerns\HasBillable;
class PaymentMethod extends BaseResource class PaymentMethod extends BaseResource
{ {
use HasBillable; use HasBillable;
/**
* Remove this payment method from the current user.
*
* @throws \Throwable
*/
public function delete(): bool
{
return $this->billable->anikeenId()
->request('DELETE', sprintf('v1/payment-methods/%s', $this->id))
->success();
}
}␍ }␍
+38 -32
View File
@@ -3,65 +3,71 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
class PaymentMethods extends BaseCollection class PaymentMethods extends BaseCollection
{ {
use HasBillable; use HasBillable;
private ?PaymentMethod $cachedDefaultPaymentMethod = null;
/** /**
* Check if current user has at least one payment method. * Check if current user has at least one payment method.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function hasPaymentMethod(): bool public function hasPaymentMethod(): bool
{ {
return $this->result->count() > 0; return $this->result->count() > 0;
} }
/**
* Get default payment method from the current user.
*
* @throws RequestRequiresClientIdException
* @throws GuzzleException
*/
public function defaultPaymentMethod(): PaymentMethod
{
if ($this->cachedDefaultPaymentMethod === null) {
$this->cachedDefaultPaymentMethod = (new PaymentMethod(
$this->billable->request('GET', 'v1/payment-methods/default')
))->setBillable($this->billable);
}
return $this->cachedDefaultPaymentMethod;
}
/** /**
* Check if the current user has a default payment method. * Check if the current user has a default payment method.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function hasDefaultPaymentMethod(): bool public function hasDefaultPaymentMethod(): bool
{ {
return $this->defaultPaymentMethod()?->id !== null; return $this->defaultPaymentMethod()?->id !== null;
} }
/**
* Get default payment method from the current user.
*
* @throws Throwable
*/
public function defaultPaymentMethod(): PaymentMethod
{
if (!isset($this->defaultPaymentMethodCache)) {
$this->defaultPaymentMethodCache = (new PaymentMethod(fn() => $this->billable->anikeenId()
->request('GET', 'v1/payment-methods/default')))
->setBillable($this->billable);
}
return $this->defaultPaymentMethodCache;
}
/**
* Set the default payment method for the current user.
*
* @throws Throwable
*/
public function setDefault(string $id): PaymentMethod
{
unset($this->defaultPaymentMethodCache);
return (new PaymentMethod(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/payment-methods/%s/default', $id))))
->setBillable($this->billable);
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*
* @throws Throwable
*/ */
public function find(string $id): ?PaymentMethod public function find(string $id): ?PaymentMethod
{ {
$result = $this->billable->request('GET', sprintf('v1/payment-methods/%s', $id)); return (new PaymentMethod(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/payment-methods/%s', $id))))
return $result->success() ->setBillable($this->billable);
? (new PaymentMethod($result))
->setBillable($this->billable)
: null;
} }
} }
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Concerns\HasParent;
use Throwable;
/**
* @property string $id
* @property string $number delivery note number, e.g. LS-2026-0001
* @property string $order_id
* @property null|string $carrier
* @property null|string $tracking_number
* @property null|string $tracking_url
* @property array $items order_item_id, name, description, units
* @property object $shipping_address
* @property null|string $note
* @property string $shipped_at
*/
class Shipment extends BaseResource
{
use HasBillable;
use HasParent;
/**
* The delivery note as PDF (binary string).
*
* @throws Throwable
*/
public function deliveryNote(): string
{
$result = $this->billable->anikeenId()
->request('GET', sprintf('v1/orders/%s/shipments/%s/delivery-note', $this->order_id, $this->id));
return (string) $result->response?->getBody();
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Concerns\HasParent;
use Throwable;
/**
* Deliveries of an order's physical goods. Each one adds a delivery note to the customer's
* order documents on Anikeen ID.
*/
class Shipments extends BaseCollection
{
use HasBillable;
use HasParent;
/**
* Ship goods of a paid order. Only the app that created the order (or a trusted app) can.
*
* Without `items`, everything physical that hasn't been shipped yet is shipped. Items and
* the shipping address are stored as they are now; the user sees them on the delivery note.
*
* @param array{
* carrier?: string,
* tracking_number?: string,
* tracking_url?: string,
* note?: string,
* shipped_at?: string,
* notify_customer?: bool,
* items?: array<array{order_item_id: string, units?: float|int|string}>
* } $attributes
* - carrier: e.g. "DHL"
* - tracking_url: http(s) link to track the parcel, shown to the user
* - shipped_at: when it was sent (default: now, not in the future)
* - notify_customer: Anikeen ID mails the user with the delivery note (default true);
* false if your shop sends its own mail
* - items: physical items of the order and how many of them (default: all left)
*
* Errors (ResourceException with the HTTP status): 409 when the order isn't paid or nothing
* is left to ship, 422 for items that aren't physical items of the order or exceed what's left.
*
* @throws Throwable
*/
public function create(array $attributes = []): Shipment
{
return (new Shipment(fn() => $this->billable->anikeenId()
->request('POST', sprintf('v1/orders/%s/shipments', $this->parent->id), $attributes)))
->setBillable($this->billable)
->setParent($this->parent);
}
/**
* {@inheritDoc}
*/
public function find(string $id): ?Shipment
{
return (new Shipment(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/orders/%s/shipments/%s', $this->parent->id, $id))))
->setBillable($this->billable)
->setParent($this->parent);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Anikeen\Id\Resources;
/**
* @property string $id
* @property string $user_id
* @property string $driver
* @property string $uid
* @property string|null $display_name
* @property string|null $avatar
* @property string|null $expires_at
* @property string $created_at
* @property string $updated_at
*/
class SocialiteUser extends BaseResource
{
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasParent;
class SocialiteUsers extends BaseCollection
{
use HasParent;
public function find(string $id): ?SocialiteUser
{
return null;
}
}
+12 -4
View File
@@ -3,8 +3,7 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasParent; use Anikeen\Id\Concerns\HasParent;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use GuzzleHttp\Exception\GuzzleException;
/** /**
* @property string $id * @property string $id
@@ -16,9 +15,18 @@ class SshKey extends BaseResource
/** /**
* Deletes a given ssh key for the currently authed user. * Deletes a given ssh key for the currently authed user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
/**
* Rename the SSH key.
*
* @throws Throwable
*/
public function update(string $name): self
{
return (new self(fn() => $this->parent->put(sprintf('v1/ssh-keys/%s', $this->id), ['name' => $name])))->setParent($this->parent);
}
public function delete(): bool public function delete(): bool
{ {
return $this->parent->delete(sprintf('v1/ssh-keys/%s', $this->id))->success(); return $this->parent->delete(sprintf('v1/ssh-keys/%s', $this->id))->success();
+4 -13
View File
@@ -3,9 +3,7 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasParent; use Anikeen\Id\Concerns\HasParent;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Throwable;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
class SshKeys extends BaseCollection class SshKeys extends BaseCollection
{ {
@@ -16,12 +14,11 @@ class SshKeys extends BaseCollection
* *
* @param string $publicKey The public key to be added * @param string $publicKey The public key to be added
* @param string|null $name The name of the key (optional) * @param string|null $name The name of the key (optional)
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function create(string $publicKey, ?string $name = null): SshKey public function create(string $publicKey, ?string $name = null): SshKey
{ {
return (new SshKey($this->parent->post('v1/ssh-keys', [ return (new SshKey(fn() => $this->parent->post('v1/ssh-keys', [
'public_key' => $publicKey, 'public_key' => $publicKey,
'name' => $name, 'name' => $name,
])))->setParent($this->parent); ])))->setParent($this->parent);
@@ -32,12 +29,6 @@ class SshKeys extends BaseCollection
*/ */
public function find(string $id): ?SshKey public function find(string $id): ?SshKey
{ {
/** @var Result $result */ return (new SshKey(fn() => $this->parent->get(sprintf('v1/ssh-keys/%s', $id))))->setParent($this->parent);
$result = $this->parent->get(sprintf('v1/ssh-keys/%s', $id));
return $result->success()
? (new SshKey($result))
->setParent($this->parent)
: null;
} }
}␍ }␍
+63 -24
View File
@@ -3,66 +3,105 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Anikeen\Id\Concerns\HasConfirmationUrl;
use GuzzleHttp\Exception\GuzzleException; use Anikeen\Id\Contracts\AppTokenRepository;
use Throwable;
/** /**
* @property string $id * @property string $id
* @property string $name * @property string $name
* @property string $description * @property string $description
* @property string $status
* @property string $unit * @property string $unit
* @property float $price * @property float $price
* @property float $vat_rate
* @property array $payload
* @property string $ends_at * @property string $ends_at
* @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;
/**
* Update a given subscription from the current user.
*
* @param array{
* group: string,
* name: string,
* description: null|string,
* unit: string,
* price: float,
* vat_rate: float,
* payload: null|array,
* ends_at: null|string
* } $attributes The subscription data:
* - group: The group (optional)
* - name: The name (required when set)
* - description: The description (optional)
* - unit: The unit (required when set, e.g. "hour", "day", "week", "month", "year")
* - price: The price per unit (required when set)
* - vat_rate: The VAT rate (required when set)
* - payload: The payload (optional)
* - ends_at: The end date (optional)
* @throws Throwable
*/
public function update(array $attributes): self
{
return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/subscriptions/%s', $this->id), $attributes)))
->setBillable($this->billable);
}
/** /**
* Force given subscription to check out (trusted apps only). * Force given subscription to check out (trusted apps only).
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function checkout(): self public function checkout(): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/subscriptions/%s/checkout', $this->id)))) return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/subscriptions/%s/checkout', $this->id))))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Revoke a given running subscription from the current user. * Revoke a given running subscription from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function revoke(): self public function revoke(bool $refund = false): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/subscriptions/%s/revoke', $this->id)))) $attributes = [
'refund' => $refund,
];
return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/subscriptions/%s/revoke', $this->id), $attributes)))
->setBillable($this->billable);
}
/**
* Pause a given running subscription from the current user.
*
* @throws Throwable
*/
public function pause(): self
{
return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/subscriptions/%s/pause', $this->id))))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* Resume a given running subscription from the current user. * Resume a given running subscription from the current user.
* *
* @throws RequestRequiresClientIdException * @throws Throwable
* @throws GuzzleException
*/ */
public function resume(): self public function resume(): self
{ {
return (new self($this->billable->request('PUT', sprintf('v1/subscriptions/%s/resume', $this->id)))) return (new self(fn() => $this->billable->anikeenId()
->request('PUT', sprintf('v1/subscriptions/%s/resume', $this->id))))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/**
* Delete a given subscription from the current user.
*
* @throws RequestRequiresClientIdException
* @throws GuzzleException
*/
public function delete(): bool
{
return $this->billable->request('DELETE', sprintf('v1/subscriptions/%s', $this->id))->success();
}
} }
+19 -22
View File
@@ -3,9 +3,9 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException; use Anikeen\Id\Contracts\AppTokenRepository;
use Anikeen\Id\Result; use Anikeen\Id\Exceptions\ResourceException;
use GuzzleHttp\Exception\GuzzleException; use Throwable;
class Subscriptions extends BaseCollection class Subscriptions extends BaseCollection
{ {
@@ -15,44 +15,41 @@ class Subscriptions extends BaseCollection
* Create a new subscription for the current user. * Create a new subscription for the current user.
* *
* @param array{ * @param array{
* name: null, * group: null|string,
* description: string, * name: string,
* description: null|string,
* unit: string, * unit: string,
* price: float, * price: float,
* vat: null|float, * vat_rate: float,
* payload: null|array, * payload: null|array,
* ends_at: null|string, * ends_at: null|string
* webhook_url: null|string,
* webhook_secret: null|string
* } $attributes The subscription data: * } $attributes The subscription data:
* - group: The group (optional)
* - name: The name * - name: The name
* - description: The description * - description: The description (optional)
* - unit: The unit (e.g. "hour", "day", "week", "month", "year") * - unit: The unit (e.g. "hour", "day", "week", "month", "year")
* - price: The price per unit * - price: The price per unit
* - vat: The VAT (optional) * - 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)
* - webhook_url: The webhook URL (optional) * @throws Throwable
* - webhook_secret: The webhook secret (optional)
* @throws RequestRequiresClientIdException
* @throws GuzzleException
*/ */
public function create(array $attributes): Subscription public function create(array $attributes): Subscription
{ {
return (new Subscription($this->billable->request('POST', 'v1/subscriptions', $attributes))) return (new Subscription(fn() => $this->billable->anikeenId()
->request('POST', 'v1/subscriptions', $attributes)))
->setBillable($this->billable); ->setBillable($this->billable);
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*
* @throws ResourceException
*/ */
public function find(string $id): ?Subscription public function find(string $id): ?Subscription
{ {
$result = $this->billable->request('GET', sprintf('v1/subscriptions/%s', $id)); return (new Subscription(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/subscriptions/%s', $id))))
return $result->success() ->setBillable($this->billable);
? (new Subscription($result))
->setBillable($this->billable)
: null;
} }
} }
+3 -22
View File
@@ -3,37 +3,18 @@
namespace Anikeen\Id\Resources; namespace Anikeen\Id\Resources;
use Anikeen\Id\Concerns\HasBillable; use Anikeen\Id\Concerns\HasBillable;
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
class Transactions extends BaseCollection class Transactions extends BaseCollection
{ {
use HasBillable; use HasBillable;
/**
* Create a new transaction for the current user.
*
* @param array $attributes The attributes for the transaction.
* @throws RequestRequiresClientIdException
* @throws GuzzleException
* @todo Add type hinting for the attributes array.
*/
public function create(array $attributes = []): Transaction
{
return new Transaction($this->billable->request('POST', 'v1/transactions', $attributes));
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function find(string $id): ?Transaction public function find(string $id): ?Transaction
{ {
$result = $this->billable->request('GET', sprintf('v1/transactions/%s', $id)); return (new Transaction(fn() => $this->billable->anikeenId()
->request('GET', sprintf('v1/transactions/%s', $id))))
return $result->success() ->setBillable($this->billable);
? (new Transaction($result))
->setBillable($this->billable)
: null;
} }
} }
+10 -5
View File
@@ -2,6 +2,7 @@
namespace Anikeen\Id\Socialite; namespace Anikeen\Id\Socialite;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Enums\Scope; use Anikeen\Id\Enums\Scope;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -32,11 +33,7 @@ class Provider extends AbstractProvider implements ProviderInterface
*/ */
protected function getBaseUrl(): string protected function getBaseUrl(): string
{ {
$mode = config('services.anikeen.mode') ?? 'production'; return app(AnikeenId::class)->getBaseUrl();
return $mode === 'staging'
? 'https://staging.id.anikeen.com'
: 'https://id.anikeen.com';
} }
/** /**
@@ -98,4 +95,12 @@ class Provider extends AbstractProvider implements ProviderInterface
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
]); ]);
} }
/**
* Returns the user logout url for the provider.
*/
public function getLogoutUrl(string $redirect = null): string
{
return app(AnikeenId::class)->getBaseUrl() . '/logout?redirect=' . urlencode($redirect ?: '/');
}
} }
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace Anikeen\Id\Support;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Contracts\AppTokenRepository;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
use Throwable;
/**
* Sends a request with the app's own token (client credentials). A rejected token is renewed
* once; every failure ends in an ApiException with status and error code.
*/
final class AppRequest
{
/**
* @throws ApiException
*/
public static function send(string $method, string $path, ?array $payload = null, array $query = []): Result
{
$result = self::attempt($method, $path, $payload, $query);
if ($result->status === 401) {
$tokens = app(AppTokenRepository::class);
if (method_exists($tokens, 'forgetAccessToken')) {
$tokens->forgetAccessToken();
$result = self::attempt($method, $path, $payload, $query);
}
}
if (!$result->success()) {
$body = is_object($result->data) ? $result->data : null;
throw new ApiException(
sprintf('Anikeen ID request %s %s failed: %s', $method, $path, $body->message ?? $result->error()),
$result->response()?->getStatusCode() ?? 0,
$body->error ?? null,
$result->exception,
);
}
return $result;
}
/**
* @throws ApiException
*/
private static function attempt(string $method, string $path, ?array $payload, array $query): Result
{
try {
return app(AnikeenId::class)->asApp()->request($method, $path, $payload, $query);
} catch (ApiException $e) {
throw $e;
} catch (GuzzleException|Throwable $e) {
// network errors / timeouts (ConnectException isn't a RequestException) and token errors
throw new ApiException(sprintf('Anikeen ID is not reachable: %s', $e->getMessage()), 0, null, $e);
}
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Anikeen\Id\Webhooks;
/**
* The `type` of webhook events Anikeen ID sends, e.g.
* `match ($event['type']) { EventType::CHECKOUT_COMPLETED => …, … }`.
*/
final class EventType
{
public const ORDER_CREATED = 'order.created';
public const ORDER_COMPLETED = 'order.completed';
public const ORDER_PAYMENT_FAILED = 'order.payment_failed';
public const ORDER_CANCELLED = 'order.cancelled';
public const ORDER_SHIPPED = 'order.shipped';
public const SUBSCRIPTION_CREATED = 'subscription.created';
public const SUBSCRIPTION_ACTIVATED = 'subscription.activated';
public const SUBSCRIPTION_PAUSED = 'subscription.paused';
public const SUBSCRIPTION_RESUMED = 'subscription.resumed';
public const SUBSCRIPTION_CANCELLED = 'subscription.cancelled';
public const SUBSCRIPTION_EXPIRED = 'subscription.expired';
/** The user confirmed a checkout session: all of its subscriptions are running (sent after their subscription.activated). */
public const CHECKOUT_COMPLETED = 'checkout.completed';
/** The user or the app cancelled a checkout session; its drafts were cancelled. */
public const CHECKOUT_CANCELLED = 'checkout.cancelled';
/** A checkout session was not confirmed within 24 hours; its drafts were cancelled. */
public const CHECKOUT_EXPIRED = 'checkout.expired';
public const TEST = 'webhook.test';
/**
* @return list<string>
*/
public static function all(): array
{
return array_values((new \ReflectionClass(self::class))->getConstants());
}
private function __construct()
{
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace Anikeen\Id\Webhooks;
use Anikeen\Id\Exceptions\SignatureVerificationException;
/**
* Verifies webhooks from Anikeen ID, like Stripe's Webhook::constructEvent().
*
* Anikeen ID signs every request with your endpoint's signing secret (whsec_…):
* `Anikeen-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`.
*/
final class Webhook
{
/** Requests older (or newer) than this many seconds are rejected to prevent replays. */
public const DEFAULT_TOLERANCE = 300;
/**
* Verifies the signature and returns the event: ['id', 'type', 'created', 'data' => ['object' => …]].
*
* @param string $payload the raw request body (not re-encoded JSON)
* @param string|null $signatureHeader the Anikeen-Signature header
*
* @throws SignatureVerificationException
*/
public static function constructEvent(string $payload, ?string $signatureHeader, string $secret, int $tolerance = self::DEFAULT_TOLERANCE): array
{
self::verify($payload, $signatureHeader, $secret, $tolerance);
$event = json_decode($payload, true);
if (!is_array($event) || !isset($event['id'], $event['type'])) {
throw new SignatureVerificationException('The webhook payload is not a valid event.');
}
return $event;
}
/**
* @throws SignatureVerificationException
*/
public static function verify(string $payload, ?string $signatureHeader, string $secret, int $tolerance = self::DEFAULT_TOLERANCE): void
{
$timestamp = null;
$signatures = [];
foreach (explode(',', (string) $signatureHeader) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, null);
if ($key === 't' && ctype_digit((string) $value)) {
$timestamp = (int) $value;
} elseif ($key === 'v1' && $value) {
$signatures[] = $value;
}
}
if ($timestamp === null || $signatures === []) {
throw new SignatureVerificationException('The Anikeen-Signature header is missing or malformed.');
}
$expected = hash_hmac('sha256', "{$timestamp}.{$payload}", $secret);
if (!array_filter($signatures, fn (string $signature) => hash_equals($expected, $signature))) {
throw new SignatureVerificationException('The webhook signature does not match. Check the signing secret.');
}
if ($tolerance > 0 && abs(time() - $timestamp) > $tolerance) {
throw new SignatureVerificationException('The webhook timestamp is outside the tolerance.');
}
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Billable;
use Illuminate\Database\Eloquent\Model;
class AppOrdersTest extends TestCase
{
private function owner(): Model
{
$owner = new class extends Model {
use Billable;
protected $guarded = [];
};
$owner->anikeen_id = '01JUSER';
return $owner;
}
private function page(array $orders, int $page = 1, int $last = 1): array
{
return ['data' => $orders, 'meta' => ['current_page' => $page, 'last_page' => $last, 'total' => count($orders)], 'links' => ['next' => null]];
}
private function requestQuery(int $index): array
{
parse_str($this->sent[$index]['request']->getUri()->getQuery(), $query);
return $query;
}
public function test_pending_orders_of_a_user(): void
{
$this->respond(200, $this->page([['id' => 'o1', 'user_id' => '01JUSER', 'status' => 'pending', 'gross_total' => 11.9, 'next_payment_attempt_at' => null, 'payment_attempts' => 4]]));
$orders = $this->owner()->appOrders()->pending();
$this->assertSame('o1', $orders[0]->id);
$this->assertSame(4, $orders[0]->payment_attempts);
$request = $this->sent[0]['request'];
$this->assertSame('GET /api/v1/client/orders Bearer app-token', $request->getMethod() . ' ' . $request->getUri()->getPath() . ' ' . $request->getHeaderLine('Authorization'));
$this->assertSame(['status' => 'pending', 'user_id' => '01JUSER', 'per_page' => '100', 'page' => '1'], $this->requestQuery(0));
}
public function test_pending_orders_of_all_users_follow_pages(): void
{
$this->respond(200, $this->page([['id' => 'o1', 'user_id' => 'a']], 1, 2));
$this->respond(200, $this->page([['id' => 'o2', 'user_id' => 'b']], 2, 2));
$orders = app(AnikeenId::class)->appOrders()->pending(['group' => 'team-1']);
$this->assertSame(['o1', 'o2'], array_map(fn ($o) => $o->id, $orders));
$this->assertSame(['group' => 'team-1', 'status' => 'pending', 'per_page' => '100', 'page' => '2'], $this->requestQuery(1));
}
public function test_find_returns_null_for_unknown_and_other_users_orders(): void
{
$this->respond(404, ['message' => 'Order not found.', 'error' => 'order_not_found']);
$this->respond(200, ['data' => ['id' => 'o1', 'user_id' => 'someone-else']]);
$this->respond(200, ['data' => ['id' => 'o1', 'user_id' => '01JUSER']]);
$orders = $this->owner()->appOrders();
$this->assertNull($orders->find('unknown'));
$this->assertNull($orders->find('o1'));
$this->assertSame('o1', $orders->find('o1')->id);
}
}
+183
View File
@@ -0,0 +1,183 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Billable;
use Anikeen\Id\Exceptions\ApiException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Psr7\Request;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
class AppSubscriptionsTest extends TestCase
{
private function owner(?string $anikeenId = '01JUSER'): Model
{
$owner = new class extends Model {
use Billable;
protected $guarded = [];
};
$owner->anikeen_id = $anikeenId;
$owner->anikeen_id_access_token = 'user-token';
return $owner;
}
private function subscription(array $overrides = []): array
{
return ['data' => ['id' => '01JSUB', 'user_id' => '01JUSER', 'name' => 'Server', 'active' => false, 'cancelled' => false, ...$overrides]];
}
public function test_create_sends_the_user_id_with_the_app_token(): void
{
$this->respond(201, $this->subscription());
$subscription = $this->owner()->appSubscriptions()->create(['group' => 'team-1', 'name' => 'Server', 'unit' => 'hour', 'price' => '0.0137', 'idempotency_key' => 'server:1']);
$request = $this->sent[0]['request'];
$this->assertSame('POST', $request->getMethod());
$this->assertSame('/api/v1/client/subscriptions', $request->getUri()->getPath());
$this->assertSame('Bearer app-token', $request->getHeaderLine('Authorization'));
$this->assertSame(['group' => 'team-1', 'name' => 'Server', 'unit' => 'hour', 'price' => '0.0137', 'idempotency_key' => 'server:1', 'user_id' => '01JUSER'], $this->sentJson(0));
$this->assertSame('01JSUB', $subscription->id);
}
public function test_nothing_is_requested_until_a_method_is_called(): void
{
$this->owner()->appSubscriptions();
$this->assertCount(0, $this->sent);
}
public function test_actions_use_the_app_endpoints(): void
{
$this->respond(201, $this->subscription());
$this->respond(200, $this->subscription(['active' => true]));
$this->respond(200, $this->subscription(['active' => true, 'autorenew' => false]));
$this->respond(200, $this->subscription(['active' => true, 'autorenew' => true]));
$this->respond(200, $this->subscription(['cancelled' => true]));
$subscription = $this->owner()->appSubscriptions()->create(['name' => 'Server', 'unit' => 'hour', 'price' => 1]);
$this->assertTrue($subscription->checkout()->active);
$this->assertFalse($subscription->pause()->autorenew);
$this->assertTrue($subscription->resume()->autorenew);
$this->assertTrue($subscription->revoke(refund: true)->cancelled);
$this->assertSame([
'POST /api/v1/client/subscriptions',
'PUT /api/v1/client/subscriptions/01JSUB/checkout',
'PUT /api/v1/client/subscriptions/01JSUB/pause',
'PUT /api/v1/client/subscriptions/01JSUB/resume',
'PUT /api/v1/client/subscriptions/01JSUB/revoke',
], array_map(fn ($entry) => $entry['request']->getMethod() . ' ' . $entry['request']->getUri()->getPath(), $this->sent));
$this->assertSame(['refund' => true], $this->sentJson(4));
}
public function test_a_running_service_is_checked_out_from_its_start(): void
{
$this->respond(201, $this->subscription());
$this->respond(200, $this->subscription(['active' => true]));
$subscription = $this->owner()->appSubscriptions()->create(['name' => '.de TLD', 'unit' => 'year', 'price' => '5.19']);
$subscription->checkout(new \DateTimeImmutable('2026-05-19 11:33:58', new \DateTimeZone('UTC')));
$this->assertSame(['starts_at' => '2026-05-19T11:33:58+00:00'], $this->sentJson(1));
}
public function test_errors_carry_status_and_error_code(): void
{
$this->respond(409, ['message' => 'Product subscription has already been cancelled.', 'error' => 'already_cancelled']);
try {
$this->owner()->appSubscriptions()->create(['name' => 'Server', 'unit' => 'hour', 'price' => 1]);
$this->fail('Expected an ApiException.');
} catch (ApiException $e) {
$this->assertSame(409, $e->status);
$this->assertSame('already_cancelled', $e->error);
$this->assertTrue($e->isConflict());
$this->assertFalse($e->isTemporary());
}
}
public function test_find_returns_null_for_unknown_subscriptions_and_other_users(): void
{
$this->respond(404, ['message' => 'Subscription not found.', 'error' => 'subscription_not_found']);
$this->respond(200, $this->subscription(['user_id' => '01JSOMEONEELSE']));
$this->respond(200, $this->subscription());
$subscriptions = $this->owner()->appSubscriptions();
$this->assertNull($subscriptions->find('01JUNKNOWN'));
$this->assertNull($subscriptions->find('01JSUB'));
$this->assertSame('01JSUB', $subscriptions->find('01JSUB')->id);
}
public function test_all_follows_pages_and_filters_by_user(): void
{
$this->respond(200, ['data' => [['id' => 'a', 'user_id' => '01JUSER']], 'meta' => ['current_page' => 1, 'last_page' => 2, 'total' => 2], 'links' => ['next' => null]]);
$this->respond(200, ['data' => [['id' => 'b', 'user_id' => '01JUSER']], 'meta' => ['current_page' => 2, 'last_page' => 2, 'total' => 2], 'links' => ['next' => null]]);
$all = $this->owner()->appSubscriptions()->all(['group' => 'team-1', 'active' => true]);
$this->assertSame(['a', 'b'], array_map(fn ($s) => $s->id, $all));
parse_str($this->sent[0]['request']->getUri()->getQuery(), $query);
$this->assertSame(['group' => 'team-1', 'active' => '1', 'user_id' => '01JUSER', 'per_page' => '100', 'page' => '1'], $query);
}
public function test_a_rejected_app_token_is_renewed_once(): void
{
$this->respond(401, ['message' => 'Unauthenticated.']);
$this->respond(200, ['data' => [], 'meta' => ['last_page' => 1], 'links' => ['next' => null]]);
$this->assertSame([], $this->owner()->appSubscriptions()->all());
$this->assertSame('Bearer app-token', $this->sent[0]['request']->getHeaderLine('Authorization'));
$this->assertSame('Bearer fresh-app-token', $this->sent[1]['request']->getHeaderLine('Authorization'));
}
public function test_an_unreachable_service_is_a_temporary_api_exception(): void
{
$this->http->append(new ConnectException('Connection refused', new Request('GET', 'v1/client/subscriptions')));
try {
$this->owner()->appSubscriptions()->all();
$this->fail('Expected an ApiException.');
} catch (ApiException $e) {
$this->assertSame(0, $e->status);
$this->assertTrue($e->isTemporary());
}
}
public function test_the_shared_client_keeps_the_users_token(): void
{
$this->respond(200, ['data' => [], 'meta' => ['last_page' => 1], 'links' => ['next' => null]]);
app(AnikeenId::class)->withToken('user-token');
$this->owner()->appSubscriptions()->all();
$this->assertSame('user-token', app(AnikeenId::class)->getToken());
}
public function test_the_user_id_field_is_configurable(): void
{
AnikeenId::useUserIdField('id_service_user');
$owner = $this->owner(null);
$owner->id_service_user = '01JOTHER';
try {
$this->assertSame('01JOTHER', $owner->appSubscriptions()->userId());
} finally {
AnikeenId::useUserIdField('anikeen_id');
}
}
public function test_a_missing_user_id_is_reported(): void
{
$this->expectException(InvalidArgumentException::class);
$this->owner(null)->appSubscriptions()->create(['name' => 'Server', 'unit' => 'hour', 'price' => 1]);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\Billable;
use Illuminate\Database\Eloquent\Model;
class BillableModelTest extends TestCase
{
public function test_cached_api_results_are_not_model_attributes(): void
{
$user = new class extends Model {
use Billable;
protected $guarded = [];
public function cacheAll(): void
{
foreach (['addresses', 'countries', 'defaultPaymentMethod', 'invoices', 'orders', 'paymentMethods', 'subscriptions', 'transactions', 'userData'] as $name) {
$this->{$name.'Cache'} = 'cached';
}
}
};
$user->email = 'ada@example.com';
$user->cacheAll();
// save() would otherwise write them as columns ("no such column: ordersCache")
$this->assertSame(['email' => 'ada@example.com'], $user->getAttributes());
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\Billable;
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
use Illuminate\Database\Eloquent\Model;
class CheckoutConfirmationTest extends TestCase
{
private function owner(): Model
{
$owner = new class extends Model {
use Billable;
protected $guarded = [];
};
$owner->anikeen_id = '01JUSER';
$owner->anikeen_id_access_token = 'user-token';
return $owner;
}
public function test_a_draft_order_links_to_its_confirmation_with_the_return_url(): void
{
$this->respond(200, ['data' => []]); // orders() loads the list first
$this->respond(201, ['data' => ['id' => '01JORD', 'status' => 'draft', 'confirmation_url' => 'https://id.anikeen.com/checkout/orders/01JORD']]);
$order = $this->owner()->orders()->create(['billing_address_id' => '01JADDR', 'items' => []]);
$this->assertSame('https://id.anikeen.com/checkout/orders/01JORD', $order->confirmationUrl());
$this->assertSame(
'https://id.anikeen.com/checkout/orders/01JORD?return_url=https%3A%2F%2Fshop.test%2Fdone%3Fcart%3D1',
$order->confirmationUrl('https://shop.test/done?cart=1'),
);
$this->assertSame('POST /api/v1/orders', $this->sent[1]['request']->getMethod() . ' ' . $this->sent[1]['request']->getUri()->getPath());
}
public function test_checked_out_bookings_have_no_confirmation_url(): void
{
$this->respond(200, ['data' => []]);
$this->respond(201, ['data' => ['id' => '01JORD', 'status' => 'completed', 'confirmation_url' => null]]);
$this->assertNull($this->owner()->orders()->create([])->confirmationUrl('https://shop.test/done'));
}
public function test_checking_out_a_draft_as_a_third_party_app_points_to_the_confirmation(): void
{
$this->respond(200, ['data' => []]); // subscriptions() loads the list first
$this->respond(201, ['data' => ['id' => '01JSUB', 'active' => false, 'confirmation_url' => 'https://id.anikeen.com/checkout/subscriptions/01JSUB']]);
$this->respond(403, ['message' => 'The user has to confirm this on Anikeen ID.', 'error' => 'confirmation_required', 'confirmation_url' => 'https://id.anikeen.com/checkout/subscriptions/01JSUB']);
$subscription = $this->owner()->subscriptions()->create(['name' => 'Pro', 'unit' => 'month', 'price' => 4.99]);
try {
$subscription->checkout();
$this->fail('Expected a ConfirmationRequiredException.');
} catch (ConfirmationRequiredException $e) {
$this->assertSame(403, $e->getCode());
$this->assertSame('https://id.anikeen.com/checkout/subscriptions/01JSUB', $e->confirmationUrl);
}
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Billable;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Resources\AppCheckoutSession;
use Anikeen\Id\Resources\AppSubscription;
use Anikeen\Id\Resources\CheckoutSession;
use Anikeen\Id\Webhooks\EventType;
use Anikeen\Id\Webhooks\Webhook;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
class CheckoutSessionsTest extends TestCase
{
private function owner(): Model
{
$owner = new class extends Model {
use Billable;
protected $guarded = [];
};
$owner->anikeen_id = '01JUSER';
$owner->anikeen_id_access_token = 'user-token';
return $owner;
}
private function sessionData(array $overrides = []): array
{
return ['data' => [
'object' => 'checkout_session',
'id' => '01JCS',
'user_id' => '01JUSER',
'status' => 'open',
'return_url' => 'https://console.test/builder/done',
'metadata' => ['cart' => '42'],
'confirmation_url' => 'https://id.anikeen.com/checkout/sessions/01JCS',
'subscription_ids' => ['01JS1', '01JS2'],
'subscriptions' => [
['id' => '01JS1', 'user_id' => '01JUSER', 'name' => 'Cloud Server S', 'active' => false, 'payload' => ['product' => 'server-s']],
['id' => '01JS2', 'user_id' => '01JUSER', 'name' => 'Backup', 'active' => false],
],
...$overrides,
]];
}
private function request(int $index): string
{
$request = $this->sent[$index]['request'];
return $request->getMethod() . ' ' . $request->getUri()->getPath() . ' ' . $request->getHeaderLine('Authorization');
}
public function test_a_trusted_app_opens_a_session_with_its_own_token(): void
{
$this->respond(201, $this->sessionData());
$session = $this->owner()->appCheckoutSessions()->create([
'return_url' => 'https://console.test/builder/done',
'idempotency_key' => 'cart:42',
'subscriptions' => [
['group' => 'team-1', 'name' => 'Cloud Server S', 'unit' => 'hour', 'price' => '0.0137', 'payload' => ['product' => 'server-s']],
['id' => '01JS2'],
],
]);
$this->assertSame('POST /api/v1/client/checkout-sessions Bearer app-token', $this->request(0));
$this->assertSame('01JUSER', $this->sentJson(0)['user_id']);
$this->assertSame([['group' => 'team-1', 'name' => 'Cloud Server S', 'unit' => 'hour', 'price' => '0.0137', 'payload' => ['product' => 'server-s']], ['id' => '01JS2']], $this->sentJson(0)['subscriptions']);
$this->assertInstanceOf(AppCheckoutSession::class, $session);
$this->assertSame('https://id.anikeen.com/checkout/sessions/01JCS', $session->confirmationUrl());
$this->assertTrue($session->isOpen());
$this->assertSame(['01JS1', '01JS2'], $session->subscriptionIds());
$this->assertContainsOnlyInstancesOf(AppSubscription::class, $session->subscriptions());
$this->assertSame('server-s', $session->subscriptions()[0]->payload->product);
$this->assertSame('42', $session->metadata->cart);
}
public function test_the_app_finds_refreshes_and_cancels_sessions(): void
{
$this->respond(200, $this->sessionData(['status' => 'completed', 'confirmation_url' => null]));
$this->respond(200, $this->sessionData(['user_id' => 'someone-else']));
$this->respond(404, ['message' => 'Checkout session not found.', 'error' => 'checkout_session_not_found']);
$this->respond(200, $this->sessionData());
$this->respond(200, $this->sessionData(['status' => 'cancelled', 'confirmation_url' => null]));
$this->respond(409, ['message' => 'The checkout session is cancelled.', 'error' => 'checkout_session_cancelled']);
$sessions = $this->owner()->appCheckoutSessions();
$completed = $sessions->find('01JCS');
$this->assertTrue($completed->isCompleted());
$this->assertNull($completed->confirmationUrl());
$this->assertNull($sessions->find('01JCS'), 'another user\'s session');
$this->assertNull($sessions->find('unknown'));
$session = app(AnikeenId::class)->appCheckoutSessions()->find('01JCS'); // e.g. from a webhook
$session->cancel();
$this->assertTrue($session->isCancelled());
$this->assertSame('POST /api/v1/client/checkout-sessions/01JCS/cancel Bearer app-token', $this->request(4));
try {
$session->cancel();
$this->fail('Expected an ApiException.');
} catch (ApiException $e) {
$this->assertTrue($e->isConflict());
$this->assertSame('checkout_session_cancelled', $e->error);
}
}
public function test_without_a_billable_the_user_id_is_required(): void
{
$this->expectException(InvalidArgumentException::class);
app(AnikeenId::class)->appCheckoutSessions()->create(['subscriptions' => [['id' => '01JS1']]]);
}
public function test_any_app_opens_a_session_with_the_users_token(): void
{
$this->respond(201, $this->sessionData());
$this->respond(200, $this->sessionData(['status' => 'expired', 'confirmation_url' => null]));
$this->respond(404, ['message' => 'Checkout session not found.', 'error' => 'checkout_session_not_found']);
$user = $this->owner();
$session = $user->checkoutSessions()->create(['subscriptions' => [['name' => 'Pro', 'unit' => 'month', 'price' => 4.99]]]);
$this->assertSame('POST /api/v1/checkout-sessions Bearer user-token', $this->request(0));
$this->assertArrayNotHasKey('user_id', $this->sentJson(0));
$this->assertInstanceOf(CheckoutSession::class, $session);
$this->assertSame('https://id.anikeen.com/checkout/sessions/01JCS', $session->confirmationUrl());
$this->assertSame(['01JS1', '01JS2'], $session->subscriptionIds());
$expired = $user->checkoutSessions()->find('01JCS');
$this->assertTrue($expired->isCancelled());
$this->assertSame(CheckoutSession::STATUS_EXPIRED, $expired->status);
$this->assertNull($user->checkoutSessions()->find('unknown'));
}
public function test_nothing_is_requested_until_a_method_is_called(): void
{
$this->owner()->checkoutSessions();
$this->owner()->appCheckoutSessions();
$this->assertCount(0, $this->sent);
}
public function test_checkout_webhooks_carry_the_session(): void
{
$payload = json_encode(['id' => '01JEV', 'type' => 'checkout.completed', 'created' => time(), 'data' => ['object' => $this->sessionData(['status' => 'completed'])['data']]]);
$timestamp = time();
$signature = 't=' . $timestamp . ',v1=' . hash_hmac('sha256', "{$timestamp}.{$payload}", 'whsec_test');
$event = Webhook::constructEvent($payload, $signature, 'whsec_test');
$this->assertSame(EventType::CHECKOUT_COMPLETED, $event['type']);
$this->assertSame(['01JS1', '01JS2'], $event['data']['object']['subscription_ids']);
$this->assertContains('checkout.expired', EventType::all());
$this->assertContains('subscription.activated', EventType::all());
}
}
+210
View File
@@ -0,0 +1,210 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Billable;
use Illuminate\Database\Eloquent\Model;
/**
* Every package method has to call an endpoint that exists in Anikeen ID, with the right token.
*/
class EndpointsTest extends TestCase
{
private function owner(): Model
{
$owner = new class extends Model {
use Billable;
protected $guarded = [];
};
$owner->anikeen_id = '01JUSER';
$owner->anikeen_id_access_token = 'user-token';
return $owner;
}
private function sentCall(int $index): string
{
$request = $this->sent[$index]['request'];
return $request->getMethod() . ' ' . $request->getUri()->getPath() . ' ' . $request->getHeaderLine('Authorization');
}
private function list(array $items = []): array
{
return ['data' => $items, 'meta' => ['current_page' => 1, 'last_page' => 1, 'total' => count($items)], 'links' => ['next' => null]];
}
public function test_charge_uses_the_versioned_endpoint_without_stripe_options(): void
{
$this->respond(201, ['data' => ['id' => 'tx1', 'status' => 'succeeded']]);
$this->owner()->charge(10, 'pm_1', ['transfer_data' => ['destination' => 'acct_x']]);
$this->assertSame('POST /api/v1/billing/charge Bearer user-token', $this->sentCall(0));
$this->assertSame(['amount' => 10, 'payment_method_id' => 'pm_1'], $this->sentJson(0));
}
public function test_billing_overview(): void
{
$this->respond(200, ['data' => ['current_charges' => 11.9, 'has_default_payment_method' => true]]);
$this->assertSame(11.9, $this->owner()->billingOverview()->current_charges);
$this->assertSame('GET /api/v1/billing Bearer user-token', $this->sentCall(0));
}
public function test_invoice_download_url_is_read_not_updated(): void
{
$this->respond(200, $this->list([['id' => 'inv1']]));
$this->respond(200, ['data' => ['id' => 'inv1', 'temporary_url' => 'https://s3/inv1.pdf']]);
$this->respond(200, ['data' => ['id' => 'inv1', 'temporary_url' => 'https://s3/inv1.pdf']]);
$url = $this->owner()->invoices()->find('inv1')->getInvoiceTemporaryUrl();
$this->assertSame('https://s3/inv1.pdf', $url);
$this->assertSame('GET /api/v1/invoices/inv1 Bearer user-token', $this->sentCall(2));
}
public function test_order_items_are_created_on_the_items_endpoint(): void
{
$this->respond(200, $this->list()); // GET v1/orders
$this->respond(200, ['data' => ['id' => 'order1', 'status' => 'draft']]); // GET v1/orders/order1
$this->respond(200, $this->list()); // GET v1/orders/order1/items
$this->respond(201, ['data' => [['id' => 'item1', 'name' => 'Domain']]]); // POST v1/orders/order1/items
$created = $this->owner()->orders()->find('order1')->orderItems()
->create('order1', ['items' => [['type' => 'digital', 'name' => 'Domain', 'price' => 10, 'unit' => 'year', 'units' => 1]]]);
$this->assertSame('item1', $created->id);
$this->assertSame('POST /api/v1/orders/order1/items Bearer user-token', $this->sentCall(3));
}
public function test_create_user_uses_the_app_token_and_admin_endpoint(): void
{
$this->respond(200, ['data' => ['id' => '01JNEW']]);
app(AnikeenId::class)->createUser(['first_name' => 'Erika', 'last_name' => 'Mustermann', 'email' => 'erika@example.com', 'password' => 'secret-123']);
$this->assertSame('POST /api/v1/admin/users Bearer app-token', $this->sentCall(0));
$this->assertSame(['email' => 'erika@example.com', 'password' => 'secret-123', 'name' => 'Erika Mustermann', 'password_confirmation' => 'secret-123'], $this->sentJson(0));
}
public function test_email_check_and_socialite_users(): void
{
$this->respond(200, ['data' => ['exists' => true]]);
$this->respond(200, ['data' => ['id' => '01JUSER']]);
$this->assertTrue(app(AnikeenId::class)->isEmailExisting('erika@example.com')->data->exists);
app(AnikeenId::class)->findOrCreateSocialiteUser('twitch', '123', 'streamer@example.com');
$this->assertSame('POST /api/v1/admin/users/check Bearer app-token', $this->sentCall(0));
$this->assertSame('POST /api/v1/admin/users/socialite Bearer app-token', $this->sentCall(1));
$this->assertSame(['provider' => 'twitch', 'provider_id' => '123', 'email' => 'streamer@example.com'], $this->sentJson(1));
}
public function test_ssh_keys_of_a_user_for_apps_are_not_cached_across_users(): void
{
$this->respond(200, ['data' => [['id' => 'k1', 'name' => 'A']]]);
$this->respond(200, ['data' => [['id' => 'k2', 'name' => 'B']]]);
$first = app(AnikeenId::class)->sshKeysByUserId('01JA');
$second = app(AnikeenId::class)->sshKeysByUserId('01JB');
$this->assertSame('k1', $first->toArray()[0]->id);
$this->assertSame('k2', $second->toArray()[0]->id);
$this->assertSame('GET /api/v1/client/users/01JA/ssh-keys Bearer app-token', $this->sentCall(0));
$this->assertSame('GET /api/v1/client/users/01JB/ssh-keys Bearer app-token', $this->sentCall(1));
}
public function test_users_manage_their_own_ssh_keys(): void
{
$this->respond(200, $this->list());
$this->respond(201, ['data' => ['id' => 'k1', 'name' => 'Laptop']]);
$this->respond(200, ['data' => ['id' => 'k1', 'name' => 'Work']]);
$this->respond(204);
$keys = $this->owner()->sshKeys();
$key = $keys->create('ssh-ed25519 AAAA… erika@laptop', 'Laptop');
$renamed = $key->update('Work');
$this->assertSame('Work', $renamed->name);
$this->assertTrue($renamed->delete());
$this->assertSame([
'GET /api/v1/ssh-keys Bearer user-token',
'POST /api/v1/ssh-keys Bearer user-token',
'PUT /api/v1/ssh-keys/k1 Bearer user-token',
'DELETE /api/v1/ssh-keys/k1 Bearer user-token',
], array_map(fn ($i) => $this->sentCall($i), range(0, 3)));
}
public function test_payment_methods_can_be_deleted(): void
{
$this->respond(200, ['data' => [['id' => 'pm_1']]]);
$this->respond(200, ['data' => ['id' => 'pm_1', 'type' => 'card']]);
$this->respond(204);
$this->assertTrue($this->owner()->paymentMethods()->find('pm_1')->delete());
$this->assertSame('DELETE /api/v1/payment-methods/pm_1 Bearer user-token', $this->sentCall(2));
}
public function test_products_and_boxes(): void
{
$this->respond(200, ['data' => [['id' => 'p1']]]);
$this->respond(200, [['id' => 'b1']]);
app(AnikeenId::class)->products();
app(AnikeenId::class)->boxes();
$this->assertStringStartsWith('GET /api/v1/products', $this->sentCall(0));
$this->assertStringStartsWith('GET /api/v1/boxes', $this->sentCall(1));
}
public function test_shipping_labels_use_the_app_token(): void
{
foreach (range(1, 5) as $i) {
$this->respond(200, ['data' => []]);
}
$this->http->append(new \GuzzleHttp\Psr7\Response(200, ['Content-Type' => 'application/pdf'], '%PDF-1.7'));
$id = app(AnikeenId::class);
$id->shippingLabels();
$id->shippingLabel('l1');
$id->issueShippingLabel(['box' => ['id' => 'b1'], 'weight' => 20, 'address' => [], 'billed_user_id' => '01JUSER', 'test' => true]);
$id->shipShippingLabel(['0A', 'FF']);
$id->shippingPriceList();
$pdf = $id->shippingLabelPdf('l1');
$this->assertSame('%PDF-1.7', $pdf);
$this->assertSame([
'GET /api/v1/admin/shipping-labels Bearer app-token',
'GET /api/v1/admin/shipping-labels/l1 Bearer app-token',
'POST /api/v1/admin/shipping-labels/issue Bearer app-token',
'POST /api/v1/admin/shipping-labels/ship Bearer app-token',
'GET /api/v1/admin/shipping-labels/price-list Bearer app-token',
'GET /api/v1/admin/shipping-labels/l1/pdf Bearer app-token',
], array_map(fn ($i) => $this->sentCall($i), range(0, 5)));
}
public function test_orders_and_transactions_for_users(): void
{
$this->respond(201, ['data' => ['id' => 'o1']]);
$this->respond(201, ['data' => ['id' => 'tx1']]);
app(AnikeenId::class)->createOrderForUser('01JUSER', ['items' => [], 'checkout' => true]);
app(AnikeenId::class)->createTransactionForUser('01JUSER', ['status' => 'succeeded', 'type' => 'deposit', 'amount' => '9.99', 'currency_iso' => 'EUR', 'created_at' => '2026-10-26']);
$this->assertSame('POST /api/v1/admin/orders Bearer app-token', $this->sentCall(0));
$this->assertSame('01JUSER', $this->sentJson(0)['user_id']);
$this->assertSame('POST /api/v1/admin/transactions Bearer app-token', $this->sentCall(1));
}
public function test_order_preview_maps_the_country_into_the_billing_address(): void
{
$this->respond(200, ['data' => ['gross_total' => 11.9]]);
app(AnikeenId::class)->createOrderPreview(['country_iso' => 'DE', 'items' => []]);
$this->assertSame(['items' => [], 'billing_address' => ['country_iso' => 'DE']], $this->sentJson(0));
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\Billable;
use Anikeen\Id\Exceptions\ResourceException;
use GuzzleHttp\Psr7\Response;
use Illuminate\Database\Eloquent\Model;
class ShipmentsTest extends TestCase
{
private function owner(): Model
{
$owner = new class extends Model {
use Billable;
protected $guarded = [];
};
$owner->anikeen_id = '01JUSER';
$owner->anikeen_id_access_token = 'user-token';
return $owner;
}
private function order(): \Anikeen\Id\Resources\Order
{
$this->respond(200, ['data' => [], 'meta' => ['current_page' => 1, 'last_page' => 1, 'total' => 0], 'links' => ['next' => null]]);
$this->respond(200, ['data' => ['id' => 'ord1', 'status' => 'completed']]);
return $this->owner()->orders()->find('ord1');
}
private function sentCall(int $index): string
{
$request = $this->sent[$index]['request'];
return $request->getMethod() . ' ' . $request->getUri()->getPath() . ' ' . $request->getHeaderLine('Authorization');
}
public function test_an_order_is_shipped_with_carrier_tracking_and_items(): void
{
$order = $this->order();
$this->respond(200, ['data' => []]);
$this->respond(201, ['data' => ['id' => 'shp1', 'number' => 'LS-2026-0001', 'order_id' => 'ord1', 'carrier' => 'DHL']]);
$shipment = $order->shipments()->create([
'carrier' => 'DHL',
'tracking_number' => '0034',
'items' => [['order_item_id' => 'item1', 'units' => 1]],
]);
$this->assertSame('LS-2026-0001', $shipment->number);
$this->assertSame('GET /api/v1/orders/ord1/shipments Bearer user-token', $this->sentCall(2));
$this->assertSame('POST /api/v1/orders/ord1/shipments Bearer user-token', $this->sentCall(3));
$this->assertSame(['carrier' => 'DHL', 'tracking_number' => '0034', 'items' => [['order_item_id' => 'item1', 'units' => 1]]], $this->sentJson(3));
}
public function test_shipments_are_listed_and_the_delivery_note_is_downloaded(): void
{
$order = $this->order();
$this->respond(200, ['data' => [['id' => 'shp1', 'number' => 'LS-2026-0001']]]);
$this->respond(200, ['data' => ['id' => 'shp1', 'number' => 'LS-2026-0001', 'order_id' => 'ord1']]);
$this->http->append(new Response(200, ['Content-Type' => 'application/pdf'], '%PDF-1.7 test'));
$shipments = $order->shipments();
$this->assertSame('LS-2026-0001', $shipments->toArray()[0]->number);
$pdf = $shipments->find('shp1')->deliveryNote();
$this->assertSame('%PDF-1.7 test', $pdf);
$this->assertSame('GET /api/v1/orders/ord1/shipments/shp1/delivery-note Bearer user-token', $this->sentCall(4));
}
public function test_refusals_keep_their_status(): void
{
$order = $this->order();
$this->respond(200, ['data' => []]);
$this->respond(409, ['message' => 'Only paid orders can be shipped.', 'error' => 'order_not_paid']);
try {
$order->shipments()->create();
$this->fail('expected a ResourceException');
} catch (ResourceException $e) {
$this->assertSame(409, $e->getCode());
$this->assertStringContainsString('Only paid orders can be shipped', $e->getMessage());
}
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Contracts\AppTokenRepository;
use Anikeen\Id\Providers\AnikeenIdServiceProvider;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
use Orchestra\Testbench\TestCase as Orchestra;
abstract class TestCase extends Orchestra
{
protected MockHandler $http;
/** @var list<array{request: \Psr\Http\Message\RequestInterface}> */
protected array $sent = [];
protected function getPackageProviders($app): array
{
return [AnikeenIdServiceProvider::class];
}
protected function setUp(): void
{
parent::setUp();
config(['services.anikeen.client_id' => 'app-client', 'services.anikeen.client_secret' => 'secret']);
$this->http = new MockHandler();
$stack = HandlerStack::create($this->http);
$stack->push(Middleware::history($this->sent));
$this->app->instance(AnikeenId::class, (new AnikeenId())->setHttpClient(new Client(['handler' => $stack, 'base_uri' => 'https://id.test/api/'])));
$this->app->instance(AppTokenRepository::class, new class implements AppTokenRepository {
public int $forgotten = 0;
public function getAccessToken(): string
{
return $this->forgotten ? 'fresh-app-token' : 'app-token';
}
public function forgetAccessToken(): void
{
$this->forgotten++;
}
});
}
protected function respond(int $status, array $body = []): void
{
$this->http->append(new Response($status, ['Content-Type' => 'application/json'], json_encode($body)));
}
protected function sentJson(int $index): array
{
return json_decode((string) $this->sent[$index]['request']->getBody(), true) ?? [];
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace Anikeen\Id\Tests;
use Anikeen\Id\Exceptions\SignatureVerificationException;
use Anikeen\Id\Webhooks\Webhook;
class WebhookTest extends TestCase
{
private string $secret = 'whsec_test';
private string $payload = '{"id":"01JEVT","type":"order.completed","created":1790000000,"data":{"object":{"id":"01JORD"}}}';
private function header(?int $timestamp = null, ?string $secret = null): string
{
$timestamp ??= time();
return "t={$timestamp},v1=" . hash_hmac('sha256', "{$timestamp}.{$this->payload}", $secret ?? $this->secret);
}
public function test_a_signed_event_is_returned(): void
{
$event = Webhook::constructEvent($this->payload, $this->header(), $this->secret);
$this->assertSame('order.completed', $event['type']);
$this->assertSame('01JORD', $event['data']['object']['id']);
}
public function test_a_wrong_secret_is_rejected(): void
{
$this->expectException(SignatureVerificationException::class);
Webhook::constructEvent($this->payload, $this->header(secret: 'whsec_other'), $this->secret);
}
public function test_a_changed_body_is_rejected(): void
{
$this->expectException(SignatureVerificationException::class);
Webhook::constructEvent(str_replace('01JORD', '01JXXX', $this->payload), $this->header(), $this->secret);
}
public function test_old_requests_are_rejected(): void
{
$this->expectException(SignatureVerificationException::class);
Webhook::constructEvent($this->payload, $this->header(time() - 600), $this->secret);
}
public function test_a_missing_header_is_rejected(): void
{
$this->expectException(SignatureVerificationException::class);
Webhook::constructEvent($this->payload, null, $this->secret);
}
}