Files
fotospiel-app/app/Services/LemonSqueezy/LemonSqueezyClient.php
2026-02-04 12:43:40 +01:00

112 lines
3.4 KiB
PHP

<?php
namespace App\Services\LemonSqueezy;
use App\Services\LemonSqueezy\Exceptions\LemonSqueezyException;
use Illuminate\Http\Client\Factory as HttpFactory;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class LemonSqueezyClient
{
public function __construct(
private readonly HttpFactory $http,
) {}
public function get(string $endpoint, array $query = []): array
{
return $this->send('GET', $endpoint, ['query' => $query]);
}
public function post(string $endpoint, array|object $payload = []): array
{
return $this->send('POST', $endpoint, ['json' => $payload]);
}
public function patch(string $endpoint, array|object $payload = []): array
{
return $this->send('PATCH', $endpoint, ['json' => $payload]);
}
public function delete(string $endpoint, array|object $payload = []): array
{
return $this->send('DELETE', $endpoint, ['json' => $payload]);
}
protected function send(string $method, string $endpoint, array $options = []): array
{
$request = $this->preparedRequest();
try {
$response = $request->send(strtoupper($method), ltrim($endpoint, '/'), $options);
} catch (RequestException $exception) {
throw new LemonSqueezyException(
$exception->getMessage(),
$exception->response?->status(),
$exception->response?->json() ?? []
);
}
if ($response->failed()) {
$body = $response->json() ?? [];
$message = Arr::get($body, 'errors.0.detail')
?? Arr::get($body, 'error')
?? Arr::get($body, 'message')
?? sprintf('Lemon Squeezy request failed with status %s', $response->status());
throw new LemonSqueezyException($message, $response->status(), $body);
}
return $response->json() ?? [];
}
protected function preparedRequest(): PendingRequest
{
$apiKey = config('lemonsqueezy.api_key');
if (! $apiKey) {
throw new LemonSqueezyException('Lemon Squeezy API key is not configured.');
}
$baseUrl = $this->normalizeBaseUrl((string) config('lemonsqueezy.base_url'));
return $this->http
->baseUrl($baseUrl)
->withHeaders([
'Accept' => 'application/vnd.api+json',
'Content-Type' => 'application/vnd.api+json',
'User-Agent' => sprintf('FotospielApp/%s LemonSqueezyClient', app()->version()),
])
->withToken($apiKey)
->acceptJson()
->asJson();
}
protected function normalizeBaseUrl(string $baseUrl): string
{
$baseUrl = trim($baseUrl);
if ($baseUrl === '') {
$baseUrl = 'https://api.lemonsqueezy.com/v1';
}
if (! Str::startsWith($baseUrl, ['http://', 'https://'])) {
$baseUrl = 'https://api.lemonsqueezy.com/'.ltrim($baseUrl, '/');
}
$parsedHost = parse_url($baseUrl, PHP_URL_HOST);
if (! is_string($parsedHost) || $parsedHost === '' || ! Str::endsWith($parsedHost, 'lemonsqueezy.com')) {
$baseUrl = 'https://api.lemonsqueezy.com/v1';
}
$baseUrl = rtrim($baseUrl, '/');
if (! Str::endsWith($baseUrl, '/v1')) {
$baseUrl .= '/v1';
}
return $baseUrl;
}
}