v1.0.0.0
StocketBase
- <?php
-
- declare(strict_types=1);
-
- require_once __DIR__ . '/../config.php';
- require_once __DIR__ . '/../site-front.php';
-
- final class PolarClient
- {
- private const API_BASE = 'https://api.polar.sh/v1';
-
- private string $accessToken;
-
- public function __construct(?string $accessToken = null)
- {
- $this->accessToken = $accessToken ?? (string) (SiteFront::settings()['payment_polar_access_token'] ?? '');
- }
-
- public function createCheckoutSession(
- string $polarProductId,
- string $successUrl,
- ?string $customerEmail,
- array $metadata = []
- ): ?array {
- if ($this->accessToken === '') {
- error_log('PolarClient: cannot create checkout session, no access token configured.');
-
- return null;
- }
-
- if ($polarProductId === '') {
- error_log('PolarClient: cannot create checkout session, no Polar product ID given.');
-
- return null;
- }
-
- $payload = [
- 'products' => [$polarProductId],
- 'success_url' => $successUrl,
- ];
-
- if ($customerEmail !== null && $customerEmail !== '') {
- $payload['customer_email'] = $customerEmail;
- }
-
- if (!empty($metadata)) {
- $payload['metadata'] = $metadata;
- }
-
- [$status, $body] = $this->post('/checkouts/', $payload);
-
- if ($status < 200 || $status >= 300 || !isset($body['url'])) {
- error_log('PolarClient: checkout session creation failed with HTTP ' . $status . ' — ' . (string) json_encode($body));
-
- return null;
- }
-
- return $body;
- }
-
- private function post(string $path, array $payload): array
- {
- $url = self::API_BASE . $path;
- $body = (string) json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
-
- if (!function_exists('curl_init')) {
- error_log('PolarClient: cURL extension is not available.');
-
- return [0, []];
- }
-
- $curl = curl_init($url);
- curl_setopt_array($curl, [
- CURLOPT_POST => true,
- CURLOPT_POSTFIELDS => $body,
- CURLOPT_HTTPHEADER => [
- 'Authorization: Bearer ' . $this->accessToken,
- 'Content-Type: application/json',
- ],
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_CONNECTTIMEOUT => 10,
- CURLOPT_TIMEOUT => 20,
- ]);
- $response = curl_exec($curl);
- $status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
- $curlError = curl_error($curl);
- curl_close($curl);
-
- if ($response === false) {
- error_log('PolarClient: request failed — ' . $curlError);
-
- return [0, []];
- }
-
- $decoded = json_decode($response, true);
-
- return [$status, is_array($decoded) ? $decoded : []];
- }
- }
-