mirror of
https://github.com/anikeen-com/id.git
synced 2026-11-04 22:59:41 +00:00
Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce820cd198
|
||
|
|
2faccac0f4
|
||
|
|
e3e59fb8a4
|
||
|
|
26716e7bba
|
||
|
|
2acbef72c8
|
||
|
|
396eb889c4 | ||
|
|
dc29eb2844
|
||
|
|
b074ec3c0c | ||
|
|
c2493b76fd
|
||
|
|
285594e7e9 | ||
|
|
34f6854bdd
|
||
|
|
3acd36ca29
|
||
|
|
a0470111fa | ||
|
|
934b1c5c3f
|
||
|
|
6a568a5354 | ||
|
|
5349ee81f6
|
||
|
|
60b4b80f17 | ||
|
|
1f645b50bc
|
||
|
|
9731dd36ca | ||
|
|
be59602b30
|
||
|
|
fd96e559af
|
||
|
|
d6e6684d00 | ||
|
|
68132e7026 | ||
|
|
5c09089822
|
||
|
|
526b65cb5c
|
||
|
|
f20a12e6da
|
||
|
|
0fce38f48a | ||
|
|
c4a42b4ddc
|
||
|
|
a1707e9189 | ||
|
|
820f1b37cc
|
||
|
|
9a6f40ad99 | ||
|
|
9613d31a8d
|
||
|
|
8de737641e
|
||
|
|
9c3f9344a0 | ||
|
|
a7ec7aa908 | ||
|
|
4555efa80c | ||
|
|
4f78e32af1 | ||
|
|
bc9c202c3b | ||
|
|
cecf8560ff | ||
|
|
25248e7822 | ||
|
|
c641ec725d | ||
|
|
8eb0c25582 | ||
|
|
30ac4ae4f9 | ||
|
|
e1a6af11a3 | ||
|
|
bb5df7f115 | ||
|
|
297404b05d | ||
|
|
5ab57dcdfe | ||
|
|
0f14fa1b4c | ||
|
|
437e78770c | ||
|
|
0dbb27fc94 | ||
|
|
8232de4003 | ||
|
|
ac3e28f67f | ||
|
|
63e3f0a4a2
|
||
|
|
1d2119a32b
|
||
|
|
1725ec68de
|
||
|
|
dcda4b990e
|
||
|
|
937fde603b
|
||
|
|
80b1f003b2
|
||
|
|
aff901de4e
|
||
|
|
92eadcca08
|
||
|
|
8b874f540c
|
||
|
|
3bcebd9d45
|
||
|
|
71663bffd8
|
||
|
|
5b2b3c72cc
|
||
|
|
235918f0c0
|
||
|
|
4b23f6ddbb
|
||
|
|
85702fcb2c
|
||
|
|
65d4b12006
|
||
|
|
5d621b7cdc
|
||
|
|
4d6fe7c325
|
||
|
|
d447a88430
|
||
|
|
d9a330222b
|
||
|
|
21946e3a22
|
||
|
|
1b96b87e1d
|
||
|
|
7f908f4e6a
|
No files matched your search
@@ -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
|
||||
@@ -0,0 +1,64 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for Claude Code (and other contributors) working in this repository.
|
||||
|
||||
## What this is
|
||||
|
||||
`anikeen/id` is the public PHP client for the Anikeen ID API, shipped as a Laravel package
|
||||
(Laravel 11–13, PHP 8.2+). It covers OAuth/Socialite login, an API token guard, and the billing
|
||||
API (subscriptions, orders, checkout sessions, shipments, invoices, webhooks). This is a public
|
||||
repo published on Packagist: never commit secrets, internal hostnames or customer data.
|
||||
|
||||
## Commands
|
||||
|
||||
```shell
|
||||
composer install
|
||||
composer test # vendor/bin/phpunit
|
||||
vendor/bin/phpunit --filter AppSubscriptionsTest
|
||||
composer docs # regenerate README.md from README.stub
|
||||
```
|
||||
|
||||
CI (`.github/workflows/tests.yml`) runs PHPUnit on PHP 8.3 and 8.4.
|
||||
|
||||
## Layout
|
||||
|
||||
- `src/Id/AnikeenId.php` – the API client (singleton, facade `AnikeenId`). Reads
|
||||
`config('services.anikeen.*')`; `mode=staging` switches to the staging base URL unless
|
||||
`base_url` is set. `request()` wraps Guzzle and returns a `Result`.
|
||||
- `src/Id/Billable.php` – trait for the app's user model; composes the `Concerns/Manages*` traits.
|
||||
Its API caches are declared properties on purpose (undeclared ones would be treated as Eloquent
|
||||
attributes and break `save()`). Add a new cache property there when a concern caches.
|
||||
- `src/Id/Concerns/` – one trait per API area. Traits on `AnikeenId` act as the app/client;
|
||||
traits on `Billable` act for one user.
|
||||
- `src/Id/Resources/` – `BaseResource` (single object, throws `ResourceException`, or
|
||||
`ConfirmationRequiredException` for `confirmation_required`) and `BaseCollection` (lists,
|
||||
lazily built via `::builder()`).
|
||||
- `src/Id/Resources/App*` – "app" variants that use the app's own client-credentials token
|
||||
(`AnikeenId::asApp()`, `Support/AppRequest`) instead of the user's token, for trusted apps.
|
||||
They throw `Exceptions/ApiException` with a stable `error` code and must not send any request
|
||||
until a method is called.
|
||||
- `src/Id/Auth/`, `Providers/AnikeenIdServiceProvider.php`, `Http/Middleware/` – the `anikeen`
|
||||
guard driver and user provider, JWT validation (`Helpers/JwtParser.php` with the bundled
|
||||
`oauth-public*.key`), scope middleware.
|
||||
- `src/Id/Webhooks/` – signature verification (`Webhook::constructEvent`) and `EventType`
|
||||
constants.
|
||||
- `src/Support/Query.php` – query-string builder.
|
||||
- `generator/generate-docs.php` – reflects the public methods of `AnikeenId` and `Billable` traits
|
||||
into the README.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **README:** edit `README.stub`, never `README.md` directly, then run `composer docs`. The
|
||||
`<!-- GENERATED-DOCS -->` marker is replaced with the method reference. Commit both files.
|
||||
- **New endpoints:** add a method to the matching `Concerns/Manages*` trait (or a resource class),
|
||||
document request attributes with an `array{…}` PHPDoc shape and a short description per key,
|
||||
and add an example to `README.stub` when it is a new feature.
|
||||
- **Tests:** extend `Anikeen\Id\Tests\TestCase` (Orchestra Testbench). No live API: queue
|
||||
responses with `$this->respond($status, $body)` (Guzzle `MockHandler`) and assert the sent
|
||||
requests via `$this->sent` / `$this->sentJson($i)` – method, path, `Authorization` header and
|
||||
JSON body. The app token is faked as `app-token`.
|
||||
- **Compatibility:** this is a library used by several apps. Keep public method signatures
|
||||
backwards compatible; add optional parameters instead of changing existing ones.
|
||||
- Code, comments, docs and commit messages in English. Commit subjects are short, imperative,
|
||||
sentence case (e.g. "Ship orders: shipments with delivery notes"). Work happens on feature
|
||||
branches merged via PR into `main`.
|
||||
+636
-91
@@ -6,14 +6,21 @@
|
||||
|
||||
PHP Anikeen ID API Client for Laravel 11+
|
||||
|
||||
Sign in with Anikeen ID and let your users pay with their Anikeen ID account: one-off orders,
|
||||
subscriptions and physical goods, with invoices, VAT and payment handled by Anikeen ID.
|
||||
|
||||
## Table of contents
|
||||
|
||||
1. [Installation](#installation)
|
||||
2. [Event Listener](#event-listener)
|
||||
3. [Configuration](#configuration)
|
||||
4. [Examples](#examples)
|
||||
5. [Documentation](#documentation)
|
||||
6. [Development](#Development)
|
||||
2. [Configuration](#configuration)
|
||||
3. [Sign in with Anikeen ID](#sign-in-with-anikeen-id)
|
||||
4. [Payments](#payments)
|
||||
5. [Trusted apps](#trusted-apps)
|
||||
6. [API authentication](#api-authentication)
|
||||
7. [General](#general)
|
||||
8. [Examples](#examples)
|
||||
9. [Documentation](#documentation)
|
||||
10. [Development](#development)
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -21,73 +28,581 @@ PHP Anikeen ID API Client for Laravel 11+
|
||||
composer require anikeen/id
|
||||
```
|
||||
|
||||
## Event Listener
|
||||
|
||||
In Laravel 11, the default EventServiceProvider provider was removed. Instead, add the listener using the listen method on the Event facade, in your `AppServiceProvider`
|
||||
|
||||
```
|
||||
Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
|
||||
$event->extendSocialite('anikeen-id', \Anikeen\Id\Socialite\Provider::class);
|
||||
});
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Copy configuration to config folder:
|
||||
Register your app in Anikeen ID first. You need:
|
||||
|
||||
```
|
||||
$ php artisan vendor:publish --provider="Anikeen\Id\Providers\AnikeenIdServiceProvider"
|
||||
```
|
||||
- an OAuth client with your callback URL as redirect URI (e.g. `https://shop.test/auth/callback`),
|
||||
- a webhook endpoint (e.g. `https://shop.test/webhooks/anikeen`) if you sell something; Anikeen ID
|
||||
shows its signing secret `whsec_…`,
|
||||
- optionally a logo, shown to your users on the login and confirmation pages.
|
||||
|
||||
Add environmental variables to your `.env`
|
||||
Add the credentials to your `.env` file:
|
||||
|
||||
```
|
||||
ANIKEEN_ID_KEY=
|
||||
ANIKEEN_ID_SECRET=
|
||||
ANIKEEN_ID_REDIRECT_URI=http://localhost
|
||||
ANIKEEN_ID_CALLBACK_URL=http://localhost/auth/callback
|
||||
ANIKEEN_ID_WEBHOOK_SECRET=
|
||||
```
|
||||
|
||||
To switch from `production` to `staging` use following variable:
|
||||
|
||||
```
|
||||
ANIKEEN_ID_MODE=staging
|
||||
```
|
||||
|
||||
You will need to add an entry to the services configuration file so that after config files are cached for usage in production environment (Laravel command `artisan config:cache`) all config is still available.
|
||||
|
||||
**Add to `config/services.php`:**
|
||||
Add to `config/services.php` file:
|
||||
|
||||
```php
|
||||
'anikeen-id' => [
|
||||
'anikeen' => [
|
||||
'mode' => env('ANIKEEN_ID_MODE'),
|
||||
'client_id' => env('ANIKEEN_ID_KEY'),
|
||||
'client_secret' => env('ANIKEEN_ID_SECRET'),
|
||||
'redirect' => env('ANIKEEN_ID_REDIRECT_URI')
|
||||
'redirect' => env('ANIKEEN_ID_CALLBACK_URL'),
|
||||
'base_url' => env('ANIKEEN_ID_BASE_URL'),
|
||||
'webhook_secret' => env('ANIKEEN_ID_WEBHOOK_SECRET'),
|
||||
],
|
||||
```
|
||||
|
||||
## Implementing Auth
|
||||
## Sign in with Anikeen ID
|
||||
|
||||
This method should typically be called in the `boot` method of your `AuthServiceProvider` class:
|
||||
### Event Listener
|
||||
|
||||
In Laravel 11, the default EventServiceProvider provider was removed. Instead, add the listener using the listen method on the Event facade, in your `AppServiceProvider` boot method:
|
||||
|
||||
```php
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Anikeen\Id\Providers\AnikeenIdSsoUserProvider;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Register any authentication / authorization services.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function boot()
|
||||
public function boot(): void
|
||||
{
|
||||
Auth::provider('sso-users', function ($app, array $config) {
|
||||
return new AnikeenIdSsoUserProvider(
|
||||
$app->make(AnikeenId::class),
|
||||
$app->make(Request::class),
|
||||
$config['model'],
|
||||
$config['fields'] ?? [],
|
||||
$config['access_token_field'] ?? null
|
||||
);
|
||||
Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
|
||||
$event->extendSocialite('anikeen', \Anikeen\Id\Socialite\Provider::class);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
reference the guard in the `guards` configuration of your `auth.php` configuration file:
|
||||
### User model
|
||||
|
||||
Your users table needs the user's Anikeen ID and their tokens:
|
||||
|
||||
```php
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->string('anikeen_id')->nullable()->unique();
|
||||
$table->text('anikeen_id_access_token')->nullable();
|
||||
$table->text('anikeen_id_refresh_token')->nullable();
|
||||
});
|
||||
```
|
||||
|
||||
Add the `Billable` trait to the user model. Keep the tokens encrypted and out of JSON:
|
||||
|
||||
```php
|
||||
use Anikeen\Id\Billable;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use Billable;
|
||||
|
||||
protected $hidden = ['password', 'remember_token', 'anikeen_id_access_token', 'anikeen_id_refresh_token'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'anikeen_id_access_token' => 'encrypted',
|
||||
'anikeen_id_refresh_token' => 'encrypted',
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
All user methods (`$user->orders()`, `$user->subscriptions()`, …) call the API with the user's
|
||||
access token from `anikeen_id_access_token`.
|
||||
|
||||
### Login and callback
|
||||
|
||||
Ask for the scopes your app needs (see [Scope](src/Id/Enums/Scope.php)). To sell orders and
|
||||
subscriptions, a shop typically asks for:
|
||||
|
||||
```php
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
|
||||
Route::get('auth/redirect', fn () => Socialite::driver('anikeen')
|
||||
->scopes(['user:read', 'addresses:read', 'orders', 'subscriptions'])
|
||||
->redirect());
|
||||
|
||||
Route::get('auth/callback', function () {
|
||||
$account = Socialite::driver('anikeen')->user();
|
||||
|
||||
$user = User::updateOrCreate(['anikeen_id' => $account->getId()], [
|
||||
'name' => $account->getName() ?: $account->getNickname(),
|
||||
'email' => $account->getEmail(),
|
||||
'anikeen_id_access_token' => $account->token,
|
||||
'anikeen_id_refresh_token' => $account->refreshToken,
|
||||
]);
|
||||
|
||||
Auth::login($user, remember: true);
|
||||
|
||||
return redirect()->intended('/');
|
||||
});
|
||||
```
|
||||
|
||||
Access tokens expire. Get a new one with the refresh token (or send the user through the login
|
||||
again):
|
||||
|
||||
```php
|
||||
$result = app(\Anikeen\Id\AnikeenId::class)->refreshToken($user->anikeen_id_refresh_token);
|
||||
|
||||
if ($result->success()) {
|
||||
$user->update([
|
||||
'anikeen_id_access_token' => $result->data()->access_token,
|
||||
'anikeen_id_refresh_token' => $result->data()->refresh_token,
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
### Change the default access token / refresh token field name
|
||||
|
||||
If your access / refresh token fields differ from the default `anikeen_id_access_token` / `anikeen_id_refresh_token`, you can specify the field name in the `AppServiceProvider` boot method:
|
||||
|
||||
```php
|
||||
use Anikeen\Id\AnikeenId;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
AnikeenId::useAccessTokenField('anikeen_id_access_token');
|
||||
AnikeenId::useRefreshTokenField('anikeen_id_refresh_token');
|
||||
}
|
||||
```
|
||||
|
||||
## Payments
|
||||
|
||||
### Which way fits?
|
||||
|
||||
| You want to sell | Use | Token | Who starts the payment |
|
||||
|---|---|---|---|
|
||||
| One-off purchases (digital or physical goods) | [Orders](#selling-an-order) | user | the user, on Anikeen ID |
|
||||
| Something that recurs (a pass, a plan) | [Subscriptions](#subscriptions) | user | the user, on Anikeen ID |
|
||||
| Several subscriptions in one step | [Checkout sessions](#checkout-sessions-the-user-confirms-several-subscriptions-at-once) | user or app | the user, on Anikeen ID |
|
||||
| Usage billing from your backend, without the user online | [App subscriptions](#app-subscriptions-trusted-apps-no-user-token) | app | your app (trusted apps only) |
|
||||
|
||||
Most apps are third-party apps: they create an order or subscription as a draft, send the user to
|
||||
Anikeen ID to confirm and pay, and get the user back afterwards. Anikeen ID shows the items, asks
|
||||
for missing addresses, takes the payment and writes the invoice. Trusted apps (operated by
|
||||
Anikeen) can also charge directly; see [Trusted apps](#trusted-apps).
|
||||
|
||||
The flow, as in a typical shop:
|
||||
|
||||
1. The user signs in with Anikeen ID ([above](#sign-in-with-anikeen-id)).
|
||||
2. Your app creates the order: `$user->orders()->create([...])`.
|
||||
3. Redirect the user to `$order->confirmationUrl($returnUrl)`.
|
||||
4. The user confirms and pays on Anikeen ID, then comes back to `$returnUrl?status=…&order=…`.
|
||||
5. Your app reads the order through the API (never trust the query string) and shows the result.
|
||||
6. The `order.completed` webhook arrives; fulfil the order there.
|
||||
|
||||
### Selling an order
|
||||
|
||||
```php
|
||||
use Anikeen\Id\Exceptions\ResourceException;
|
||||
|
||||
$order = $user->orders()->create([
|
||||
'billing_address_id' => $user->getUserData()->billing_address_id,
|
||||
'items' => [
|
||||
['type' => 'digital', 'name' => 'Sticker pack', 'unit' => 'piece', 'units' => 1, 'gross_price' => '9.99'],
|
||||
],
|
||||
]);
|
||||
|
||||
$shopOrder = ShopOrder::create(['user_id' => $user->id, 'anikeen_id' => $order->id, 'status' => $order->status]); // your own order model
|
||||
|
||||
return redirect()->away($order->confirmationUrl(route('orders.return', $shopOrder)));
|
||||
// later: https://shop.test/orders/1/return?status=completed&order=01J…
|
||||
```
|
||||
|
||||
When the user has no billing address on Anikeen ID yet, pass one instead of the ID. A name and
|
||||
the country are enough; the user completes it on the confirmation page:
|
||||
|
||||
```php
|
||||
'billing_address' => ['first_name' => 'Ada', 'last_name' => 'Lovelace', 'country_iso' => 'DE', 'email' => $user->email],
|
||||
```
|
||||
|
||||
Back in your app, read the order to know its state:
|
||||
|
||||
```php
|
||||
Route::get('orders/{shopOrder}/return', function (ShopOrder $shopOrder) {
|
||||
$order = auth()->user()->orders()->find($shopOrder->anikeen_id);
|
||||
|
||||
$shopOrder->update(['status' => $order->status]);
|
||||
|
||||
return redirect()->route('orders.show', $shopOrder);
|
||||
});
|
||||
```
|
||||
|
||||
The order's `status`:
|
||||
|
||||
| `status` | Meaning |
|
||||
|---|---|
|
||||
| `draft` | Created, not confirmed by the user yet |
|
||||
| `pending` | Confirmed, the payment is still processing |
|
||||
| `completed` | Paid |
|
||||
| `cancelled` | The user cancelled, or it wasn't confirmed within 24 hours |
|
||||
|
||||
`return_url` must have the origin of one of your app's redirect URIs. The `status` in its query
|
||||
string (`completed`, `pending` or `cancelled`) is only a hint for the message you show.
|
||||
|
||||
`checkout()` on such a draft throws `ConfirmationRequiredException`; its `confirmationUrl`
|
||||
points to the same page. Trusted apps keep checking out directly.
|
||||
|
||||
### Prices and VAT
|
||||
|
||||
Anikeen ID calculates VAT from the user's billing address and the item `type`:
|
||||
|
||||
| `type` | For | VAT in Germany |
|
||||
|---|---|---|
|
||||
| `digital` | Downloads, streams, services | 19 % |
|
||||
| `physical` | Goods you ship | 19 % |
|
||||
| `physical-reduced` | Goods with the reduced rate (books, event tickets, …) | 7 % |
|
||||
|
||||
Give each item either `gross_price` (VAT included, what the user pays) or `price` (net), per unit.
|
||||
`unit` is `piece` or `onetime` for orders; `units` is the quantity. Subscription prices are always
|
||||
net per unit (`hour`, `day`, `week`, `month`, `year`).
|
||||
|
||||
To show a total before the user confirms, ask for a preview:
|
||||
|
||||
```php
|
||||
$preview = app(\Anikeen\Id\AnikeenId::class)->createOrderPreview([
|
||||
'country_iso' => 'DE',
|
||||
'items' => [['type' => 'physical', 'name' => 'T-shirt', 'gross_price' => '24.90', 'unit' => 'piece', 'units' => 1]],
|
||||
])->shift();
|
||||
|
||||
$preview->gross_total;
|
||||
```
|
||||
|
||||
### Physical goods and shipments
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
To know what is left to ship, compare the order's items with its shipments:
|
||||
|
||||
```php
|
||||
$items = $order->orderItems()->toArray(); // id, type, name, units, …
|
||||
$shipments = $order->shipments()->toArray(); // each with items: [{order_item_id, units}]
|
||||
```
|
||||
|
||||
Only the app that created the order (or a trusted app) can ship it, and only once it is paid.
|
||||
|
||||
### Subscriptions
|
||||
|
||||
Subscriptions work like orders: create a draft, let the user confirm it, read it back.
|
||||
|
||||
```php
|
||||
$subscription = $user->subscriptions()->create([
|
||||
'name' => 'Pixel Stream Pass',
|
||||
'description' => 'All streams, every month',
|
||||
'unit' => 'month',
|
||||
'price' => 6.714286, // net per unit, 7.99 with 19 % VAT
|
||||
]);
|
||||
|
||||
return redirect()->away($subscription->confirmationUrl(route('pass.return')));
|
||||
// later: https://shop.test/pass/return?status=completed&subscription=01J…
|
||||
```
|
||||
|
||||
After the return, read the subscription and check its state:
|
||||
|
||||
```php
|
||||
$subscription = $user->subscriptions()->find($id);
|
||||
|
||||
if ($subscription->isActive()) {
|
||||
// grant access
|
||||
}
|
||||
```
|
||||
|
||||
`status()` returns one of the `Anikeen\Id\Enums\SubscriptionStatus` constants (the API sends the
|
||||
same value as `status`):
|
||||
|
||||
| `status()` | Meaning | `isActive()` |
|
||||
|---|---|---|
|
||||
| `draft` | Created, not confirmed by the user yet | no |
|
||||
| `trial` | Running, in its trial period | yes |
|
||||
| `active` | Running and billed | yes |
|
||||
| `paused` | Runs until the paid period ends, then expires (`resume()` to continue) | yes |
|
||||
| `cancelling` | Runs until a scheduled cancellation takes effect | yes |
|
||||
| `expired` | Paused and ran out; `resume()` starts a new period | no |
|
||||
| `cancelled` | Cancelled for good | no |
|
||||
|
||||
There are shortcuts for each: `isDraft()`, `isPaused()`, `isCancelling()`, `isExpired()`,
|
||||
`isCancelled()`. App subscriptions (`appSubscriptions()`) have the same methods.
|
||||
|
||||
### Webhooks
|
||||
|
||||
Anikeen ID sends `order.*`, `subscription.*` and `checkout.*` events to the webhook endpoints of
|
||||
your app (see [`EventType`](src/Id/Webhooks/EventType.php) for all of them). Verify each request
|
||||
with the raw body and answer 2xx within 10 seconds; failed deliveries are retried for about three
|
||||
days.
|
||||
|
||||
Exclude the route from CSRF protection in `bootstrap/app.php`:
|
||||
|
||||
```php
|
||||
->withMiddleware(function (Middleware $middleware) {
|
||||
$middleware->validateCsrfTokens(except: ['webhooks/*']);
|
||||
})
|
||||
```
|
||||
|
||||
```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);
|
||||
}
|
||||
|
||||
if (! ProcessedEvent::firstOrCreate(['id' => $event['id']])->wasRecentlyCreated) {
|
||||
return response()->noContent(); // already handled
|
||||
}
|
||||
|
||||
$object = $event['data']['object'];
|
||||
|
||||
match ($event['type']) {
|
||||
EventType::ORDER_COMPLETED => Shop::fulfil($object['id'], $object['shipping_address']),
|
||||
EventType::ORDER_CANCELLED => Shop::release($object['id']),
|
||||
EventType::SUBSCRIPTION_ACTIVATED => Pass::grant($object['id']),
|
||||
EventType::SUBSCRIPTION_CANCELLED => Pass::revoke($object['id']),
|
||||
EventType::CHECKOUT_COMPLETED => Panel::provision($object['subscription_ids']),
|
||||
default => null,
|
||||
};
|
||||
|
||||
return response()->noContent();
|
||||
});
|
||||
```
|
||||
|
||||
`data.object` is the order, subscription or checkout session as the API returns it. 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. The admin panel can send a
|
||||
`webhook.test` event to check your endpoint.
|
||||
|
||||
### Errors
|
||||
|
||||
Calls with the user's token throw `Anikeen\Id\Exceptions\ResourceException` when Anikeen ID
|
||||
rejects them; `getCode()` is the HTTP status (e.g. `422` for invalid data, `404` for an unknown
|
||||
ID) and `getMessage()` the reason. App calls (`app*()`) throw its subclass `ApiException`, which
|
||||
adds a stable `error` code. Catching `ResourceException` covers both:
|
||||
|
||||
```php
|
||||
use Anikeen\Id\Exceptions\ResourceException;
|
||||
|
||||
try {
|
||||
$order = $user->orders()->create($attributes);
|
||||
} catch (ResourceException $e) {
|
||||
report($e);
|
||||
|
||||
return back()->with('error', 'The order could not be created.');
|
||||
}
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
Develop against staging (`ANIKEEN_ID_MODE=staging`) with an OAuth client registered there.
|
||||
Payments on staging run in Stripe's test mode: pay with Stripe's
|
||||
[test cards](https://docs.stripe.com/testing), e.g. `4242 4242 4242 4242` with any future expiry
|
||||
date and any CVC. No money is charged.
|
||||
Point `ANIKEEN_ID_BASE_URL` at your own Anikeen ID instance if you run one locally.
|
||||
|
||||
In unit tests, swap the HTTP client for a Guzzle `MockHandler`:
|
||||
|
||||
```php
|
||||
$mock = new \GuzzleHttp\Handler\MockHandler([
|
||||
new \GuzzleHttp\Psr7\Response(201, ['Content-Type' => 'application/json'], json_encode(['data' => ['id' => '01JORDER', 'status' => 'draft']])),
|
||||
]);
|
||||
|
||||
$this->app->instance(AnikeenId::class, (new AnikeenId())->setHttpClient(new \GuzzleHttp\Client([
|
||||
'handler' => \GuzzleHttp\HandlerStack::create($mock),
|
||||
'base_uri' => 'https://id.test/api/',
|
||||
])));
|
||||
```
|
||||
|
||||
## Trusted apps
|
||||
|
||||
Apps operated by Anikeen can be marked as trusted. They can charge without asking the user and
|
||||
use their own token (client credentials), so billing keeps working when the user's login expired.
|
||||
|
||||
### 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: a cart 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.
|
||||
|
||||
|
||||
## API authentication
|
||||
|
||||
Use this when your own API accepts access tokens issued by Anikeen ID.
|
||||
|
||||
### Registering Middleware
|
||||
|
||||
To call your API from your own frontend with the user's session, append the middleware to the
|
||||
web middleware group in your application's `bootstrap/app.php` file:
|
||||
|
||||
```php
|
||||
->withMiddleware(function (Middleware $middleware) {
|
||||
$middleware->web(append: [
|
||||
\Anikeen\Id\Http\Middleware\CreateFreshApiToken::class,
|
||||
]);
|
||||
})
|
||||
```
|
||||
|
||||
### Implementing Auth (API tokens)
|
||||
|
||||
The package registers an `anikeen` guard driver and an `anikeen` user provider. Reference them
|
||||
in `config/auth.php`:
|
||||
|
||||
```php
|
||||
'guards' => [
|
||||
@@ -97,54 +612,65 @@ reference the guard in the `guards` configuration of your `auth.php` configurati
|
||||
],
|
||||
|
||||
'api' => [
|
||||
'driver' => 'anikeen-id',
|
||||
'provider' => 'sso-users',
|
||||
'driver' => 'anikeen',
|
||||
'provider' => 'anikeen',
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
reference the provider in the `providers` configuration of your `auth.php` configuration file:
|
||||
|
||||
```php
|
||||
'providers' => [
|
||||
'users' => [
|
||||
'driver' => 'eloquent',
|
||||
'model' => App\Models\User::class,
|
||||
],
|
||||
|
||||
'sso-users' => [
|
||||
'driver' => 'sso-users',
|
||||
'anikeen' => [
|
||||
'driver' => 'anikeen',
|
||||
'model' => App\Models\User::class,
|
||||
'fields' => ['first_name', 'last_name', 'email'],
|
||||
'access_token_field' => 'sso_access_token',
|
||||
'column' => 'anikeen_id', // optional, see below
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
## Examples
|
||||
The guard accepts `Authorization: Bearer <access token>` with an access token issued by Anikeen ID
|
||||
(personal access token or OAuth token, a JWT). It verifies the RS256 signature with Anikeen ID's
|
||||
public key and the time claims (`exp`, `nbf`, `iat`, 60 seconds leeway). The token's `sub` (the
|
||||
user's Anikeen ID) is looked up in the column `anikeen_id` of the user model: the provider's
|
||||
`column`, else `services.anikeen.user_id_column`, else `AnikeenId::useUserIdField()`. Tokens of
|
||||
unknown users, client credentials tokens (no `sub`), expired or forged tokens leave the request
|
||||
unauthenticated, so `auth:api` answers `401 {"message": "Unauthenticated."}` to JSON requests.
|
||||
|
||||
#### Basic
|
||||
The user model uses `Anikeen\Id\HasAnikeenTokens`; the token's scopes are then available:
|
||||
|
||||
```php
|
||||
$anikeenId = new Anikeen\IdAnikeenId();
|
||||
|
||||
$anikeenId->setClientId('abc123');
|
||||
|
||||
// Get SSH Key by User ID
|
||||
$result = $anikeenId->getSshKeysByUserId(38);
|
||||
|
||||
// Check, if the query was successfull
|
||||
if ( ! $result->success()) {
|
||||
die('Ooops: ' . $result->error());
|
||||
}
|
||||
|
||||
// Shift result to get single key data
|
||||
$sshKey = $result->shift();
|
||||
|
||||
echo $sshKey->name;
|
||||
$request->user()->anikeenTokenCan('user'); // has the scope (or `*`)
|
||||
$request->user()->anikeenTokenCanAny(['user', 'user:read']);
|
||||
```
|
||||
|
||||
#### Setters
|
||||
or as middleware (`403` without the scope):
|
||||
|
||||
```php
|
||||
use Anikeen\Id\Http\Middleware\CheckForAnyScope;
|
||||
use Anikeen\Id\Http\Middleware\CheckScopes;
|
||||
|
||||
Route::middleware(['auth:api', CheckScopes::using('user')])->post(...); // all scopes
|
||||
Route::middleware(['auth:api', CheckForAnyScope::using('user', 'user:read')])->get(...); // any scope
|
||||
```
|
||||
|
||||
Options in `config/services.php` (`anikeen`):
|
||||
|
||||
| Key | Default | |
|
||||
|-----|---------|-|
|
||||
| `public_key` | – | Anikeen ID's public key (PEM; `\n` escapes allowed) |
|
||||
| `public_key_path` | – | path to that key; without both the key shipped for the `mode` is used |
|
||||
| `user_id_column` | `anikeen_id` | column holding the user's Anikeen ID |
|
||||
| `verify_revocation` | `false` | also ask Anikeen ID (`GET v1/user`) whether the token is still valid, so revoked tokens stop working before they expire; fails closed when Anikeen ID is unreachable |
|
||||
| `revocation_cache_ttl` | `300` | seconds that answer is cached per token |
|
||||
|
||||
The key is read once per process. In tests `AnikeenId::actingAs($user, ['user'])` signs in without a token.
|
||||
|
||||
## General
|
||||
|
||||
#### Setters and Getters
|
||||
|
||||
```php
|
||||
$anikeenId = new Anikeen\Id\AnikeenId();
|
||||
@@ -158,27 +684,50 @@ $anikeenId = $anikeenId->withClientSecret('abc123');
|
||||
$anikeenId = $anikeenId->withToken('abcdef123456');
|
||||
```
|
||||
|
||||
#### Results and resources
|
||||
|
||||
Low-level methods on `AnikeenId` (e.g. `getAuthedUser()`, `createOrderPreview()`,
|
||||
`refreshToken()`) return a `Result`. Check it before you use it:
|
||||
|
||||
```php
|
||||
$result = $anikeenId->getAuthedUser();
|
||||
|
||||
if (!$result->success()) {
|
||||
die('Ooops: ' . $result->error());
|
||||
}
|
||||
|
||||
$user = $result->shift(); // the object, or the first item of a list
|
||||
```
|
||||
|
||||
Resource methods (`$user->orders()`, `$anikeenId->sshKeysByUserId()`, …) return objects and throw
|
||||
`ResourceException` instead (see [Errors](#errors)).
|
||||
|
||||
## Examples
|
||||
|
||||
#### Get User SSH Keys
|
||||
|
||||
Uses the app's own token (client credentials):
|
||||
|
||||
```php
|
||||
$sshKeys = app(Anikeen\Id\AnikeenId::class)->sshKeysByUserId($anikeenUserId);
|
||||
|
||||
foreach ($sshKeys->toArray() as $sshKey) {
|
||||
echo $sshKey->name;
|
||||
}
|
||||
```
|
||||
|
||||
#### OAuth Tokens
|
||||
|
||||
```php
|
||||
$anikeenId = new Anikeen\Id\AnikeenId();
|
||||
|
||||
$anikeenId->setClientId('abc123');
|
||||
$anikeenId->setToken('abcdef123456');
|
||||
|
||||
$result = $anikeenId->getAuthedUser();
|
||||
|
||||
$user = $userResult->shift();
|
||||
$user = $anikeenId->getAuthedUser()->shift();
|
||||
```
|
||||
|
||||
```php
|
||||
$anikeenId->setToken('uvwxyz456789');
|
||||
|
||||
$result = $anikeenId->getAuthedUser();
|
||||
```
|
||||
|
||||
```php
|
||||
$result = $anikeenId->withToken('uvwxyz456789')->getAuthedUser();
|
||||
$user = $anikeenId->withToken('uvwxyz456789')->getAuthedUser()->shift();
|
||||
```
|
||||
|
||||
#### Facade
|
||||
@@ -186,14 +735,14 @@ $result = $anikeenId->withToken('uvwxyz456789')->getAuthedUser();
|
||||
```php
|
||||
use Anikeen\Id\Facades\AnikeenId;
|
||||
|
||||
AnikeenId::withClientId('abc123')->withToken('abcdef123456')->getAuthedUser();
|
||||
AnikeenId::withToken('abcdef123456')->getAuthedUser();
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
<!-- GENERATED-DOCS -->
|
||||
|
||||
[**OAuth Scopes Enums**](https://github.com/anikeen-com/id/blob/main/src/Enums/Scope.php)
|
||||
[**OAuth Scopes Enums**](https://github.com/anikeen-com/id/blob/main/src/Id/Enums/Scope.php)
|
||||
|
||||
## Development
|
||||
|
||||
@@ -203,10 +752,6 @@ AnikeenId::withClientId('abc123')->withToken('abcdef123456')->getAuthedUser();
|
||||
composer test
|
||||
```
|
||||
|
||||
```shell
|
||||
BASE_URL=xxxx CLIENT_ID=xxxx CLIENT_KEY=yyyy CLIENT_ACCESS_TOKEN=zzzz composer test
|
||||
```
|
||||
|
||||
#### Generate Documentation
|
||||
|
||||
```shell
|
||||
|
||||
+13
-11
@@ -1,28 +1,30 @@
|
||||
{
|
||||
"name": "anikeen/id",
|
||||
"description": "PHP AnikeenId API Client for Laravel 10+",
|
||||
"description": "PHP Anikeen ID API client for Laravel 11+",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "René Preuß",
|
||||
"name": "Ren\u00e9 Preu\u00df",
|
||||
"email": "rene@anikeen.com"
|
||||
},
|
||||
{
|
||||
"name": "Maurice Preuß",
|
||||
"name": "Maurice Preu\u00df",
|
||||
"email": "maurice@anikeen.com"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^8.0",
|
||||
"php": "^8.2",
|
||||
"ext-json": "*",
|
||||
"illuminate/support": "^11.0|^12.0",
|
||||
"illuminate/console": "^11.0|^12.0",
|
||||
"guzzlehttp/guzzle": "^6.3|^7.0",
|
||||
"socialiteproviders/manager": "^3.4|^4.0.1",
|
||||
"firebase/php-jwt": "^6.0"
|
||||
"illuminate/support": "^11.0|^12.0|^13.0",
|
||||
"illuminate/console": "^11.0|^12.0|^13.0",
|
||||
"guzzlehttp/guzzle": "^7.8",
|
||||
"socialiteproviders/manager": "^4.6",
|
||||
"firebase/php-jwt": "^6.10|^7.0"
|
||||
},
|
||||
"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": {
|
||||
"psr-4": {
|
||||
@@ -49,4 +51,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'client_key' => env('ANIKEEN_ID_KEY'),
|
||||
'client_secret' => env('ANIKEEN_ID_SECRET'),
|
||||
'redirect_url' => env('ANIKEEN_ID_REDIRECT_URI'),
|
||||
'base_url' => env('ANIKEEN_ID_BASE_URL'),
|
||||
];
|
||||
+119
-85
@@ -1,85 +1,119 @@
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
$markdown = collect(class_uses(AnikeenId::class))
|
||||
->map(function ($trait) {
|
||||
|
||||
$title = str_replace('Trait', '', Arr::last(explode('\\', $trait)));
|
||||
|
||||
$methods = [];
|
||||
|
||||
$reflection = new ReflectionClass($trait);
|
||||
|
||||
collect($reflection->getMethods())
|
||||
->reject(function (ReflectionMethod $method) {
|
||||
return $method->isAbstract();
|
||||
})
|
||||
->reject(function (ReflectionMethod $method) {
|
||||
return $method->isPrivate() || $method->isProtected();
|
||||
})
|
||||
->reject(function (ReflectionMethod $method) {
|
||||
return $method->isConstructor();
|
||||
})
|
||||
->each(function (ReflectionMethod $method) use (&$methods, $title, $trait) {
|
||||
|
||||
$declaration = collect($method->getModifiers())->map(function (int $modifier) {
|
||||
return $modifier == ReflectionMethod::IS_PUBLIC ? 'public ' : '';
|
||||
})->join(' ');
|
||||
|
||||
$declaration .= 'function ';
|
||||
$declaration .= $method->getName();
|
||||
$declaration .= '(';
|
||||
|
||||
$declaration .= collect($method->getParameters())->map(function (ReflectionParameter $parameter) {
|
||||
|
||||
$parameterString = Arr::last(explode('\\', $parameter->getType()->getName()));
|
||||
$parameterString .= ' ';
|
||||
$parameterString .= '$';
|
||||
$parameterString .= $parameter->getName();
|
||||
|
||||
if ($parameter->isDefaultValueAvailable()) {
|
||||
$parameterString .= ' = ';
|
||||
$parameterString .= str_replace(PHP_EOL, '', var_export($parameter->getDefaultValue(), true));
|
||||
}
|
||||
|
||||
return $parameterString;
|
||||
|
||||
})->join(', ');
|
||||
|
||||
$declaration .= ')';
|
||||
|
||||
$methods[] = $declaration;
|
||||
});
|
||||
|
||||
return [$title, $methods];
|
||||
})
|
||||
->map(function ($args) {
|
||||
|
||||
list($title, $methods) = $args;
|
||||
|
||||
$markdown = '### ' . $title;
|
||||
$markdown .= PHP_EOL . PHP_EOL;
|
||||
$markdown .= '```php';
|
||||
$markdown .= PHP_EOL;
|
||||
|
||||
$markdown .= collect($methods)->each(function ($method) {
|
||||
return $method;
|
||||
})->implode(PHP_EOL);
|
||||
|
||||
$markdown .= PHP_EOL;
|
||||
$markdown .= '```';
|
||||
|
||||
return $markdown;
|
||||
})->join(PHP_EOL . PHP_EOL);
|
||||
|
||||
$markdown = str_replace("array (\n)", '[]', $markdown);
|
||||
|
||||
$content = file_get_contents(__DIR__ . '/../README.stub');
|
||||
|
||||
$content = str_replace('<!-- GENERATED-DOCS -->', $markdown, $content);
|
||||
|
||||
file_put_contents(__DIR__ . '/../README.md', $content);
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Anikeen\Id\Billable;
|
||||
use Illuminate\Support\Arr;
|
||||
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
|
||||
$classes = [
|
||||
AnikeenId::class,
|
||||
Billable::class,
|
||||
];
|
||||
|
||||
$allMarkdown = collect($classes)
|
||||
->map(function (string $class) {
|
||||
$className = Arr::last(explode('\\', $class));
|
||||
$markdown = "## {$className}\n\n";
|
||||
|
||||
// alle Traits der Klasse, außer denen aus ApiOperations
|
||||
$traits = collect(class_uses($class) ?: [])
|
||||
->reject(function (string $trait) {
|
||||
return Str::contains($trait, 'ApiOperations\\');
|
||||
})
|
||||
->all();
|
||||
|
||||
if (empty($traits)) {
|
||||
$markdown .= '_Keine Traits gefunden._';
|
||||
return $markdown;
|
||||
}
|
||||
|
||||
// für jeden Trait die Methoden extrahieren
|
||||
$markdown .= collect($traits)
|
||||
->map(function (string $trait) {
|
||||
$title = str_replace('Trait', '', Arr::last(explode('\\', $trait)));
|
||||
$reflection = new ReflectionClass($trait);
|
||||
|
||||
$methods = collect($reflection->getMethods())
|
||||
->reject->isAbstract()
|
||||
->reject->isPrivate()
|
||||
->reject->isProtected()
|
||||
->reject->isConstructor()
|
||||
->map(function (ReflectionMethod $method) {
|
||||
// Methodendeklaration starten
|
||||
$decl = 'public function ' . $method->getName() . '(';
|
||||
|
||||
// Parameter-Typen und Default-Werte
|
||||
$decl .= collect($method->getParameters())
|
||||
->map(function (ReflectionParameter $p) {
|
||||
// Typ-Hint
|
||||
$typeHint = '';
|
||||
if ($p->hasType()) {
|
||||
$typeHint = typeName($p->getType()) . ' ';
|
||||
}
|
||||
|
||||
// Parameter-Name
|
||||
$param = $typeHint . '$' . $p->getName();
|
||||
|
||||
// Default-Wert
|
||||
if ($p->isDefaultValueAvailable()) {
|
||||
$default = $p->getDefaultValue();
|
||||
if (is_array($default) && empty($default)) {
|
||||
// leeres Array → Short-Syntax
|
||||
$param .= ' = []';
|
||||
} elseif ($default === null) {
|
||||
// NULL → null (kleingeschrieben)
|
||||
$param .= ' = null';
|
||||
} else {
|
||||
// sonst var_export, Newlines entfernen
|
||||
$def = var_export($default, true);
|
||||
$param .= ' = ' . str_replace(PHP_EOL, '', $def);
|
||||
}
|
||||
}
|
||||
|
||||
return $param;
|
||||
})
|
||||
->implode(', ');
|
||||
|
||||
$decl .= ')';
|
||||
|
||||
// Rückgabetyp, falls vorhanden
|
||||
if ($method->hasReturnType()) {
|
||||
$decl .= ': ' . typeName($method->getReturnType());
|
||||
}
|
||||
|
||||
return $decl;
|
||||
})
|
||||
->all();
|
||||
|
||||
// Markdown-Block für diesen Trait
|
||||
$md = "### {$title}\n\n```php\n";
|
||||
$md .= implode("\n", $methods) . "\n```\n";
|
||||
return $md;
|
||||
})
|
||||
->implode("\n");
|
||||
|
||||
return $markdown;
|
||||
})
|
||||
->implode("\n\n");
|
||||
|
||||
// README zusammenbauen und schreiben
|
||||
$stub = file_get_contents(__DIR__ . '/../README.stub');
|
||||
$content = str_replace('<!-- GENERATED-DOCS -->', $allMarkdown, $stub);
|
||||
file_put_contents(__DIR__ . '/../README.md', $content);
|
||||
@@ -0,0 +1,14 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEArGn4rtfKjlLtJsh61eW/
|
||||
cZdLC6ECbSUKVTZlLLvRoYr7Li6RKRDiIj7KEy+lRL4miiMtadXNx6d89KZwr8SL
|
||||
DQXDbP//F3HEXVJBtr6j8p8HbJh1pinLJeKtcmeJfOIwVLyQ3sPdewkQoFtwkQyF
|
||||
uZWLeh6TCfAtcQs49I6C0rYgLDQrfTzvQ195mX1HkgArndNDXBiECMYCCulmPpzv
|
||||
yq5MWS5+/uQjKmPToo5lPfKxbWD6lyLII9ZkGp7wFilSonpUN1LmwRJlgQqh+1Hb
|
||||
celGHTIXiP3lDNIG3sR/H5v6vwGeqfu9MBQ2Ksrz259O1aojqRQ+d9k1dj8pcbuC
|
||||
ZurlI4++JOsmecc4B3g8tvlsevlb0UbtW/JHKckgK/JL9PO+04WJD+hSJrEhokLq
|
||||
aB5Ceg6FKwqoM0l7dtoHRka8vh/q/UU3oawUESoZ5l3TjWI4b0jZzsJqE4cyKgK3
|
||||
S3tBooj4rM4dOh4y7crD1PcsJG/IF2bg4YEAO8q8Fz6TmOzCM20oBhaLrFJOnYph
|
||||
Xhhl7ZPHqCCIt6HSDbwlFJw1Iw/2nygnkAZ0iJV/EQl0M+zlDGEv41SWHQfsLTK6
|
||||
HBSM1QSEbuMz0sF/TpolYEvYso+nCDjDzQ4MFdhGxH6OVyuSySm6nG0fK/Bio5Ow
|
||||
6SNz0wIg3RagjzTbljHsT4cCAwEAAQ==
|
||||
-----END PUBLIC KEY-----
|
||||
+9
-22
@@ -1,29 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit bootstrap="vendor/autoload.php"
|
||||
backupGlobals="false"
|
||||
backupStaticAttributes="false"
|
||||
colors="true"
|
||||
verbose="true"
|
||||
convertErrorsToExceptions="true"
|
||||
convertNoticesToExceptions="true"
|
||||
convertWarningsToExceptions="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
printerClass="\Codedungeon\PHPUnitPrettyResultPrinter\Printer">
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true">
|
||||
<testsuites>
|
||||
<testsuite name="Unit">
|
||||
<directory>tests</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<filter>
|
||||
<whitelist processUncoveredFilesFromWhitelist="true">
|
||||
<source>
|
||||
<include>
|
||||
<directory suffix=".php">src</directory>
|
||||
</whitelist>
|
||||
</filter>
|
||||
<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/v1/"/>
|
||||
<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>
|
||||
</include>
|
||||
</source>
|
||||
</phpunit>
|
||||
+191
-109
@@ -2,6 +2,13 @@
|
||||
|
||||
namespace Anikeen\Id;
|
||||
|
||||
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\ManagesUserBilling;
|
||||
use Anikeen\Id\Concerns\ManagesUsers;
|
||||
use Anikeen\Id\Exceptions\RequestRequiresAuthenticationException;
|
||||
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
|
||||
use Anikeen\Id\Exceptions\RequestRequiresRedirectUriException;
|
||||
@@ -15,14 +22,20 @@ use Illuminate\Contracts\Auth\Authenticatable;
|
||||
|
||||
class AnikeenId
|
||||
{
|
||||
use Traits\OauthTrait;
|
||||
use Traits\SshKeysTrait;
|
||||
use Traits\UsersTrait;
|
||||
use OauthTrait;
|
||||
use ManagesPricing;
|
||||
use ManagesProducts;
|
||||
use ManagesShippingLabels;
|
||||
use ManagesUserBilling;
|
||||
use ManagesSocialiteUsers;
|
||||
use ManagesSshKeys;
|
||||
use ManagesUsers;
|
||||
|
||||
use ApiOperations\Delete;
|
||||
use ApiOperations\Get;
|
||||
use ApiOperations\Post;
|
||||
use ApiOperations\Put;
|
||||
use ApiOperations\Request;
|
||||
|
||||
/**
|
||||
* The name for API token cookies.
|
||||
@@ -41,7 +54,17 @@ class AnikeenId
|
||||
*/
|
||||
public static bool $unserializesCookies = false;
|
||||
|
||||
private static string $baseUrl = 'https://id.anikeen.com/api/';
|
||||
/**
|
||||
* The key for the access token.
|
||||
*/
|
||||
private static string $accessTokenField = 'anikeen_id_access_token';
|
||||
|
||||
/**
|
||||
* The key for the access token.
|
||||
*/
|
||||
private static string $refreshTokenField = 'anikeen_id_refresh_token';
|
||||
|
||||
private static string $userIdField = 'anikeen_id';
|
||||
|
||||
/**
|
||||
* Guzzle is used to make http requests.
|
||||
@@ -55,13 +78,11 @@ class AnikeenId
|
||||
|
||||
/**
|
||||
* Anikeen ID OAuth token.
|
||||
*
|
||||
*/
|
||||
protected ?string $token = null;
|
||||
|
||||
/**
|
||||
* Anikeen ID client id.
|
||||
*
|
||||
*/
|
||||
protected ?string $clientId = null;
|
||||
|
||||
@@ -75,36 +96,109 @@ class AnikeenId
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
if ($clientId = config('anikeen_id.client_id')) {
|
||||
if ($clientId = config('services.anikeen.client_id')) {
|
||||
$this->setClientId($clientId);
|
||||
}
|
||||
if ($clientSecret = config('anikeen_id.client_secret')) {
|
||||
if ($clientSecret = config('services.anikeen.client_secret')) {
|
||||
$this->setClientSecret($clientSecret);
|
||||
}
|
||||
if ($redirectUri = config('anikeen_id.redirect_url')) {
|
||||
if ($redirectUri = config('services.anikeen.redirect')) {
|
||||
$this->setRedirectUri($redirectUri);
|
||||
}
|
||||
if ($redirectUri = config('anikeen_id.base_url')) {
|
||||
self::setBaseUrl($redirectUri);
|
||||
if (self::getMode() === 'staging' && !config('services.anikeen.base_url')) {
|
||||
self::setBaseUrl($this->stagingBaseUrl);
|
||||
}
|
||||
if ($baseUrl = config('services.anikeen.base_url')) {
|
||||
self::setBaseUrl($baseUrl);
|
||||
}
|
||||
$this->client = new Client([
|
||||
'base_uri' => self::$baseUrl,
|
||||
'base_uri' => $this->baseUrl . '/api/',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $baseUrl
|
||||
*
|
||||
* @internal only for internal and debug purposes.
|
||||
*/
|
||||
public static function setBaseUrl(string $baseUrl): void
|
||||
protected 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
|
||||
{
|
||||
self::$accessTokenField = $accessTokenField;
|
||||
}
|
||||
|
||||
public static function getAccessTokenField(): string
|
||||
{
|
||||
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
|
||||
{
|
||||
self::$refreshTokenField = $refreshTokenField;
|
||||
}
|
||||
|
||||
public static function getRefreshTokenField(): string
|
||||
{
|
||||
return self::$refreshTokenField;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,7 +207,7 @@ class AnikeenId
|
||||
* @param string|null $cookie
|
||||
* @return string|static
|
||||
*/
|
||||
public static function cookie(string $cookie = null)
|
||||
public static function cookie(?string $cookie = null): string|static
|
||||
{
|
||||
if (is_null($cookie)) {
|
||||
return static::$cookie;
|
||||
@@ -127,7 +221,7 @@ class AnikeenId
|
||||
/**
|
||||
* Set the current user for the application with the given scopes.
|
||||
*/
|
||||
public static function actingAs(Authenticatable|Traits\HasAnikeenTokens $user, array $scopes = [], string $guard = 'api'): Authenticatable
|
||||
public static function actingAs(Authenticatable|HasAnikeenTokens $user, array $scopes = [], string $guard = 'api'): Authenticatable
|
||||
{
|
||||
$user->withAnikeenAccessToken((object)[
|
||||
'scopes' => $scopes
|
||||
@@ -250,63 +344,6 @@ class AnikeenId
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function get(string $path = '', array $parameters = [], Paginator $paginator = null): Result
|
||||
{
|
||||
return $this->query('GET', $path, $parameters, $paginator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build query & execute.
|
||||
*
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function query(string $method = 'GET', string $path = '', array $parameters = [], Paginator $paginator = null, mixed $jsonBody = null): Result
|
||||
{
|
||||
/** @noinspection DuplicatedCode */
|
||||
if ($paginator !== null) {
|
||||
$parameters[$paginator->action] = $paginator->cursor();
|
||||
}
|
||||
try {
|
||||
$response = $this->client->request($method, $path, [
|
||||
'headers' => $this->buildHeaders((bool)$jsonBody),
|
||||
'query' => Query::build($parameters),
|
||||
'json' => $jsonBody ?: null,
|
||||
]);
|
||||
$result = new Result($response, null, $paginator);
|
||||
} catch (RequestException $exception) {
|
||||
$result = new Result($exception->getResponse(), $exception, $paginator);
|
||||
}
|
||||
$result->anikeenId = $this;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build headers for request.
|
||||
*
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
private function buildHeaders(bool $json = false): array
|
||||
{
|
||||
$headers = [
|
||||
'Client-ID' => $this->getClientId(),
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
if ($this->token) {
|
||||
$headers['Authorization'] = 'Bearer ' . $this->token;
|
||||
}
|
||||
if ($json) {
|
||||
$headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get client id.
|
||||
*
|
||||
@@ -330,42 +367,87 @@ class AnikeenId
|
||||
}
|
||||
|
||||
/**
|
||||
* Build query & execute.
|
||||
*
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function post(string $path = '', 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
|
||||
{
|
||||
return $this->query('POST', $path, $parameters, $paginator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function delete(string $path = '', array $parameters = [], Paginator $paginator = null): Result
|
||||
{
|
||||
return $this->query('DELETE', $path, $parameters, $paginator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function put(string $path = '', array $parameters = [], Paginator $paginator = null): Result
|
||||
{
|
||||
return $this->query('PUT', $path, $parameters, $paginator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function json(string $method, string $path = '', array $body = null): Result
|
||||
{
|
||||
if ($body) {
|
||||
$body = json_encode(['data' => $body]);
|
||||
if ($paginator !== null) {
|
||||
$parameters[$paginator->action] = $paginator->cursor();
|
||||
}
|
||||
|
||||
return $this->query($method, $path, [], null, $body);
|
||||
try {
|
||||
$response = $this->client->request($method, $path, [
|
||||
'headers' => $this->buildHeaders((bool)$payload, $useClientSecret),
|
||||
'query' => Query::build($parameters),
|
||||
'json' => $payload ?: null,
|
||||
]);
|
||||
|
||||
$result = new Result($response, null, $this);
|
||||
} catch (RequestException $exception) {
|
||||
$result = new Result($exception->getResponse(), $exception, $this);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build headers for request.
|
||||
*
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
private function buildHeaders(bool $json = false, bool $useClientSecret = false): array
|
||||
{
|
||||
$headers = [
|
||||
'Client-ID' => $this->getClientId(),
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
// public endpoints (products, order preview, …) work without a token
|
||||
if ($bearerToken = $useClientSecret ? $this->getClientSecret() : $this->token) {
|
||||
$headers['Authorization'] = 'Bearer ' . $bearerToken;
|
||||
}
|
||||
if ($json) {
|
||||
$headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function get(string $path, array $parameters = [], ?Paginator $paginator = null): Result
|
||||
{
|
||||
return $this->request('GET', $path, null, $parameters, $paginator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function post(string $path, array $payload = [], array $parameters = [], ?Paginator $paginator = null): Result
|
||||
{
|
||||
return $this->request('POST', $path, $payload, $parameters, $paginator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function put(string $path, array $payload = [], array $parameters = [], ?Paginator $paginator = null): Result
|
||||
{
|
||||
return $this->request('PUT', $path, $payload, $parameters, $paginator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws GuzzleException
|
||||
* @throws RequestRequiresClientIdException
|
||||
*/
|
||||
public function delete(string $path, array $payload = [], array $parameters = [], ?Paginator $paginator = null): Result
|
||||
{
|
||||
return $this->request('DELETE', $path, $payload, $parameters, $paginator);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,18 @@
|
||||
|
||||
namespace Anikeen\Id\ApiOperations;
|
||||
|
||||
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
|
||||
use Anikeen\Id\Helpers\Paginator;
|
||||
use Anikeen\Id\Result;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
|
||||
trait Delete
|
||||
{
|
||||
abstract public function delete(string $path = '', array $parameters = [], Paginator $paginator = null): Result;
|
||||
/**
|
||||
* Delete a resource from the API.
|
||||
*
|
||||
* @throws RequestRequiresClientIdException
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
abstract public function delete(string $path, array $payload = [], array $parameters = [], ?Paginator $paginator = null): Result;
|
||||
}
|
||||
@@ -2,10 +2,18 @@
|
||||
|
||||
namespace Anikeen\Id\ApiOperations;
|
||||
|
||||
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
|
||||
use Anikeen\Id\Helpers\Paginator;
|
||||
use Anikeen\Id\Result;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
|
||||
trait Get
|
||||
{
|
||||
abstract public function get(string $path = '', array $parameters = [], Paginator $paginator = null): Result;
|
||||
/**
|
||||
* Get a resource from the API.
|
||||
*
|
||||
* @throws RequestRequiresClientIdException
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
abstract public function get(string $path, array $parameters = [], ?Paginator $paginator = null): Result;
|
||||
}
|
||||
@@ -2,10 +2,18 @@
|
||||
|
||||
namespace Anikeen\Id\ApiOperations;
|
||||
|
||||
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
|
||||
use Anikeen\Id\Helpers\Paginator;
|
||||
use Anikeen\Id\Result;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
|
||||
trait Post
|
||||
{
|
||||
abstract public function post(string $path = '', array $parameters = [], Paginator $paginator = null): Result;
|
||||
/**
|
||||
* Make a POST request to the API.
|
||||
*
|
||||
* @throws RequestRequiresClientIdException
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
abstract public function post(string $path, array $payload = [], array $parameters = [], ?Paginator $paginator = null): Result;
|
||||
}
|
||||
@@ -2,10 +2,18 @@
|
||||
|
||||
namespace Anikeen\Id\ApiOperations;
|
||||
|
||||
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
|
||||
use Anikeen\Id\Helpers\Paginator;
|
||||
use Anikeen\Id\Result;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
|
||||
trait Put
|
||||
{
|
||||
abstract public function put(string $path = '', array $parameters = [], Paginator $paginator = null): Result;
|
||||
/**
|
||||
* Make a PUT request to the API.
|
||||
*
|
||||
* @throws RequestRequiresClientIdException
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
abstract public function put(string $path, array $payload = [], array $parameters = [], ?Paginator $paginator = null): Result;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\ApiOperations;
|
||||
|
||||
use Anikeen\Id\Exceptions\RequestRequiresClientIdException;
|
||||
use Anikeen\Id\Helpers\Paginator;
|
||||
use Anikeen\Id\Result;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
|
||||
trait Request
|
||||
{
|
||||
/**
|
||||
* Make a request to the API.
|
||||
*
|
||||
* @throws RequestRequiresClientIdException
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
abstract public function request(string $method, string $path, null|array $payload = null, array $parameters = [], ?Paginator $paginator = null): Result;
|
||||
}
|
||||
@@ -10,7 +10,7 @@ trait Validation
|
||||
/**
|
||||
* @throws RequestRequiresMissingParametersException
|
||||
*/
|
||||
public function validateRequired(array $parameters, array $required)
|
||||
public function validateRequired(array $parameters, array $required): void
|
||||
{
|
||||
if (!Arr::has($parameters, $required)) {
|
||||
throw RequestRequiresMissingParametersException::fromValidateRequired($parameters, $required);
|
||||
|
||||
@@ -25,7 +25,7 @@ class ApiTokenCookieFactory
|
||||
{
|
||||
$config = $this->config->get('session');
|
||||
|
||||
$expiration = Carbon::now()->addMinutes($config['lifetime']);
|
||||
$expiration = Carbon::now()->addMinutes((int)$config['lifetime']);
|
||||
|
||||
return new Cookie(
|
||||
AnikeenId::cookie(),
|
||||
|
||||
+111
-62
@@ -3,44 +3,45 @@
|
||||
namespace Anikeen\Id\Auth;
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Anikeen\Id\HasAnikeenTokens;
|
||||
use Anikeen\Id\Helpers\JwtParser;
|
||||
use Anikeen\Id\Traits\HasAnikeenTokens;
|
||||
use Exception;
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
use Illuminate\Auth\AuthenticationException;
|
||||
use Illuminate\Auth\GuardHelpers;
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
use Illuminate\Contracts\Debug\ExceptionHandler;
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Contracts\Encryption\Encrypter;
|
||||
use Illuminate\Cookie\CookieValuePrefix;
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use stdClass;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Resolves the user of a request from an Anikeen ID access token (JWT, "Authorization: Bearer …")
|
||||
* or from the encrypted token cookie of CreateFreshApiToken.
|
||||
*
|
||||
* A bearer token is verified with the JwtParser (signature, expiry). Its `sub` is the user's
|
||||
* Anikeen ID, looked up by the provider (AnikeenIdUserProvider::retrieveByAnikeenId(), column
|
||||
* `anikeen_id` by default). The token is attached to the user: `$user->anikeenTokenCan('scope')`.
|
||||
*
|
||||
* With `services.anikeen.verify_revocation` the token is also checked against Anikeen ID
|
||||
* (GET v1/user, cached per token for `services.anikeen.revocation_cache_ttl` seconds), so
|
||||
* revoked tokens stop working before they expire.
|
||||
*/
|
||||
class TokenGuard
|
||||
{
|
||||
use GuardHelpers;
|
||||
|
||||
private Encrypter $encrypter;
|
||||
|
||||
private JwtParser $jwtParser;
|
||||
|
||||
public function __construct(UserProvider $provider, Encrypter $encrypter, JwtParser $jwtParser)
|
||||
{
|
||||
$this->provider = $provider;
|
||||
$this->encrypter = $encrypter;
|
||||
$this->jwtParser = $jwtParser;
|
||||
public function __construct(
|
||||
protected UserProvider $provider,
|
||||
private Encrypter $encrypter,
|
||||
private JwtParser $jwtParser
|
||||
) {
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the user for the incoming request.
|
||||
*
|
||||
* @throws BindingResolutionException
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function user(Request $request): ?Authenticatable
|
||||
{
|
||||
@@ -55,9 +56,6 @@ class TokenGuard
|
||||
|
||||
/**
|
||||
* Authenticate the incoming request via the Bearer token.
|
||||
*
|
||||
* @throws BindingResolutionException
|
||||
* @throws Throwable
|
||||
*/
|
||||
protected function authenticateViaBearerToken(Request $request): ?Authenticatable
|
||||
{
|
||||
@@ -65,51 +63,97 @@ class TokenGuard
|
||||
return null;
|
||||
}
|
||||
|
||||
// If the access token is valid we will retrieve the user according to the user ID
|
||||
// associated with the token. We will use the provider implementation which may
|
||||
// be used to retrieve users from Eloquent. Next, we'll be ready to continue.
|
||||
/** @var Authenticatable|HasAnikeenTokens $user */
|
||||
$user = $this->provider->retrieveById(
|
||||
$request->attributes->get('oauth_user_id') ?: null
|
||||
);
|
||||
// client credentials tokens have no user
|
||||
if (!is_scalar($token->sub ?? null) || (string) $token->sub === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $user?->withAnikeenAccessToken($token);
|
||||
if (!$this->tokenIsActive($token, (string) $request->bearerToken())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var Authenticatable|HasAnikeenTokens|null $user */
|
||||
$user = $this->retrieveUser((string) $token->sub);
|
||||
|
||||
return $user && method_exists($user, 'withAnikeenAccessToken')
|
||||
? $user->withAnikeenAccessToken($token)
|
||||
: $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate and get the incoming request via the Bearer token.
|
||||
*
|
||||
* @throws BindingResolutionException
|
||||
* @throws Throwable
|
||||
* Verify the Bearer token and expose its claims as request attributes.
|
||||
*/
|
||||
protected function validateRequestViaBearerToken(Request $request): ?stdClass
|
||||
{
|
||||
try {
|
||||
$decoded = $this->jwtParser->decode($request);
|
||||
|
||||
$request->attributes->set('oauth_access_token_id', $decoded->jti);
|
||||
$request->attributes->set('oauth_client_id', $decoded->aud);
|
||||
$request->attributes->set('oauth_client_trusted', $decoded->client->trusted);
|
||||
$request->attributes->set('oauth_user_id', $decoded->sub);
|
||||
$request->attributes->set('oauth_scopes', $decoded->scopes);
|
||||
|
||||
return $decoded;
|
||||
} catch (AuthenticationException $e) {
|
||||
$request->headers->set('Authorization', '', true);
|
||||
|
||||
Container::getInstance()->make(
|
||||
ExceptionHandler::class
|
||||
)->report($e);
|
||||
|
||||
} catch (AuthenticationException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decoded->scopes = array_values(array_filter((array) ($decoded->scopes ?? []), 'is_string'));
|
||||
|
||||
$request->attributes->set('oauth_access_token_id', $decoded->jti ?? null);
|
||||
$request->attributes->set('oauth_client_id', $decoded->aud ?? null);
|
||||
$request->attributes->set('oauth_client_trusted', $decoded->client->trusted ?? null);
|
||||
$request->attributes->set('oauth_user_id', $decoded->sub ?? null);
|
||||
$request->attributes->set('oauth_scopes', $decoded->scopes);
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Anikeen ID still accepts the token (only with services.anikeen.verify_revocation).
|
||||
*/
|
||||
protected function tokenIsActive(stdClass $token, string $jwt): bool
|
||||
{
|
||||
if (!config('services.anikeen.verify_revocation')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$key = 'anikeen-id:token-active:' . hash('sha256', $jwt);
|
||||
|
||||
if (($cached = Cache::get($key)) !== null) {
|
||||
return (bool) $cached;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = (clone app(AnikeenId::class))->withToken($jwt)->getAuthedUser();
|
||||
} catch (Throwable) {
|
||||
return false; // Anikeen ID unreachable: fail closed, ask again next time
|
||||
}
|
||||
|
||||
$status = $result->response?->getStatusCode();
|
||||
|
||||
if ($result->success()) {
|
||||
$active = true;
|
||||
} elseif (in_array($status, [401, 403], true)) {
|
||||
$active = false;
|
||||
} else {
|
||||
return false; // server error: fail closed without caching
|
||||
}
|
||||
|
||||
$ttl = (int) config('services.anikeen.revocation_cache_ttl', 300);
|
||||
if (isset($token->exp)) {
|
||||
$ttl = max(1, min($ttl, (int) $token->exp - time()));
|
||||
}
|
||||
Cache::put($key, $active, $ttl);
|
||||
|
||||
return $active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the local user of an Anikeen ID.
|
||||
*/
|
||||
protected function retrieveUser(string $anikeenId): ?Authenticatable
|
||||
{
|
||||
return $this->provider->retrieveByAnikeenId($anikeenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate the incoming request via the token cookie.
|
||||
*/
|
||||
protected function authenticateViaCookie(Request $request): mixed
|
||||
protected function authenticateViaCookie(Request $request): ?Authenticatable
|
||||
{
|
||||
if (!$token = $this->getTokenViaCookie($request)) {
|
||||
return null;
|
||||
@@ -118,9 +162,11 @@ class TokenGuard
|
||||
// If this user exists, we will return this user and attach a "transient" token to
|
||||
// the user model. The transient token assumes it has all scopes since the user
|
||||
// is physically logged into the application via the application's interface.
|
||||
/** @var Authenticatable|HasAnikeenTokens $user */
|
||||
if ($user = $this->provider->retrieveById($token['sub'])) {
|
||||
return $user->withAnikeenAccessToken((object)['scopes' => ['*']]);
|
||||
/** @var Authenticatable|HasAnikeenTokens|null $user */
|
||||
if ($user = $this->retrieveUser((string) $token['sub'])) {
|
||||
return method_exists($user, 'withAnikeenAccessToken')
|
||||
? $user->withAnikeenAccessToken((object) ['scopes' => ['*']])
|
||||
: $user;
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -136,15 +182,18 @@ class TokenGuard
|
||||
// database. If we can't decrypt the value we'll bail out with a null return.
|
||||
try {
|
||||
$token = $this->decodeJwtTokenCookie($request);
|
||||
} catch (Exception $e) {
|
||||
} catch (Exception) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!isset($token['sub'], $token['expiry'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// We will compare the CSRF token in the decoded API token against the CSRF header
|
||||
// sent with the request. If they don't match then this request isn't sent from
|
||||
// a valid source and we won't authenticate the request for further handling.
|
||||
if (!AnikeenId::$ignoreCsrfToken && (!$this->validCsrf($token, $request) ||
|
||||
time() >= $token['expiry'])) {
|
||||
if (time() >= $token['expiry'] || (!AnikeenId::$ignoreCsrfToken && !$this->validCsrf($token, $request))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -156,7 +205,7 @@ class TokenGuard
|
||||
*/
|
||||
protected function decodeJwtTokenCookie(Request $request): array
|
||||
{
|
||||
return (array)JWT::decode(
|
||||
return (array) JWT::decode(
|
||||
CookieValuePrefix::remove($this->encrypter->decrypt($request->cookie(AnikeenId::cookie()), AnikeenId::$unserializesCookies)),
|
||||
new Key(
|
||||
$this->encrypter->getKey(),
|
||||
@@ -171,8 +220,8 @@ class TokenGuard
|
||||
protected function validCsrf(array $token, Request $request): bool
|
||||
{
|
||||
return isset($token['csrf']) && hash_equals(
|
||||
$token['csrf'], $this->getTokenFromRequest($request)
|
||||
);
|
||||
$token['csrf'], $this->getTokenFromRequest($request)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,7 +235,7 @@ class TokenGuard
|
||||
$token = CookieValuePrefix::remove($this->encrypter->decrypt($header, static::serialized()));
|
||||
}
|
||||
|
||||
return $token;
|
||||
return (string) $token;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -196,4 +245,4 @@ class TokenGuard
|
||||
{
|
||||
return EncryptCookies::serialized('XSRF-TOKEN');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Anikeen\Id\Auth;
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Contracts\Auth\UserProvider as Base;
|
||||
|
||||
@@ -10,11 +11,33 @@ class UserProvider implements Base
|
||||
/**
|
||||
* Create a new AnikeenId user provider.
|
||||
*/
|
||||
public function __construct(protected Base $provider, protected string $providerName)
|
||||
public function __construct(protected Base $provider, protected string $providerName, protected ?string $column = null)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* The column that holds a user's Anikeen ID: the provider's `column`, else
|
||||
* `services.anikeen.user_id_column`, else AnikeenId::getUserIdField() (`anikeen_id`).
|
||||
*/
|
||||
public function column(): string
|
||||
{
|
||||
return $this->column ?: (config('services.anikeen.user_id_column') ?: AnikeenId::getUserIdField());
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the user of an Anikeen ID (the `sub` of an access token).
|
||||
*/
|
||||
public function retrieveByAnikeenId(string $anikeenId): ?Authenticatable
|
||||
{
|
||||
if (method_exists($this->provider, 'retrieveByAnikeenId')) {
|
||||
return $this->provider->retrieveByAnikeenId($anikeenId);
|
||||
}
|
||||
|
||||
// eloquent / database providers: a plain where on the column
|
||||
return $this->provider->retrieveByCredentials([$this->column() => $anikeenId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
@@ -62,4 +85,9 @@ class UserProvider implements Base
|
||||
{
|
||||
return $this->providerName;
|
||||
}
|
||||
|
||||
public function rehashPasswordIfRequired(Authenticatable $user, #[\SensitiveParameter] array $credentials, bool $force = false)
|
||||
{
|
||||
$this->provider->rehashPasswordIfRequired($user, $credentials, $force);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id;
|
||||
|
||||
use Anikeen\Id\Concerns\ManagesAddresses;
|
||||
use Anikeen\Id\Concerns\ManagesBalance;
|
||||
use Anikeen\Id\Concerns\ManagesCountries;
|
||||
use Anikeen\Id\Concerns\ManagesInvoices;
|
||||
use Anikeen\Id\Concerns\ManagesOrders;
|
||||
use Anikeen\Id\Concerns\ManagesPaymentMethods;
|
||||
use Anikeen\Id\Concerns\ManagesProfile;
|
||||
use Anikeen\Id\Concerns\ManagesSubscriptions;
|
||||
use Anikeen\Id\Concerns\ManagesTaxation;
|
||||
use Anikeen\Id\Concerns\ManagesTransactions;
|
||||
use Anikeen\Id\Concerns\ManagesUserSshKeys;
|
||||
use Throwable;
|
||||
|
||||
trait Billable
|
||||
{
|
||||
use ManagesAddresses;
|
||||
use ManagesBalance;
|
||||
use ManagesCountries;
|
||||
use ManagesInvoices;
|
||||
use ManagesOrders;
|
||||
use ManagesPaymentMethods;
|
||||
use ManagesProfile;
|
||||
use ManagesSubscriptions;
|
||||
use ManagesTaxation;
|
||||
use ManagesTransactions;
|
||||
use ManagesUserSshKeys;
|
||||
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function getUserData(): object
|
||||
{
|
||||
if (!isset($this->userDataCache)) {
|
||||
$this->userDataCache = $this->anikeenId()->request('GET', 'v1/user')->data;
|
||||
}
|
||||
return $this->userDataCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the AnikeenId class.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function anikeenId(): AnikeenId
|
||||
{
|
||||
return app(AnikeenId::class)->withToken($this->{AnikeenId::getAccessTokenField()});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Contracts\Billable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
trait HasBillable
|
||||
{
|
||||
public Billable|Model $billable;
|
||||
|
||||
public function setBillable(Billable|Model $billable): self
|
||||
{
|
||||
$this->billable = $billable;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBillable(): Billable
|
||||
{
|
||||
return $this->billable;
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
trait HasParent
|
||||
{
|
||||
protected mixed $parent;
|
||||
|
||||
public function setParent(mixed $parent): self
|
||||
{
|
||||
$this->parent = $parent;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getParent()
|
||||
{
|
||||
return $this->parent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Enums\SubscriptionStatus;
|
||||
|
||||
/**
|
||||
* The state of a subscription, derived from its fields the same way Anikeen ID derives `status`
|
||||
* (so it also works with responses that only carry the fields).
|
||||
*/
|
||||
trait HasSubscriptionStatus
|
||||
{
|
||||
/**
|
||||
* One of the SubscriptionStatus constants: draft, trial, active, paused, cancelling, expired
|
||||
* or cancelled.
|
||||
*/
|
||||
public function status(): string
|
||||
{
|
||||
$active = (bool) $this->active;
|
||||
$started = !empty($this->starts_at);
|
||||
|
||||
return match (true) {
|
||||
(bool) $this->cancelled => SubscriptionStatus::CANCELLED,
|
||||
!$active && !$started => SubscriptionStatus::DRAFT,
|
||||
$active && !empty($this->cancels_at) => SubscriptionStatus::CANCELLING,
|
||||
$active && !$this->autorenew => SubscriptionStatus::PAUSED,
|
||||
$active && !empty($this->trial_ends_at) && strtotime($this->trial_ends_at) > time() => SubscriptionStatus::TRIAL,
|
||||
$active => SubscriptionStatus::ACTIVE,
|
||||
!$this->autorenew && $started => SubscriptionStatus::EXPIRED,
|
||||
default => SubscriptionStatus::INACTIVE,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Not checked out or confirmed yet (third-party apps: send the user to confirmationUrl()).
|
||||
*/
|
||||
public function isDraft(): bool
|
||||
{
|
||||
return $this->status() === SubscriptionStatus::DRAFT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Running and paid: active, in trial, paused or with a scheduled cancellation. Grant access
|
||||
* while this is true.
|
||||
*/
|
||||
public function isActive(): bool
|
||||
{
|
||||
return in_array($this->status(), [SubscriptionStatus::TRIAL, SubscriptionStatus::ACTIVE, SubscriptionStatus::PAUSED, SubscriptionStatus::CANCELLING], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paused: runs until the paid period ends, then expires (resume() to continue).
|
||||
*/
|
||||
public function isPaused(): bool
|
||||
{
|
||||
return $this->status() === SubscriptionStatus::PAUSED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Running until a scheduled cancellation takes effect.
|
||||
*/
|
||||
public function isCancelling(): bool
|
||||
{
|
||||
return $this->status() === SubscriptionStatus::CANCELLING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Paused and ran out: resume() starts a new period.
|
||||
*/
|
||||
public function isExpired(): bool
|
||||
{
|
||||
return $this->status() === SubscriptionStatus::EXPIRED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancelled for good.
|
||||
*/
|
||||
public function isCancelled(): bool
|
||||
{
|
||||
return $this->status() === SubscriptionStatus::CANCELLED;
|
||||
}
|
||||
}
|
||||
@@ -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 ?? []));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\Addresses;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesAddresses
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get addresses from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function addresses(): Addresses
|
||||
{
|
||||
if (!isset($this->addressesCache)) {
|
||||
$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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\Transaction;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesBalance
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get balance from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function balance(): float
|
||||
{
|
||||
return $this->getUserData()->current_balance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get charges from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function charges(): float
|
||||
{
|
||||
return $this->getUserData()->current_charges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Billing overview of the current user: current_balance, current_charges, vat_rate,
|
||||
* has_billing_address, has_default_payment_method, open_orders.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function billingOverview(): object
|
||||
{
|
||||
return $this->anikeenId()->request('GET', 'v1/billing')->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}␍
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\Countries;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesCountries
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get available countries for the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function countries(): Countries
|
||||
{
|
||||
if (!isset($this->countriesCache)) {
|
||||
$this->countriesCache = Countries::builder(fn() => $this->anikeenId()
|
||||
->request('GET', 'v1/countries'))
|
||||
->setBillable($this);
|
||||
}
|
||||
|
||||
return $this->countriesCache;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\Invoices;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesInvoices
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get invoices from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function invoices(array $parameters = []): Invoices
|
||||
{
|
||||
if (!isset($this->invoicesCache)) {
|
||||
$this->invoicesCache = Invoices::builder(fn() => $this->anikeenId()
|
||||
->request('GET', 'v1/invoices', [], $parameters))
|
||||
->setBillable($this);
|
||||
}
|
||||
|
||||
return $this->invoicesCache;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\Orders;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesOrders
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get orders from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function orders(array $parameters = []): Orders
|
||||
{
|
||||
if (!isset($this->ordersCache)) {
|
||||
$this->ordersCache = Orders::builder(fn() => $this->anikeenId()
|
||||
->request('GET', 'v1/orders', [], $parameters))
|
||||
->setBillable($this);
|
||||
}
|
||||
|
||||
return $this->ordersCache;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\PaymentMethod;
|
||||
use Anikeen\Id\Resources\PaymentMethods;
|
||||
use Anikeen\Id\Result;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesPaymentMethods
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get payment methods from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function paymentMethods(): PaymentMethods
|
||||
{
|
||||
if (!isset($this->paymentMethodsCache)) {
|
||||
$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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get billing portal URL for the current user.
|
||||
*
|
||||
* @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.
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function billingPortalUrl(?string $returnUrl = null, array $options = []): string
|
||||
{
|
||||
return $this->anikeenId()
|
||||
->request('POST', 'v1/billing/portal', [
|
||||
'return_url' => $returnUrl,
|
||||
'options' => $options,
|
||||
])
|
||||
->data
|
||||
->url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new setup intent.
|
||||
*
|
||||
* @param array $options Additional options for the setup intent.
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function createSetupIntent(array $options = []): Result
|
||||
{
|
||||
return $this->anikeenId()
|
||||
->request('POST', 'v1/payment-methods', [
|
||||
'options' => $options,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\ApiOperations\Post;
|
||||
use Anikeen\Id\Result;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesPricing
|
||||
{
|
||||
use Post;
|
||||
|
||||
/**
|
||||
* Make a new order preview (will not be stored into the database).
|
||||
*
|
||||
* VAT is calculated based on the billing address and shown in the order response.
|
||||
*
|
||||
* @param array{
|
||||
* country_iso: string,
|
||||
* items: array<array{
|
||||
* type: string,
|
||||
* name: string,
|
||||
* description: string,
|
||||
* price: float|int,
|
||||
* unit: string,
|
||||
* units: int
|
||||
* }>
|
||||
* } $attributes The order data:
|
||||
* - country_iso: ISO 3166-1 alpha-2 country code
|
||||
* - items: Array of order items (each with type, name, price, unit, units, and quantity)
|
||||
* @throws Throwable
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}␍
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Throwable;
|
||||
|
||||
trait ManagesProfile
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get the profile url for the current user.
|
||||
*
|
||||
* @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.
|
||||
* @return string
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function profilePortalUrl(?string $returnUrl = null, array $options = []): string
|
||||
{
|
||||
return $this->anikeenId()->request('POST', 'v1/user/profile', [
|
||||
'return_url' => $returnUrl,
|
||||
'options' => $options,
|
||||
])->data->url;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\ApiOperations\Get;
|
||||
use Anikeen\Id\Resources\SshKeys;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesSshKeys
|
||||
{
|
||||
use Get;
|
||||
|
||||
/**
|
||||
* 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 Throwable
|
||||
*/
|
||||
public function sshKeysByUserId(string $userId): SshKeys
|
||||
{
|
||||
$app = $this->asApp();
|
||||
|
||||
return SshKeys::builder(fn() => $app->get(sprintf('v1/client/users/%s/ssh-keys', $userId)))
|
||||
->setParent($app);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\AppCheckoutSessions;
|
||||
use Anikeen\Id\Resources\AppOrders;
|
||||
use Anikeen\Id\Resources\AppSubscriptions;
|
||||
use Anikeen\Id\Resources\CheckoutSessions;
|
||||
use Anikeen\Id\Resources\Subscriptions;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesSubscriptions
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get subscriptions from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function subscriptions(): Subscriptions
|
||||
{
|
||||
if (!isset($this->subscriptionsCache)) {
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Throwable;
|
||||
|
||||
trait ManagesTaxation
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get VAT for the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function vatRate(): float
|
||||
{
|
||||
return $this->getUserData()->vat_rate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\Resources\Transactions;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesTransactions
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get transactions from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function transactions(): Transactions
|
||||
{
|
||||
if (!isset($this->transactionsCache)) {
|
||||
$this->transactionsCache = Transactions::builder(fn() => $this->anikeenId()
|
||||
->request('GET', 'v1/transactions'))
|
||||
->setBillable($this);
|
||||
}
|
||||
|
||||
return $this->transactionsCache;
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Anikeen\Id\Concerns;
|
||||
|
||||
use Anikeen\Id\ApiOperations\Get;
|
||||
use Anikeen\Id\ApiOperations\Post;
|
||||
use Anikeen\Id\Result;
|
||||
use Throwable;
|
||||
|
||||
trait ManagesUsers
|
||||
{
|
||||
use Get, Post;
|
||||
use HasParent;
|
||||
|
||||
/**
|
||||
* Get currently authed user with Bearer Token
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function getAuthedUser(): Result
|
||||
{
|
||||
return $this->get('v1/user');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new user on behalf of the current user.
|
||||
*
|
||||
* @param array{
|
||||
* first_name: null|string,
|
||||
* last_name: null|string,
|
||||
* username: null|string,
|
||||
* email: string,
|
||||
* password: null|string
|
||||
* } $attributes The user data
|
||||
* - first_name: The first name (optional)
|
||||
* - last_name: The last name (optional)
|
||||
* - username: The username (optional)
|
||||
* - email: The email (required)
|
||||
* - password: The password (optional, can be reset by the user if not provided)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function createUser(array $attributes): Result
|
||||
{
|
||||
// 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.
|
||||
*
|
||||
* @param string $email The email to check.
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function isEmailExisting(string $email): Result
|
||||
{
|
||||
// `data.exists` tells whether an account uses the email (trusted apps, app token)
|
||||
return $this->asApp()->post('v1/admin/users/check', [
|
||||
'email' => $email,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -6,11 +6,35 @@ class Scope
|
||||
{
|
||||
const USER = 'user';
|
||||
const USER_READ = 'user:read';
|
||||
const ORDERS = 'orders';
|
||||
const ORDERS_READ = 'orders:read';
|
||||
const PRODUCTS = 'products';
|
||||
const PRODUCTS_READ = 'products:read';
|
||||
|
||||
const ADDRESSES = 'addresses';
|
||||
const ADDRESSES_READ = 'addresses:read';
|
||||
|
||||
const BILLING = 'billing';
|
||||
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';
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Enums;
|
||||
|
||||
/**
|
||||
* The state of a subscription, see Subscription::status() and AppSubscription::status().
|
||||
*/
|
||||
class SubscriptionStatus
|
||||
{
|
||||
/** Created, not checked out or confirmed by the user yet. */
|
||||
const DRAFT = 'draft';
|
||||
|
||||
/** Running and billed, in its trial period. */
|
||||
const TRIAL = 'trial';
|
||||
|
||||
/** Running and billed. */
|
||||
const ACTIVE = 'active';
|
||||
|
||||
/** Paused: runs until its paid period ends, then expires. */
|
||||
const PAUSED = 'paused';
|
||||
|
||||
/** Running until a scheduled cancellation takes effect. */
|
||||
const CANCELLING = 'cancelling';
|
||||
|
||||
/** Paused and ran out: can be resumed (new period) or cancelled. */
|
||||
const EXPIRED = 'expired';
|
||||
|
||||
/** Cancelled for good. */
|
||||
const CANCELLED = 'cancelled';
|
||||
|
||||
/** None of the above. */
|
||||
const INACTIVE = 'inactive';
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
//
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Traits;
|
||||
namespace Anikeen\Id;
|
||||
|
||||
use stdClass;
|
||||
|
||||
@@ -9,7 +9,7 @@ trait HasAnikeenTokens
|
||||
/**
|
||||
* The current access token for the authentication user.
|
||||
*/
|
||||
protected ?stdClass $accessToken;
|
||||
protected ?stdClass $accessToken = null;
|
||||
|
||||
/**
|
||||
* Get the current access token being used by the user.
|
||||
@@ -26,9 +26,23 @@ trait HasAnikeenTokens
|
||||
*/
|
||||
public function anikeenTokenCan(string $scope): bool
|
||||
{
|
||||
$scopes = $this->accessToken ? $this->accessToken->scopes : [];
|
||||
$scopes = (array) ($this->accessToken->scopes ?? []);
|
||||
|
||||
return in_array('*', $scopes) || in_array($scope, $this->accessToken->scopes);
|
||||
return in_array('*', $scopes, true) || in_array($scope, $scopes, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the current API token has any of the given scopes.
|
||||
*/
|
||||
public function anikeenTokenCanAny(array $scopes): bool
|
||||
{
|
||||
foreach ($scopes as $scope) {
|
||||
if ($this->anikeenTokenCan($scope)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2,34 +2,79 @@
|
||||
|
||||
namespace Anikeen\Id\Helpers;
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
use Illuminate\Auth\AuthenticationException;
|
||||
use Illuminate\Http\Request;
|
||||
use RuntimeException;
|
||||
use stdClass;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Verifies access tokens issued by Anikeen ID (Passport, RS256): signature against
|
||||
* Anikeen ID's public key plus the time claims (exp, nbf, iat; 60 seconds leeway).
|
||||
*
|
||||
* The key is `services.anikeen.public_key` (PEM, "\n" escapes allowed) or the file at
|
||||
* `services.anikeen.public_key_path`, else the key shipped with this package for the
|
||||
* configured mode (production / staging). It is read once per process.
|
||||
*/
|
||||
class JwtParser
|
||||
{
|
||||
/**
|
||||
* Public keys already read, by source.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private static array $keys = [];
|
||||
|
||||
/**
|
||||
* @throws AuthenticationException
|
||||
*/
|
||||
public function decode(Request $request): stdClass
|
||||
{
|
||||
return $this->decodeToken((string) $request->bearerToken());
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws AuthenticationException
|
||||
*/
|
||||
public function decodeToken(string $token): stdClass
|
||||
{
|
||||
if ($token === '') {
|
||||
throw new AuthenticationException('No access token given.');
|
||||
}
|
||||
|
||||
JWT::$leeway = 60;
|
||||
|
||||
// outside the try: a missing key is a configuration error, not an invalid token
|
||||
$key = new Key($this->getOauthPublicKey(), 'RS256');
|
||||
|
||||
try {
|
||||
return JWT::decode(
|
||||
$request->bearerToken(),
|
||||
new Key($this->getOauthPublicKey(), 'RS256')
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
throw (new AuthenticationException());
|
||||
return JWT::decode($token, $key);
|
||||
} catch (Throwable) {
|
||||
throw new AuthenticationException('The access token is invalid or expired.');
|
||||
}
|
||||
}
|
||||
|
||||
private function getOauthPublicKey(): bool|string
|
||||
/**
|
||||
* Forget the keys read so far (e.g. after changing the configuration in tests).
|
||||
*/
|
||||
public static function flushKeys(): void
|
||||
{
|
||||
return file_get_contents(dirname(__DIR__, 3) . '/oauth-public.key');
|
||||
self::$keys = [];
|
||||
}
|
||||
|
||||
protected function getOauthPublicKey(): string
|
||||
{
|
||||
if ($key = config('services.anikeen.public_key')) {
|
||||
return self::$keys['config:' . md5($key)] ??= str_replace('\\n', "\n", $key);
|
||||
}
|
||||
|
||||
$path = config('services.anikeen.public_key_path') ?: (AnikeenId::getMode() === 'staging'
|
||||
? dirname(__DIR__, 3) . '/oauth-public.staging.key'
|
||||
: dirname(__DIR__, 3) . '/oauth-public.key');
|
||||
|
||||
return self::$keys['file:' . $path] ??= (is_readable($path) ? (string) file_get_contents($path) : throw new RuntimeException("Anikeen ID public key [$path] is not readable."));
|
||||
}
|
||||
}
|
||||
@@ -7,70 +7,120 @@ use stdClass;
|
||||
|
||||
class Paginator
|
||||
{
|
||||
|
||||
/**
|
||||
* Next desired action (first, after, before).
|
||||
* Next desired action: 'first', 'after', 'before'.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
public ?string $action = null;
|
||||
|
||||
/**
|
||||
* AnikeenId response pagination cursor.
|
||||
* Raw pagination links from API ('first','last','prev','next').
|
||||
*
|
||||
* @var stdClass|null
|
||||
*/
|
||||
private ?stdClass $pagination;
|
||||
private ?stdClass $links;
|
||||
|
||||
/**
|
||||
* Raw pagination meta from API (current_page, last_page, etc.).
|
||||
*
|
||||
* @var stdClass|null
|
||||
*/
|
||||
private ?stdClass $meta;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param null|stdClass $pagination AnikeenId response pagination cursor
|
||||
* @param stdClass|null $links Pagination links object
|
||||
* @param stdClass|null $meta Pagination meta object
|
||||
*/
|
||||
public function __construct(?stdClass $pagination = null)
|
||||
public function __construct(?stdClass $links = null, ?stdClass $meta = null)
|
||||
{
|
||||
$this->pagination = $pagination;
|
||||
$this->links = $links;
|
||||
$this->meta = $meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Paginator from Result object.
|
||||
* Create Paginator from a Result instance.
|
||||
*/
|
||||
public static function from(Result $result): self
|
||||
{
|
||||
return new self($result->pagination);
|
||||
return new self($result->links, $result->meta);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current active cursor.
|
||||
* Return the cursor value (page number) based on the last set action.
|
||||
*/
|
||||
public function cursor(): string
|
||||
{
|
||||
return $this->pagination->cursor;
|
||||
switch ($this->action) {
|
||||
case 'first':
|
||||
return '1';
|
||||
|
||||
case 'after':
|
||||
// Try parsing from 'next' link
|
||||
if ($this->links && !empty($this->links->next)) {
|
||||
return $this->parsePageFromUrl($this->links->next);
|
||||
}
|
||||
// Fallback to current_page + 1
|
||||
return isset($this->meta->current_page)
|
||||
? (string)($this->meta->current_page + 1)
|
||||
: '1';
|
||||
|
||||
case 'before':
|
||||
if ($this->links && !empty($this->links->prev)) {
|
||||
return $this->parsePageFromUrl($this->links->prev);
|
||||
}
|
||||
// Fallback to current_page - 1
|
||||
return isset($this->meta->current_page)
|
||||
? (string)($this->meta->current_page - 1)
|
||||
: '1';
|
||||
|
||||
default:
|
||||
// Default to current page
|
||||
return isset($this->meta->current_page)
|
||||
? (string)$this->meta->current_page
|
||||
: '1';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Paginator to fetch the next set of results.
|
||||
* Parse the 'page' query parameter from a URL.
|
||||
*/
|
||||
private function parsePageFromUrl(string $url): string
|
||||
{
|
||||
$parts = parse_url($url);
|
||||
if (empty($parts['query'])) {
|
||||
return '1';
|
||||
}
|
||||
parse_str($parts['query'], $vars);
|
||||
return $vars['page'] ?? '1';
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the first page.
|
||||
*/
|
||||
public function first(): self
|
||||
{
|
||||
$this->action = 'first';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Paginator to fetch the first set of results.
|
||||
* Fetch the next page (after).
|
||||
*/
|
||||
public function next(): self
|
||||
{
|
||||
$this->action = 'after';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Paginator to fetch the last set of results.
|
||||
* Fetch the previous page (before).
|
||||
*/
|
||||
public function back(): self
|
||||
{
|
||||
$this->action = 'before';
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use Illuminate\Auth\AuthenticationException;
|
||||
use Illuminate\Http\Request;
|
||||
use stdClass;
|
||||
|
||||
abstract class CheckCredentials
|
||||
abstract class CheckCredentials extends UseParameters
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
|
||||
@@ -6,9 +6,9 @@ use Anikeen\Id\Exceptions\MissingScopeException;
|
||||
use Closure;
|
||||
use Illuminate\Auth\AuthenticationException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CheckForAnyScope
|
||||
class CheckForAnyScope extends UseParameters
|
||||
{
|
||||
/**
|
||||
* Handle the incoming request.
|
||||
@@ -17,7 +17,7 @@ class CheckForAnyScope
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, ...$scopes): Response
|
||||
{
|
||||
if (!$request->user() || !$request->user()->anikeenToken()) {
|
||||
if (!$request->user() || !method_exists($request->user(), 'anikeenToken') || !$request->user()->anikeenToken()) {
|
||||
throw new AuthenticationException;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ use Anikeen\Id\Exceptions\MissingScopeException;
|
||||
use Closure;
|
||||
use Illuminate\Auth\AuthenticationException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CheckScopes
|
||||
class CheckScopes extends UseParameters
|
||||
{
|
||||
/**
|
||||
* Handle the incoming request.
|
||||
@@ -17,7 +17,7 @@ class CheckScopes
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, ...$scopes): Response
|
||||
{
|
||||
if (!$request->user() || !$request->user()->anikeenToken()) {
|
||||
if (!$request->user() || !method_exists($request->user(), 'anikeenToken') || !$request->user()->anikeenToken()) {
|
||||
throw new AuthenticationException;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,35 +2,62 @@
|
||||
|
||||
namespace Anikeen\Id\Http\Middleware;
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Anikeen\Id\ApiTokenCookieFactory;
|
||||
use Anikeen\Id\Facades\AnikeenId;
|
||||
use Closure;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class CreateFreshApiToken
|
||||
{
|
||||
/**
|
||||
* The API token cookie factory instance.
|
||||
*
|
||||
* @var ApiTokenCookieFactory
|
||||
*/
|
||||
protected $cookieFactory;
|
||||
|
||||
/**
|
||||
* The authentication guard.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $guard;
|
||||
protected $guard;
|
||||
|
||||
/**
|
||||
* Create a new middleware instance.
|
||||
*
|
||||
* @param ApiTokenCookieFactory $cookieFactory
|
||||
* @return void
|
||||
*/
|
||||
public function __construct(protected ApiTokenCookieFactory $cookieFactory)
|
||||
public function __construct(ApiTokenCookieFactory $cookieFactory)
|
||||
{
|
||||
//
|
||||
$this->cookieFactory = $cookieFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify the guard for the middleware.
|
||||
*
|
||||
* @param string|null $guard
|
||||
* @return string
|
||||
*/
|
||||
public static function using($guard = null)
|
||||
{
|
||||
$guard = is_null($guard) ? '' : ':' . $guard;
|
||||
|
||||
return static::class . $guard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param Request $request
|
||||
* @param Closure $next
|
||||
* @param string|null $guard
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string $guard = null): mixed
|
||||
public function handle($request, Closure $next, $guard = null)
|
||||
{
|
||||
$this->guard = $guard;
|
||||
|
||||
@@ -47,8 +74,12 @@ class CreateFreshApiToken
|
||||
|
||||
/**
|
||||
* Determine if the given request should receive a fresh token.
|
||||
*
|
||||
* @param Request $request
|
||||
* @param Response $response
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldReceiveFreshToken(Request $request, Response $response): bool
|
||||
protected function shouldReceiveFreshToken($request, $response)
|
||||
{
|
||||
return $this->requestShouldReceiveFreshToken($request) &&
|
||||
$this->responseShouldReceiveFreshToken($response);
|
||||
@@ -56,25 +87,37 @@ class CreateFreshApiToken
|
||||
|
||||
/**
|
||||
* Determine if the request should receive a fresh token.
|
||||
*
|
||||
* @param Request $request
|
||||
* @return bool
|
||||
*/
|
||||
protected function requestShouldReceiveFreshToken(Request $request): bool
|
||||
protected function requestShouldReceiveFreshToken($request)
|
||||
{
|
||||
return $request->isMethod('GET') && $request->user($this->guard);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the response should receive a fresh token.
|
||||
*
|
||||
* @param Response $response
|
||||
* @return bool
|
||||
*/
|
||||
protected function responseShouldReceiveFreshToken(Response $response): bool
|
||||
protected function responseShouldReceiveFreshToken($response)
|
||||
{
|
||||
return !$this->alreadyContainsToken($response);
|
||||
return ($response instanceof Response ||
|
||||
$response instanceof JsonResponse) &&
|
||||
!$this->alreadyContainsToken($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given response already contains an API token.
|
||||
*
|
||||
* This avoids us overwriting a just "refreshed" token.
|
||||
*
|
||||
* @param Response $response
|
||||
* @return bool
|
||||
*/
|
||||
protected function alreadyContainsToken(Response $response): bool
|
||||
protected function alreadyContainsToken($response)
|
||||
{
|
||||
foreach ($response->headers->getCookies() as $cookie) {
|
||||
if ($cookie->getName() === AnikeenId::cookie()) {
|
||||
@@ -84,4 +127,4 @@ class CreateFreshApiToken
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Anikeen\Id\Traits;
|
||||
namespace Anikeen\Id;
|
||||
|
||||
use Anikeen\Id\Result;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
|
||||
|
||||
@@ -24,13 +23,11 @@ trait OauthTrait
|
||||
],
|
||||
]);
|
||||
|
||||
$result = new Result($response, null);
|
||||
$result = new Result($response, null, $this);
|
||||
} catch (RequestException $exception) {
|
||||
$result = new Result($exception->getResponse(), $exception);
|
||||
$result = new Result($exception->getResponse(), $exception, $this);
|
||||
}
|
||||
|
||||
$result->anikeenId = $this;
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,11 @@ use Anikeen\Id\Auth\UserProvider;
|
||||
use Anikeen\Id\Contracts;
|
||||
use Anikeen\Id\Helpers\JwtParser;
|
||||
use Anikeen\Id\Repository;
|
||||
use Illuminate\Auth\AuthManager;
|
||||
use Illuminate\Auth\RequestGuard;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Http\Request;
|
||||
use InvalidArgumentException;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AnikeenIdServiceProvider extends ServiceProvider
|
||||
@@ -21,9 +24,7 @@ class AnikeenIdServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
$this->publishes([
|
||||
dirname(__DIR__, 3) . '/config/anikeen-id.php' => config_path('anikeen-id.php'),
|
||||
], 'config');
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -31,7 +32,6 @@ class AnikeenIdServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(dirname(__DIR__, 3) . '/config/anikeen-id.php', 'anikeen-id');
|
||||
$this->app->singleton(Contracts\AppTokenRepository::class, Repository\AppTokenRepository::class);
|
||||
$this->app->singleton(AnikeenId::class, function () {
|
||||
return new AnikeenId;
|
||||
@@ -41,15 +41,28 @@ class AnikeenIdServiceProvider extends ServiceProvider
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the token guard.
|
||||
* Register the `anikeen` guard driver and user provider.
|
||||
*
|
||||
* Laravel binds non-static extend() closures to the AuthManager, so these closures are
|
||||
* static and use nothing but their arguments.
|
||||
*/
|
||||
protected function registerGuard(): void
|
||||
{
|
||||
Auth::resolved(function ($auth) {
|
||||
$auth->extend('anikeen-id', function ($app, $name, array $config) {
|
||||
return tap($this->makeGuard($config), function ($guard) {
|
||||
$this->app->refresh('request', $guard, 'setRequest');
|
||||
});
|
||||
$this->callAfterResolving('auth', static function (AuthManager $auth): void {
|
||||
$auth->provider('anikeen', static fn (Application $app, array $config) => new AnikeenIdUserProvider(
|
||||
$app->make(AnikeenId::class),
|
||||
$app->make('request'),
|
||||
$config['model'] ?? $app['config']->get('auth.providers.users.model'),
|
||||
$config['fields'] ?? [],
|
||||
$config['column'] ?? null,
|
||||
));
|
||||
|
||||
$auth->extend('anikeen', static function (Application $app, string $name, array $config): RequestGuard {
|
||||
$guard = AnikeenIdServiceProvider::makeGuard($app, $config);
|
||||
|
||||
$app->refresh('request', $guard, 'setRequest');
|
||||
|
||||
return $guard;
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -57,15 +70,20 @@ class AnikeenIdServiceProvider extends ServiceProvider
|
||||
/**
|
||||
* Make an instance of the token guard.
|
||||
*/
|
||||
protected function makeGuard(array $config): RequestGuard
|
||||
public static function makeGuard(Application $app, array $config): RequestGuard
|
||||
{
|
||||
return new RequestGuard(function ($request) use ($config) {
|
||||
$providerName = $config['provider'] ?? $app['config']->get('auth.defaults.provider', 'users');
|
||||
$provider = $app['auth']->createUserProvider($providerName)
|
||||
?? throw new InvalidArgumentException("Authentication user provider [$providerName] is not configured.");
|
||||
$providerConfig = $app['config']->get("auth.providers.$providerName", []);
|
||||
|
||||
return new RequestGuard(static function (Request $request) use ($app, $provider, $providerName, $providerConfig, $config) {
|
||||
return (new TokenGuard(
|
||||
new UserProvider(Auth::createUserProvider($config['provider']), $config['provider']),
|
||||
$this->app->make('encrypter'),
|
||||
$this->app->make(JwtParser::class)
|
||||
new UserProvider($provider, $providerName, $config['column'] ?? $providerConfig['column'] ?? null),
|
||||
$app->make('encrypter'),
|
||||
$app->make(JwtParser::class)
|
||||
))->user($request);
|
||||
}, $this->app['request']);
|
||||
}, $app['request'], $provider);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,117 +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 AnikeenId $anikeenId;
|
||||
private ?string $accessTokenField = null;
|
||||
private array $fields;
|
||||
private string $model;
|
||||
private Request $request;
|
||||
|
||||
public function __construct(
|
||||
AnikeenId $anikeenId,
|
||||
Request $request,
|
||||
string $model,
|
||||
array $fields,
|
||||
?string $accessTokenField = null
|
||||
)
|
||||
{
|
||||
$this->request = $request;
|
||||
$this->model = $model;
|
||||
$this->fields = $fields;
|
||||
$this->accessTokenField = $accessTokenField;
|
||||
$this->anikeenId = $anikeenId;
|
||||
}
|
||||
|
||||
public function retrieveById(mixed $identifier): Builder|Model|null
|
||||
{
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?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 = [],
|
||||
private ?string $column = null,
|
||||
) {
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the user of an Anikeen ID (the `sub` of an access token) by the provider's `column`,
|
||||
* else `services.anikeen.user_id_column`, else AnikeenId::getUserIdField() (`anikeen_id`).
|
||||
*/
|
||||
public function retrieveByAnikeenId(string $anikeenId): ?Authenticatable
|
||||
{
|
||||
$column = $this->column ?: (config('services.anikeen.user_id_column') ?: AnikeenId::getUserIdField());
|
||||
|
||||
return $this->newModelQuery()->where($column, $anikeenId)->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();
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,14 @@ class AppTokenRepository implements Repository
|
||||
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
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
* @property null|string $company_name
|
||||
* @property null|string $first_name
|
||||
* @property null|string $last_name
|
||||
* @property null|string $address_2
|
||||
* @property null|string $address
|
||||
* @property null|string $house_number
|
||||
* @property null|string $postal_code
|
||||
* @property null|string $city
|
||||
* @property null|string $state
|
||||
* @property string $country_iso
|
||||
* @property null|string $phone_number
|
||||
* @property null|string $email
|
||||
* @property bool $primary
|
||||
* @property bool $primary_billing_address
|
||||
*/
|
||||
class Address extends BaseResource
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Update given address from the current user.
|
||||
*
|
||||
* VAT is calculated based on the billing address and shown in the address response.
|
||||
*
|
||||
* @param array{
|
||||
* company_name: null|string,
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* address_2: null|string,
|
||||
* address: string,
|
||||
* house_number: null|string,
|
||||
* postal_code: string,
|
||||
* city: string,
|
||||
* state: null|string,
|
||||
* country_iso: string,
|
||||
* phone_number: null|string,
|
||||
* email: null|string,
|
||||
* primary: bool,
|
||||
* primary_billing_address: bool
|
||||
* } $attributes The address data:
|
||||
* - company_name: Company name (optional)
|
||||
* - first_name: First name (required when set)
|
||||
* - last_name: Last name (required when set)
|
||||
* - address: Address line 1 (e.g. street address, P.O. Box, etc.)
|
||||
* - address_2: Address line 2 (optional, e.g. apartment number, c/o, etc.)
|
||||
* - house_number: House number (optional)
|
||||
* - postal_code: Postal code (required when set)
|
||||
* - city: City (required when set)
|
||||
* - state: State (optional, e.g. province, region, etc.)
|
||||
* - country_iso: Country ISO code (required when set, e.g. US, CA, etc.)
|
||||
* - phone_number: Phone number (optional)
|
||||
* - email: Email address (optional, e.g. for delivery notifications)
|
||||
* - primary: Whether this address should be the primary address (optional)
|
||||
* - primary_billing_address: Whether this address should be the primary billing address (optional)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function update(array $attributes = []): self
|
||||
{
|
||||
return (new self(fn() => $this->billable->anikeenId()
|
||||
->request('PUT', sprintf('v1/addresses/%s', $this->id), $attributes)))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete given address from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
return $this->billable->anikeenId()
|
||||
->request('DELETE', sprintf('v1/addresses/%s', $this->id))->success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Throwable;
|
||||
|
||||
class Addresses extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Creates a new address for the current user.
|
||||
*
|
||||
* @param array{
|
||||
* company_name: null|string,
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* address: string,
|
||||
* address_2: null|string,
|
||||
* house_number: null|string,
|
||||
* postal_code: string,
|
||||
* city: string,
|
||||
* state: null|string,
|
||||
* country_iso: string,
|
||||
* phone_number: null|string,
|
||||
* email: null|string,
|
||||
* primary: bool,
|
||||
* primary_billing_address: bool
|
||||
* } $attributes The address data:
|
||||
* - company_name: Company name (optional)
|
||||
* - first_name: First name
|
||||
* - last_name: Last name
|
||||
* - address: Address line 1 (e.g. street address, P.O. Box, etc.)
|
||||
* - address_2: Address line 2 (optional, e.g. apartment number, c/o, etc.)
|
||||
* - house_number: House number (optional)
|
||||
* - postal_code: Postal code
|
||||
* - city: City
|
||||
* - state: State (optional, e.g. province, region, etc.)
|
||||
* - country_iso: Country ISO code (e.g. US, CA, etc.)
|
||||
* - phone_number: Phone number (optional)
|
||||
* - email: Email address (optional, e.g. for delivery notifications)
|
||||
* - primary: Whether this address should be the primary address (optional)
|
||||
* - primary_billing_address: Whether this address should be the primary billing address (optional)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function create(array $attributes = []): Address
|
||||
{
|
||||
return (new Address(fn() => $this->billable->anikeenId()
|
||||
->request('POST', 'v1/addresses', $attributes)))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function find(string $id): ?Address
|
||||
{
|
||||
return (new Address(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/addresses/%s', $id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default address from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function defaultBillingAddress(): Address
|
||||
{
|
||||
return (new Address(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/addresses/%s', $this->billable->getUserData()->billing_address_id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current user has a default billing address.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function hasDefaultBillingAddress(): bool
|
||||
{
|
||||
return $this->billable->getUserData()->billing_address_id !== null;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?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,
|
||||
* monthly_cap?: null|float|string,
|
||||
* predecessor_id?: null|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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasSubscriptionStatus;
|
||||
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 $monthly_cap net, at most this per calendar month (hour and day units)
|
||||
* @property ?float $expected_monthly_price gross estimate for a month (720 hours, at most the monthly cap)
|
||||
* @property ?string $predecessor_id the subscription this one replaced (a resize); they share the monthly cap
|
||||
* @property ?float $vat_rate
|
||||
* @property bool $active
|
||||
* @property bool $autorenew
|
||||
* @property bool $cancelled
|
||||
* @property ?string $status draft, trial, active, paused, cancelling, expired or cancelled, see status()
|
||||
* @property ?string $cancels_at when a scheduled cancellation takes effect
|
||||
* @property ?string $trial_ends_at
|
||||
* @property ?string $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
|
||||
{
|
||||
use HasSubscriptionStatus;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?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,
|
||||
* monthly_cap?: null|float|string,
|
||||
* predecessor_id?: null|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.
|
||||
* monthly_cap: net, at most this per calendar month (hour and day units only,
|
||||
* at most 2 decimals, not below price; null = no cap).
|
||||
* predecessor_id: the subscription this one replaces (a resize; same user and
|
||||
* app, checked out, not cancelled): both share the monthly cap within a month.
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Anikeen\Id\Exceptions\CollectionException;
|
||||
use Anikeen\Id\Helpers\Paginator;
|
||||
use Anikeen\Id\Result;
|
||||
use Closure;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
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
|
||||
{
|
||||
private Closure $callable;
|
||||
public ?Result $result = null;
|
||||
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the collection of resources as an array.
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return (array)$this->result->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the collection of resources as a JSON string.
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the collection of resources.
|
||||
*/
|
||||
public function paginate(): Result
|
||||
{
|
||||
return $this->result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Resource based on the ID.
|
||||
*/
|
||||
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});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Exceptions\ConfirmationRequiredException;
|
||||
use Anikeen\Id\Exceptions\ResourceException;
|
||||
use Anikeen\Id\Result;
|
||||
use JsonSerializable;
|
||||
|
||||
#[\AllowDynamicProperties]
|
||||
abstract class BaseResource implements JsonSerializable
|
||||
{
|
||||
public Result $result;
|
||||
|
||||
/**
|
||||
* @throws ResourceException
|
||||
*/
|
||||
public function __construct(callable $callable)
|
||||
{
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the collection of resources as an array.
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return (array)$this->result->data;
|
||||
}
|
||||
|
||||
public function __get(string $name)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function __isset(string $name): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
|
||||
class Countries extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function find(string $id): ?BaseResource
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
*/
|
||||
class Invoice extends BaseResource
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Get temporary download url from given invoice.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function getInvoiceTemporaryUrl(): ?string
|
||||
{
|
||||
return $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/invoices/%s', $this->id))
|
||||
->data
|
||||
->temporary_url ?? null;
|
||||
}
|
||||
}␍
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
|
||||
class Invoices extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function find(string $id): ?Invoice
|
||||
{
|
||||
return (new Invoice(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/invoices/%s', $id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Anikeen\Id\Concerns\HasConfirmationUrl;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
* @property null|string $confirmation_url where the user confirms it (third-party apps)
|
||||
*/
|
||||
class Order extends BaseResource
|
||||
{
|
||||
use HasBillable;
|
||||
use HasConfirmationUrl;
|
||||
|
||||
/**
|
||||
* Update given order from the current user.
|
||||
*
|
||||
* VAT is calculated based on the billing address and shown in the order response.
|
||||
*
|
||||
* The billing and shipping addresses are each persisted as standalone Address entities
|
||||
* in the database, but are also embedded (deep-copied) into the Order object itself
|
||||
* rather than merely referenced. This guarantees that the order retains its own snapshot
|
||||
* of both addresses for future reference.
|
||||
*
|
||||
* @param array{
|
||||
* billing_address: array{
|
||||
* company_name: null|string,
|
||||
* first_name: null|string,
|
||||
* last_name: null|string,
|
||||
* address: null|string,
|
||||
* address_2: null|string,
|
||||
* house_number: null|string,
|
||||
* city: null|string,
|
||||
* state: null|string,
|
||||
* postal_code: null|string,
|
||||
* country_iso: string,
|
||||
* phone_number: null|string,
|
||||
* email: null|string
|
||||
* },
|
||||
* shipping_address: null|array{
|
||||
* company_name: null|string,
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* address: string,
|
||||
* address_2: null|string,
|
||||
* house_number: null|string,
|
||||
* city: string,
|
||||
* state: null|string,
|
||||
* postal_code: string,
|
||||
* country_iso: string,
|
||||
* phone_number: null|string,
|
||||
* email: null|string
|
||||
* }
|
||||
* } $attributes The order data:
|
||||
* - billing_address: Billing address (ISO 3166-1 alpha-2 country code)
|
||||
* - shipping_address: Shipping address for physical items (first name, last name, address, postal code, city, ISO 3166-1 alpha-2 country code)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function update(array $attributes = []): self
|
||||
{
|
||||
return (new self(fn() => $this->billable->anikeenId()
|
||||
->request('PUT', sprintf('v1/orders/%s', $this->id), $attributes)))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checkout given order from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function checkout(): self
|
||||
{
|
||||
return (new self(fn() => $this->billable->anikeenId()
|
||||
->request('PUT', sprintf('v1/orders/%s/checkout', $this->id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke given order from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function revoke(): self
|
||||
{
|
||||
return (new self(fn() => $this->billable->anikeenId()
|
||||
->request('PUT', sprintf('v1/orders/%s/revoke', $this->id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete given order from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
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.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function orderItems(array $parameters = []): OrderItems
|
||||
{
|
||||
return OrderItems::builder(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/orders/%s/items', $this->id), [], $parameters))
|
||||
->setBillable($this->billable)
|
||||
->setParent($this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Anikeen\Id\Concerns\HasParent;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
*/
|
||||
class OrderItem extends BaseResource
|
||||
{
|
||||
use HasBillable;
|
||||
use HasParent;
|
||||
|
||||
/**
|
||||
* Update given order item from given order.
|
||||
*
|
||||
* VAT is calculated based on the billing address and shown in the order item response.
|
||||
*
|
||||
* @param array{
|
||||
* items: array<array{
|
||||
* type: string,
|
||||
* name: string,
|
||||
* description: string,
|
||||
* price: float|int,
|
||||
* unit: string,
|
||||
* units: int
|
||||
* }>
|
||||
* } $attributes The order data:
|
||||
* - items: Array of order items, each with type, name, description, price, unit, and quantity
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function update(array $attributes = []): self
|
||||
{
|
||||
return (new self(fn() => $this->billable->anikeenId()
|
||||
->request('PUT', sprintf('v1/orders/%s/items/%s', $this->parent->id, $this->id), $attributes)))
|
||||
->setBillable($this->billable)
|
||||
->setParent($this->parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete given order item from given order.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
return $this->billable->anikeenId()
|
||||
->request('DELETE', sprintf('v1/orders/%s/items/%s', $this->parent->id, $this->id))->success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Anikeen\Id\Concerns\HasParent;
|
||||
use Throwable;
|
||||
|
||||
class OrderItems extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
use HasParent;
|
||||
|
||||
/**
|
||||
* Create a new order item for given order.
|
||||
*
|
||||
* VAT is calculated based on the billing address and shown in the order item response.
|
||||
*
|
||||
* @param string $orderId The order ID.
|
||||
* @param array{
|
||||
* items: array<array{
|
||||
* type: string,
|
||||
* name: string,
|
||||
* description: string,
|
||||
* price: float|int,
|
||||
* unit: string,
|
||||
* units: int
|
||||
* }>
|
||||
* } $attributes The order data:
|
||||
* - items: Array of order items, each with type, name, description, price, unit, and quantity
|
||||
*
|
||||
* 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
|
||||
{
|
||||
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)
|
||||
->setParent($this->parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function find(string $id): ?OrderItem
|
||||
{
|
||||
return (new OrderItem(fn() => $this->parent->anikeenId()
|
||||
->request('GET', sprintf('v1/orders/%s/items/%s', $this->parent->id, $id))))
|
||||
->setBillable($this->billable)
|
||||
->setParent($this->parent);
|
||||
}
|
||||
}␍
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Throwable;
|
||||
|
||||
class Orders extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Creates a new order for the current user.
|
||||
*
|
||||
* VAT is calculated based on the billing address and shown in the order response.
|
||||
*
|
||||
* The billing and shipping addresses are each persisted as standalone Address entities
|
||||
* in the database, but are also embedded (deep-copied) into the Order object itself
|
||||
* rather than merely referenced. This guarantees that the order retains its own snapshot
|
||||
* of both addresses for future reference.
|
||||
*
|
||||
* @param array{
|
||||
* billing_address: array{
|
||||
* company_name: null|string,
|
||||
* first_name: null|string,
|
||||
* last_name: null|string,
|
||||
* address: null|string,
|
||||
* address_2: null|string,
|
||||
* house_number: null|string,
|
||||
* city: null|string,
|
||||
* state: null|string,
|
||||
* postal_code: null|string,
|
||||
* country_iso: string,
|
||||
* phone_number: null|string,
|
||||
* email: null|string
|
||||
* },
|
||||
* shipping_address: null|array{
|
||||
* company_name: null|string,
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* address: string,
|
||||
* address_2: null|string,
|
||||
* house_number: null|string,
|
||||
* city: string,
|
||||
* state: null|string,
|
||||
* postal_code: string,
|
||||
* country_iso: string,
|
||||
* phone_number: null|string,
|
||||
* email: null|string
|
||||
* },
|
||||
* items: array<array{
|
||||
* type: string,
|
||||
* name: string,
|
||||
* description?: null|string,
|
||||
* image_url?: null|string,
|
||||
* price?: float|int|string,
|
||||
* gross_price?: float|int|string,
|
||||
* unit: string,
|
||||
* units: int
|
||||
* }>
|
||||
* } $attributes The order data:
|
||||
* - billing_address: Billing address (ISO 3166-1 alpha-2 country code)
|
||||
* - shipping_address: Shipping address for physical items (first name, last name, address, postal code, city, ISO 3166-1 alpha-2 country code)
|
||||
* - items: Array of order items:
|
||||
* - type: digital, physical or physical-reduced (VAT category)
|
||||
* - 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
|
||||
{
|
||||
return (new Order(fn() => $this->billable->anikeenId()
|
||||
->request('POST', 'v1/orders', $attributes)))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get given order from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function find(string $id): ?Order
|
||||
{
|
||||
return (new Order(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/orders/%s', $id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
*/
|
||||
class PaymentMethod extends BaseResource
|
||||
{
|
||||
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();
|
||||
}
|
||||
}␍
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Throwable;
|
||||
|
||||
class PaymentMethods extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Check if current user has at least one payment method.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function hasPaymentMethod(): bool
|
||||
{
|
||||
return $this->result->count() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current user has a default payment method.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function hasDefaultPaymentMethod(): bool
|
||||
{
|
||||
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}
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function find(string $id): ?PaymentMethod
|
||||
{
|
||||
return (new PaymentMethod(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/payment-methods/%s', $id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasParent;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
*/
|
||||
class SshKey extends BaseResource
|
||||
{
|
||||
use HasParent;
|
||||
|
||||
/**
|
||||
* Deletes a given ssh key for the currently authed user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
return $this->parent->delete(sprintf('v1/ssh-keys/%s', $this->id))->success();
|
||||
}
|
||||
}␍
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasParent;
|
||||
use Throwable;
|
||||
|
||||
class SshKeys extends BaseCollection
|
||||
{
|
||||
use HasParent;
|
||||
|
||||
/**
|
||||
* Creates ssh key for the currently authed user.
|
||||
*
|
||||
* @param string $publicKey The public key to be added
|
||||
* @param string|null $name The name of the key (optional)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function create(string $publicKey, ?string $name = null): SshKey
|
||||
{
|
||||
return (new SshKey(fn() => $this->parent->post('v1/ssh-keys', [
|
||||
'public_key' => $publicKey,
|
||||
'name' => $name,
|
||||
])))->setParent($this->parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function find(string $id): ?SshKey
|
||||
{
|
||||
return (new SshKey(fn() => $this->parent->get(sprintf('v1/ssh-keys/%s', $id))))->setParent($this->parent);
|
||||
}
|
||||
}␍
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Anikeen\Id\Concerns\HasConfirmationUrl;
|
||||
use Anikeen\Id\Concerns\HasSubscriptionStatus;
|
||||
use Anikeen\Id\Contracts\AppTokenRepository;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
* @property string $name
|
||||
* @property string $description
|
||||
* @property string $unit
|
||||
* @property float $price
|
||||
* @property ?float $monthly_cap net, at most this per calendar month (hour and day units)
|
||||
* @property ?float $expected_monthly_price gross estimate for a month (720 hours, at most the monthly cap)
|
||||
* @property ?string $predecessor_id the subscription this one replaced (a resize); they share the monthly cap
|
||||
* @property float $vat_rate
|
||||
* @property array $payload
|
||||
* @property bool $active
|
||||
* @property bool $autorenew
|
||||
* @property bool $cancelled
|
||||
* @property ?string $status draft, trial, active, paused, cancelling, expired or cancelled, see status()
|
||||
* @property ?string $starts_at
|
||||
* @property string $ends_at
|
||||
* @property ?string $cancels_at when a scheduled cancellation takes effect
|
||||
* @property ?string $trial_ends_at
|
||||
* @property null|string $confirmation_url where the user confirms it (third-party apps)
|
||||
*/
|
||||
class Subscription extends BaseResource
|
||||
{
|
||||
use HasBillable;
|
||||
use HasConfirmationUrl;
|
||||
use HasSubscriptionStatus;
|
||||
|
||||
/**
|
||||
* Update a given subscription from the current user.
|
||||
*
|
||||
* @param array{
|
||||
* group: string,
|
||||
* name: string,
|
||||
* description: null|string,
|
||||
* unit: string,
|
||||
* price: float,
|
||||
* monthly_cap?: null|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)
|
||||
* - monthly_cap: Net, at most this per calendar month (hour and day units; optional)
|
||||
* - 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).
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function checkout(): self
|
||||
{
|
||||
return (new self(fn() => $this->billable->anikeenId()
|
||||
->request('PUT', sprintf('v1/subscriptions/%s/checkout', $this->id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a given running subscription from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function revoke(bool $refund = false): self
|
||||
{
|
||||
$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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a given running subscription from the current user.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function resume(): self
|
||||
{
|
||||
return (new self(fn() => $this->billable->anikeenId()
|
||||
->request('PUT', sprintf('v1/subscriptions/%s/resume', $this->id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
use Anikeen\Id\Contracts\AppTokenRepository;
|
||||
use Anikeen\Id\Exceptions\ResourceException;
|
||||
use Throwable;
|
||||
|
||||
class Subscriptions extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* Create a new subscription for the current user.
|
||||
*
|
||||
* @param array{
|
||||
* group: null|string,
|
||||
* name: string,
|
||||
* description: null|string,
|
||||
* unit: string,
|
||||
* price: float,
|
||||
* monthly_cap?: null|float,
|
||||
* predecessor_id?: null|string,
|
||||
* vat_rate: float,
|
||||
* payload: null|array,
|
||||
* ends_at: null|string
|
||||
* } $attributes The subscription data:
|
||||
* - group: The group (optional)
|
||||
* - name: The name
|
||||
* - description: The description (optional)
|
||||
* - unit: The unit (e.g. "hour", "day", "week", "month", "year")
|
||||
* - price: The price per unit
|
||||
* - monthly_cap: Net, at most this per calendar month (hour and day units, max. 2 decimals; optional)
|
||||
* - predecessor_id: The subscription this one replaces (a resize); both share the monthly cap (optional)
|
||||
* - vat_rate: The VAT rate (required when set)
|
||||
* - payload: The payload (optional)
|
||||
* - ends_at: The end date (optional)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function create(array $attributes): Subscription
|
||||
{
|
||||
return (new Subscription(fn() => $this->billable->anikeenId()
|
||||
->request('POST', 'v1/subscriptions', $attributes)))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws ResourceException
|
||||
*/
|
||||
public function find(string $id): ?Subscription
|
||||
{
|
||||
return (new Subscription(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/subscriptions/%s', $id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
|
||||
class Transaction extends BaseResource
|
||||
{
|
||||
use HasBillable;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Resources;
|
||||
|
||||
use Anikeen\Id\Concerns\HasBillable;
|
||||
|
||||
class Transactions extends BaseCollection
|
||||
{
|
||||
use HasBillable;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function find(string $id): ?Transaction
|
||||
{
|
||||
return (new Transaction(fn() => $this->billable->anikeenId()
|
||||
->request('GET', sprintf('v1/transactions/%s', $id))))
|
||||
->setBillable($this->billable);
|
||||
}
|
||||
}
|
||||
+121
-86
@@ -9,67 +9,112 @@ use stdClass;
|
||||
|
||||
class Result
|
||||
{
|
||||
|
||||
/**
|
||||
* Query successful.
|
||||
* Was the API call successful?
|
||||
*/
|
||||
public bool $success = false;
|
||||
|
||||
/**
|
||||
* Query result data.
|
||||
* Response data: either an array of items (paginated) or a single object (non-paginated)
|
||||
*/
|
||||
public array $data = [];
|
||||
public mixed $data = [];
|
||||
|
||||
/**
|
||||
* Total amount of result data.
|
||||
* Total number of items: uses meta.total, root total, or falls back to count/data existence
|
||||
*/
|
||||
public int $total = 0;
|
||||
|
||||
/**
|
||||
* Status Code.
|
||||
* HTTP status code
|
||||
*/
|
||||
public int $status = 0;
|
||||
|
||||
/**
|
||||
* AnikeenId response pagination cursor.
|
||||
* Pagination links (first, last, prev, next) as stdClass or null
|
||||
*/
|
||||
public ?stdClass $pagination;
|
||||
public ?stdClass $links = null;
|
||||
|
||||
/**
|
||||
* Original AnikeenId instance.
|
||||
*
|
||||
* @var AnikeenId
|
||||
* Pagination meta (current_page, last_page etc.) as stdClass or null
|
||||
*/
|
||||
public ?stdClass $meta = null;
|
||||
|
||||
/**
|
||||
* Paginator helper to retrieve next/prev pages
|
||||
*/
|
||||
public ?Paginator $paginator = null;
|
||||
|
||||
/**
|
||||
* Reference to the original AnikeenId client
|
||||
*/
|
||||
public AnikeenId $anikeenId;
|
||||
|
||||
public function __construct(public ?ResponseInterface $response, public ?Exception $exception = null, public ?Paginator $paginator = null)
|
||||
{
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param ResponseInterface|null $response
|
||||
* @param Exception|null $exception
|
||||
* @param AnikeenId $anikeenId
|
||||
*/
|
||||
public function __construct(
|
||||
public ?ResponseInterface $response,
|
||||
public ?Exception $exception,
|
||||
AnikeenId $anikeenId
|
||||
) {
|
||||
$this->anikeenId = $anikeenId;
|
||||
$this->success = $exception === null;
|
||||
$this->status = $response ? $response->getStatusCode() : 500;
|
||||
$jsonResponse = $response ? @json_decode($response->getBody()->getContents(), false) : null;
|
||||
if ($jsonResponse !== null) {
|
||||
$this->setProperty($jsonResponse, 'data');
|
||||
$this->setProperty($jsonResponse, 'total');
|
||||
$this->setProperty($jsonResponse, 'pagination');
|
||||
$this->paginator = Paginator::from($this);
|
||||
|
||||
$raw = $response ? (string) $response->getBody() : null;
|
||||
$json = $raw ? @json_decode($raw, false) : null;
|
||||
|
||||
if ($json !== null) {
|
||||
// Pagination info
|
||||
$this->links = $json->links ?? null;
|
||||
$this->meta = $json->meta ?? null;
|
||||
|
||||
// Determine data shape
|
||||
if (isset($json->data)) {
|
||||
if ($this->links !== null || $this->meta !== null) {
|
||||
// Paginated: always array
|
||||
$this->data = is_array($json->data) ? $json->data : [$json->data];
|
||||
} else {
|
||||
// Non-paginated: single object
|
||||
$this->data = $json->data;
|
||||
}
|
||||
} else {
|
||||
// No 'data' key: treat entire payload
|
||||
if ($this->links !== null || $this->meta !== null) {
|
||||
// Paginated but missing data key: fallback to empty array
|
||||
$this->data = [];
|
||||
} else {
|
||||
$this->data = $json;
|
||||
}
|
||||
}
|
||||
|
||||
// Total items
|
||||
if (isset($json->meta->total)) {
|
||||
$this->total = (int) $json->meta->total;
|
||||
} elseif (isset($json->total)) {
|
||||
$this->total = (int) $json->total;
|
||||
} else {
|
||||
// count array or single object
|
||||
if (is_array($this->data)) {
|
||||
$this->total = count($this->data);
|
||||
} elseif ($this->data !== null) {
|
||||
$this->total = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize paginator only if pagination present
|
||||
if ($this->links !== null || $this->meta !== null) {
|
||||
$this->paginator = Paginator::from($this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a class attribute by given JSON Response Body.
|
||||
*/
|
||||
private function setProperty(stdClass $jsonResponse, string $responseProperty, string $attribute = null): void
|
||||
{
|
||||
$classAttribute = $attribute ?? $responseProperty;
|
||||
if (property_exists($jsonResponse, $responseProperty)) {
|
||||
$this->{$classAttribute} = $jsonResponse->{$responseProperty};
|
||||
} elseif ($responseProperty === 'data') {
|
||||
$this->{$classAttribute} = $jsonResponse;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the query was successfully.
|
||||
* Was the request successful?
|
||||
*/
|
||||
public function success(): bool
|
||||
{
|
||||
@@ -77,47 +122,46 @@ class Result
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last HTTP or API error.
|
||||
* Get last error message
|
||||
*/
|
||||
public function error(): string
|
||||
{
|
||||
// TODO Switch Exception response parsing to this->data
|
||||
if ($this->exception === null || !$this->exception->hasResponse()) {
|
||||
if ($this->exception === null || !method_exists($this->exception, 'getResponse')) {
|
||||
return 'Anikeen ID API Unavailable';
|
||||
}
|
||||
$exception = (string)$this->exception->getResponse()->getBody();
|
||||
$exception = @json_decode($exception);
|
||||
if (property_exists($exception, 'message') && !empty($exception->message)) {
|
||||
return $exception->message;
|
||||
$resp = $this->exception->getResponse();
|
||||
$body = $resp ? (string) $resp->getBody() : null;
|
||||
$err = $body ? @json_decode($body) : null;
|
||||
if (isset($err->message) && $err->message !== '') {
|
||||
return $err->message;
|
||||
}
|
||||
|
||||
return $this->exception->getMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shifts the current result (Use for single user/video etc. query).
|
||||
* For paginated data: shift first element; for single object: return it
|
||||
*/
|
||||
public function shift(): mixed
|
||||
{
|
||||
if (!empty($this->data)) {
|
||||
$data = $this->data;
|
||||
|
||||
return array_shift($data);
|
||||
if (is_array($this->data)) {
|
||||
return array_shift($this->data);
|
||||
}
|
||||
|
||||
return null;
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current count of items in dataset.
|
||||
* Count of items in data
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->data);
|
||||
if (is_array($this->data)) {
|
||||
return count($this->data);
|
||||
}
|
||||
return $this->data !== null ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Paginator to fetch the next set of results.
|
||||
* Fetch next page paginator
|
||||
*/
|
||||
public function next(): ?Paginator
|
||||
{
|
||||
@@ -125,7 +169,7 @@ class Result
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Paginator to fetch the last set of results.
|
||||
* Fetch previous page paginator
|
||||
*/
|
||||
public function back(): ?Paginator
|
||||
{
|
||||
@@ -133,71 +177,62 @@ class Result
|
||||
}
|
||||
|
||||
/**
|
||||
* Get rate limit information.
|
||||
* Rate limit info from headers
|
||||
*/
|
||||
public function rateLimit(string $key = null): array|int|string|null
|
||||
public function rateLimit(?string $key = null): array|int|string|null
|
||||
{
|
||||
if (!$this->response) {
|
||||
return null;
|
||||
}
|
||||
$rateLimit = [
|
||||
'limit' => (int)$this->response->getHeaderLine('X-RateLimit-Limit'),
|
||||
'remaining' => (int)$this->response->getHeaderLine('X-RateLimit-Remaining'),
|
||||
'reset' => (int)$this->response->getHeaderLine('Retry-After'),
|
||||
$info = [
|
||||
'limit' => (int) $this->response->getHeaderLine('X-RateLimit-Limit'),
|
||||
'remaining' => (int) $this->response->getHeaderLine('X-RateLimit-Remaining'),
|
||||
'reset' => (int) $this->response->getHeaderLine('Retry-After'),
|
||||
];
|
||||
if ($key === null) {
|
||||
return $rateLimit;
|
||||
}
|
||||
|
||||
return $rateLimit[$key];
|
||||
return $key ? ($info[$key] ?? null) : $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert users in data response.
|
||||
* Insert related users into each data item (for arrays)
|
||||
*/
|
||||
public function insertUsers(string $identifierAttribute = 'user_id', string $insertTo = 'user'): self
|
||||
{
|
||||
$data = $this->data;
|
||||
$userIds = collect($data)->map(function ($item) use ($identifierAttribute) {
|
||||
return $item->{$identifierAttribute};
|
||||
})->toArray();
|
||||
if (count($userIds) === 0) {
|
||||
if (!is_array($this->data)) {
|
||||
return $this;
|
||||
}
|
||||
$users = collect($this->anikeenId->getUsersByIds($userIds)->data);
|
||||
$dataWithUsers = collect($data)->map(function ($item) use ($users, $identifierAttribute, $insertTo) {
|
||||
$item->$insertTo = $users->where('id', $item->{$identifierAttribute})->first();
|
||||
|
||||
return $item;
|
||||
});
|
||||
$this->data = $dataWithUsers->toArray();
|
||||
|
||||
$ids = array_map(fn($item) => $item->{$identifierAttribute} ?? null, $this->data);
|
||||
$ids = array_filter($ids);
|
||||
if (empty($ids)) {
|
||||
return $this;
|
||||
}
|
||||
$users = $this->anikeenId->getUsersByIds($ids)->data;
|
||||
foreach ($this->data as &$item) {
|
||||
$item->{$insertTo} = collect($users)->firstWhere('id', $item->{$identifierAttribute});
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Paginator to fetch the first set of results.
|
||||
* Fetch first page paginator
|
||||
*/
|
||||
public function first(): ?Paginator
|
||||
{
|
||||
return $this->paginator?->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Original response
|
||||
*/
|
||||
public function response(): ?ResponseInterface
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
public function dump(): void
|
||||
{
|
||||
dump($this->data());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the response data, also available as public attribute.
|
||||
* Access raw data
|
||||
*/
|
||||
public function data(): array
|
||||
public function data(): mixed
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,6 @@ class AnikeenIdExtendSocialite
|
||||
{
|
||||
public function handle(SocialiteWasCalled $socialiteWasCalled): void
|
||||
{
|
||||
$socialiteWasCalled->extendSocialite('anikeen-id', Provider::class);
|
||||
$socialiteWasCalled->extendSocialite('anikeen', Provider::class);
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace Anikeen\Id\Socialite;
|
||||
|
||||
use Anikeen\Id\AnikeenId;
|
||||
use Anikeen\Id\Enums\Scope;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Laravel\Socialite\Two\ProviderInterface;
|
||||
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
|
||||
@@ -14,7 +16,7 @@ class Provider extends AbstractProvider implements ProviderInterface
|
||||
/**
|
||||
* Unique Provider Identifier.
|
||||
*/
|
||||
const IDENTIFIER = 'ANIKEEN_ID';
|
||||
const IDENTIFIER = 'ANIKEEN';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
@@ -26,13 +28,21 @@ class Provider extends AbstractProvider implements ProviderInterface
|
||||
*/
|
||||
protected $scopeSeparator = ' ';
|
||||
|
||||
/**
|
||||
* Get the base URL for the API.
|
||||
*/
|
||||
protected function getBaseUrl(): string
|
||||
{
|
||||
return app(AnikeenId::class)->getBaseUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getAuthUrl($state): string
|
||||
{
|
||||
return $this->buildAuthUrlFromBase(
|
||||
'https://id.anikeen.com/oauth/authorize', $state
|
||||
$this->getBaseUrl() . '/oauth/authorize', $state
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,7 +51,7 @@ class Provider extends AbstractProvider implements ProviderInterface
|
||||
*/
|
||||
protected function getTokenUrl(): string
|
||||
{
|
||||
return 'https://id.anikeen.com/oauth/token';
|
||||
return $this->getBaseUrl() . '/oauth/token';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,7 +62,7 @@ class Provider extends AbstractProvider implements ProviderInterface
|
||||
protected function getUserByToken($token)
|
||||
{
|
||||
$response = $this->getHttpClient()->get(
|
||||
'https://id.anikeen.com/api/v1/user', [
|
||||
$this->getBaseUrl() . '/api/v1/user', [
|
||||
'headers' => [
|
||||
'Accept' => 'application/json',
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
@@ -85,4 +95,12 @@ class Provider extends AbstractProvider implements ProviderInterface
|
||||
'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 ?: '/');
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Anikeen\Id\Traits;
|
||||
|
||||
use Anikeen\Id\ApiOperations\Delete;
|
||||
use Anikeen\Id\ApiOperations\Get;
|
||||
use Anikeen\Id\ApiOperations\Post;
|
||||
use Anikeen\Id\Result;
|
||||
|
||||
trait SshKeysTrait
|
||||
{
|
||||
|
||||
use Get, Post, Delete;
|
||||
|
||||
/**
|
||||
* Get currently authed user with Bearer Token
|
||||
*/
|
||||
public function getSshKeysByUserId(int $id): Result
|
||||
{
|
||||
return $this->get("v1/users/$id/ssh-keys/json", [], null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates ssh key for the currently authed user
|
||||
*/
|
||||
public function createSshKey(string $publicKey, string $name = null): Result
|
||||
{
|
||||
return $this->post('v1/ssh-keys', [
|
||||
'public_key' => $publicKey,
|
||||
'name' => $name,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a given ssh key for the currently authed user
|
||||
*/
|
||||
public function deleteSshKey(int $id): Result
|
||||
{
|
||||
return $this->delete("v1/ssh-keys/$id", []);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Anikeen\Id\Traits;
|
||||
|
||||
use Anikeen\Id\ApiOperations\Get;
|
||||
use Anikeen\Id\Result;
|
||||
|
||||
trait UsersTrait
|
||||
{
|
||||
|
||||
use Get;
|
||||
|
||||
/**
|
||||
* Get currently authed user with Bearer Token
|
||||
*/
|
||||
public function getAuthedUser(): Result
|
||||
{
|
||||
return $this->get('v1/user');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new user on behalf of the current user.
|
||||
*/
|
||||
public function createUser(array $parameters): Result
|
||||
{
|
||||
return $this->post('v1/users', $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given email exists.
|
||||
*/
|
||||
public function isEmailExisting(string $email): Result
|
||||
{
|
||||
return $this->post('v1/users/check', [
|
||||
'email' => $email,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user