httpStatus = $httpStatus; $this->responseBody = $responseBody; } public function getHttpStatus(): int { return $this->httpStatus; } public function getResponseBody(): array { return $this->responseBody; } } class PayenyResourceProxy { private PayenyClient $client; private string $resource; public function __construct(PayenyClient $client, string $resource) { $this->client = $client; $this->resource = $resource; } public function __call(string $name, array $arguments) { return $this->client->dispatchResourceCall($this->resource, $name, $arguments); } } class PayenyClient { private string $secretKey; private string $baseUrl; private int $timeout; public PayenyResourceProxy $customers; public PayenyResourceProxy $payments; public PayenyResourceProxy $refunds; public PayenyResourceProxy $subscriptions; public PayenyResourceProxy $checkoutSessions; public PayenyResourceProxy $checkout_sessions; public PayenyResourceProxy $invoices; public PayenyResourceProxy $webhookEndpoints; public PayenyResourceProxy $webhook_endpoints; public PayenyResourceProxy $webhooks; public PayenyResourceProxy $events; public PayenyResourceProxy $billingPortal; public PayenyResourceProxy $billing_portal; public PayenyResourceProxy $portal; public PayenyResourceProxy $coupons; public function __construct(string $secretKey, string $baseUrl = 'https://payeny.com/api/v1', int $timeout = 30) { $this->secretKey = trim($secretKey); $this->baseUrl = rtrim($baseUrl, '/'); $this->timeout = $timeout; $this->customers = new PayenyResourceProxy($this, 'customers'); $this->payments = new PayenyResourceProxy($this, 'payments'); $this->refunds = new PayenyResourceProxy($this, 'refunds'); $this->subscriptions = new PayenyResourceProxy($this, 'subscriptions'); $this->checkoutSessions = new PayenyResourceProxy($this, 'checkout_sessions'); $this->checkout_sessions = $this->checkoutSessions; $this->invoices = new PayenyResourceProxy($this, 'invoices'); $this->webhookEndpoints = new PayenyResourceProxy($this, 'webhook_endpoints'); $this->webhook_endpoints = $this->webhookEndpoints; $this->webhooks = new PayenyResourceProxy($this, 'webhooks'); $this->events = new PayenyResourceProxy($this, 'events'); $this->billingPortal = new PayenyResourceProxy($this, 'billing_portal'); $this->billing_portal = $this->billingPortal; $this->portal = $this->billingPortal; $this->coupons = new PayenyResourceProxy($this, 'coupons'); } // ========================================================================= // Customers // ========================================================================= public function createCustomer(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/customers', $params, $idempotencyKey); } public function getCustomer(string $id): array { return $this->request('GET', '/customers/' . rawurlencode($id)); } public function listCustomers(array $query = []): array { return $this->request('GET', '/customers', $query); } public function updateCustomer(string $id, array $params): array { return $this->request('PATCH', '/customers/' . rawurlencode($id), $params); } // ========================================================================= // Payments // ========================================================================= public function createPayment(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/payments', $params, $idempotencyKey); } public function getPayment(string $id): array { return $this->request('GET', '/payments/' . rawurlencode($id)); } public function listPayments(array $query = []): array { return $this->request('GET', '/payments', $query); } // ========================================================================= // Refunds // ========================================================================= public function createRefund(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/refunds', $params, $idempotencyKey); } public function getRefund(string $id): array { return $this->request('GET', '/refunds/' . rawurlencode($id)); } public function listRefunds(array $query = []): array { return $this->request('GET', '/refunds', $query); } // ========================================================================= // Subscriptions (including cancel, resume, changePlan, updatePaymentMethod) // ========================================================================= public function createSubscription(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/subscriptions', $params, $idempotencyKey); } public function getSubscription(string $id): array { return $this->request('GET', '/subscriptions/' . rawurlencode($id)); } public function listSubscriptions(array $query = []): array { return $this->request('GET', '/subscriptions', $query); } public function updateSubscription(string $id, array $params): array { return $this->request('PATCH', '/subscriptions/' . rawurlencode($id), $params); } /** * Cancel a subscription. * Accepts $paramsOrAtPeriodEnd as bool (cancel_at_period_end) or array (['cancel_at_period_end' => false, 'at_period_end' => false, 'immediate' => true]). */ public function cancelSubscription(string $id, $paramsOrAtPeriodEnd = true): array { if (is_bool($paramsOrAtPeriodEnd)) { $payload = ['cancel_at_period_end' => $paramsOrAtPeriodEnd]; } elseif (is_array($paramsOrAtPeriodEnd)) { $payload = $paramsOrAtPeriodEnd; } else { $payload = ['cancel_at_period_end' => (bool)$paramsOrAtPeriodEnd]; } return $this->request('POST', '/subscriptions/' . rawurlencode($id) . '/cancel', $payload); } public function resumeSubscription(string $id): array { return $this->request('POST', '/subscriptions/' . rawurlencode($id) . '/resume', []); } public function changeSubscriptionPlan(string $id, array $params): array { return $this->request('POST', '/subscriptions/' . rawurlencode($id) . '/change_plan', $params); } public function updateSubscriptionPaymentMethod(string $id, array $params): array { return $this->request('POST', '/subscriptions/' . rawurlencode($id) . '/payment_method', $params); } public function advanceSubscriptionClock(string $id, array $params = []): array { return $this->request('POST', '/subscriptions/' . rawurlencode($id) . '/advance_clock', $params); } // ========================================================================= // Billing Portal Sessions // ========================================================================= public function createBillingPortalSession(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/billing_portal_sessions', $params, $idempotencyKey); } public function createPortalSession(array $params, ?string $idempotencyKey = null): array { return $this->createBillingPortalSession($params, $idempotencyKey); } // ========================================================================= // Coupons // ========================================================================= public function createCoupon(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/coupons', $params, $idempotencyKey); } public function getCoupon(string $id): array { return $this->request('GET', '/coupons/' . rawurlencode($id)); } public function listCoupons(array $query = []): array { return $this->request('GET', '/coupons', $query); } public function deleteCoupon(string $id): array { return $this->request('DELETE', '/coupons/' . rawurlencode($id)); } // ========================================================================= // Events & Test-Mode Webhook Replay // ========================================================================= public function listEvents(array $query = []): array { return $this->request('GET', '/events', $query); } public function getEvent(string $id): array { return $this->request('GET', '/events/' . rawurlencode($id)); } public function replayEvent(string $id, array $params = []): array { return $this->request('POST', '/events/' . rawurlencode($id) . '/replay', $params); } // ========================================================================= // Checkout Sessions // ========================================================================= public function createCheckoutSession(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/checkout_sessions', $params, $idempotencyKey); } public function getCheckoutSession(string $id): array { return $this->request('GET', '/checkout_sessions/' . rawurlencode($id)); } public function listCheckoutSessions(array $query = []): array { return $this->request('GET', '/checkout_sessions', $query); } // ========================================================================= // Invoices // ========================================================================= public function listInvoices(array $query = []): array { return $this->request('GET', '/invoices', $query); } public function getInvoice(string $id): array { return $this->request('GET', '/invoices/' . rawurlencode($id)); } public function getInvoicePdfUrl(string $id): string { return $this->baseUrl . '/invoices/' . rawurlencode($id) . '/pdf'; } // ========================================================================= // Webhook Endpoints // ========================================================================= public function createWebhookEndpoint(array $params, ?string $idempotencyKey = null): array { return $this->request('POST', '/webhook_endpoints', $params, $idempotencyKey); } public function getWebhookEndpoint(string $id): array { return $this->request('GET', '/webhook_endpoints/' . rawurlencode($id)); } public function listWebhookEndpoints(array $query = []): array { return $this->request('GET', '/webhook_endpoints', $query); } public function deleteWebhookEndpoint(string $id): array { return $this->request('DELETE', '/webhook_endpoints/' . rawurlencode($id)); } // ========================================================================= // Webhook Signature Verification (HMAC-SHA256) // ========================================================================= /** * Verify Payeny-Signature header (`t=,v1=`). */ public static function verifyWebhookSignature(string $payload, string $signatureHeader, string $secret, int $toleranceSeconds = 300): bool { if ($signatureHeader === '' || $secret === '') { return false; } $parts = []; foreach (explode(',', $signatureHeader) as $segment) { $kv = explode('=', trim($segment), 2); if (count($kv) === 2) { $parts[trim($kv[0])] = trim($kv[1]); } } if (empty($parts['t']) || empty($parts['v1'])) { return false; } $timestamp = (int)$parts['t']; if ($toleranceSeconds > 0 && abs(time() - $timestamp) > $toleranceSeconds) { return false; } $expected = hash_hmac('sha256', $timestamp . '.' . $payload, $secret); return hash_equals($expected, $parts['v1']); } public static function verifySignature(string $payload, string $signatureHeader, string $secret, int $toleranceSeconds = 300): bool { return self::verifyWebhookSignature($payload, $signatureHeader, $secret, $toleranceSeconds); } public static function constructWebhookEvent(string $payload, string $signatureHeader, string $secret, int $toleranceSeconds = 300): array { if (!self::verifyWebhookSignature($payload, $signatureHeader, $secret, $toleranceSeconds)) { throw new PayenyException('Invalid Payeny webhook signature.', 400); } $decoded = json_decode($payload, true); if (!is_array($decoded)) { throw new PayenyException('Invalid JSON in webhook payload.', 400); } return $decoded; } // ========================================================================= // Resource Proxy Dispatcher (`$payeny->customers->create(...)`, etc.) // ========================================================================= public function dispatchResourceCall(string $resource, string $method, array $args) { switch ($resource) { case 'customers': return match ($method) { 'create' => $this->createCustomer($args[0] ?? [], $args[1] ?? null), 'retrieve', 'get' => $this->getCustomer((string)($args[0] ?? '')), 'list', 'all' => $this->listCustomers($args[0] ?? []), 'update' => $this->updateCustomer((string)($args[0] ?? ''), $args[1] ?? []), default => throw new \BadMethodCallException("Unknown customers method: {$method}"), }; case 'payments': return match ($method) { 'create' => $this->createPayment($args[0] ?? [], $args[1] ?? null), 'retrieve', 'get' => $this->getPayment((string)($args[0] ?? '')), 'list', 'all' => $this->listPayments($args[0] ?? []), default => throw new \BadMethodCallException("Unknown payments method: {$method}"), }; case 'refunds': return match ($method) { 'create' => $this->createRefund($args[0] ?? [], $args[1] ?? null), 'retrieve', 'get' => $this->getRefund((string)($args[0] ?? '')), 'list', 'all' => $this->listRefunds($args[0] ?? []), default => throw new \BadMethodCallException("Unknown refunds method: {$method}"), }; case 'subscriptions': return match ($method) { 'create' => $this->createSubscription($args[0] ?? [], $args[1] ?? null), 'retrieve', 'get' => $this->getSubscription((string)($args[0] ?? '')), 'list', 'all' => $this->listSubscriptions($args[0] ?? []), 'update' => $this->updateSubscription((string)($args[0] ?? ''), $args[1] ?? []), 'cancel' => $this->cancelSubscription((string)($args[0] ?? ''), $args[1] ?? true), 'resume' => $this->resumeSubscription((string)($args[0] ?? '')), 'changePlan', 'change_plan' => $this->changeSubscriptionPlan((string)($args[0] ?? ''), $args[1] ?? []), 'updatePaymentMethod', 'update_payment_method' => $this->updateSubscriptionPaymentMethod((string)($args[0] ?? ''), $args[1] ?? []), 'advanceClock', 'advance_clock' => $this->advanceSubscriptionClock((string)($args[0] ?? ''), $args[1] ?? []), default => throw new \BadMethodCallException("Unknown subscriptions method: {$method}"), }; case 'billing_portal': return match ($method) { 'create', 'createSession', 'create_session' => $this->createBillingPortalSession($args[0] ?? [], $args[1] ?? null), default => throw new \BadMethodCallException("Unknown billing_portal method: {$method}"), }; case 'coupons': return match ($method) { 'create' => $this->createCoupon($args[0] ?? [], $args[1] ?? null), 'retrieve', 'get' => $this->getCoupon((string)($args[0] ?? '')), 'list', 'all' => $this->listCoupons($args[0] ?? []), 'delete', 'remove' => $this->deleteCoupon((string)($args[0] ?? '')), default => throw new \BadMethodCallException("Unknown coupons method: {$method}"), }; case 'events': return match ($method) { 'list', 'all' => $this->listEvents($args[0] ?? []), 'retrieve', 'get' => $this->getEvent((string)($args[0] ?? '')), 'replay' => $this->replayEvent((string)($args[0] ?? ''), $args[1] ?? []), default => throw new \BadMethodCallException("Unknown events method: {$method}"), }; case 'checkout_sessions': return match ($method) { 'create' => $this->createCheckoutSession($args[0] ?? [], $args[1] ?? null), 'retrieve', 'get' => $this->getCheckoutSession((string)($args[0] ?? '')), 'list', 'all' => $this->listCheckoutSessions($args[0] ?? []), default => throw new \BadMethodCallException("Unknown checkout_sessions method: {$method}"), }; case 'invoices': return match ($method) { 'list', 'all' => $this->listInvoices($args[0] ?? []), 'retrieve', 'get' => $this->getInvoice((string)($args[0] ?? '')), 'pdfUrl', 'pdf_url' => $this->getInvoicePdfUrl((string)($args[0] ?? '')), default => throw new \BadMethodCallException("Unknown invoices method: {$method}"), }; case 'webhook_endpoints': return match ($method) { 'create' => $this->createWebhookEndpoint($args[0] ?? [], $args[1] ?? null), 'retrieve', 'get' => $this->getWebhookEndpoint((string)($args[0] ?? '')), 'list', 'all' => $this->listWebhookEndpoints($args[0] ?? []), 'delete', 'remove' => $this->deleteWebhookEndpoint((string)($args[0] ?? '')), default => throw new \BadMethodCallException("Unknown webhook_endpoints method: {$method}"), }; case 'webhooks': return match ($method) { 'verifySignature', 'verify' => self::verifyWebhookSignature( (string)($args[0] ?? ''), (string)($args[1] ?? ''), (string)($args[2] ?? ''), (int)($args[3] ?? 300) ), 'constructEvent' => self::constructWebhookEvent( (string)($args[0] ?? ''), (string)($args[1] ?? ''), (string)($args[2] ?? ''), (int)($args[3] ?? 300) ), default => throw new \BadMethodCallException("Unknown webhooks method: {$method}"), }; default: throw new \BadMethodCallException("Unknown resource: {$resource}"); } } // ========================================================================= // Core HTTP Transport // ========================================================================= public function request(string $method, string $path, array $data = [], ?string $idempotencyKey = null): array { $method = strtoupper($method); $url = $this->baseUrl . '/' . ltrim($path, '/'); if ($method === 'GET' && !empty($data)) { $qs = http_build_query($data); $url .= (strpos($url, '?') === false ? '?' : '&') . $qs; } $headers = [ 'Authorization: Bearer ' . $this->secretKey, 'Accept: application/json', 'User-Agent: Payeny-PHP-SDK/1.0', ]; if ($idempotencyKey !== null && $idempotencyKey !== '') { $headers[] = 'Idempotency-Key: ' . $idempotencyKey; } elseif ($method === 'POST') { $headers[] = 'Idempotency-Key: idem_' . bin2hex(random_bytes(12)); } $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); if ($method !== 'GET' && $method !== 'DELETE') { $headers[] = 'Content-Type: application/json'; $payload = empty($data) ? '{}' : json_encode($data, JSON_UNESCAPED_SLASHES); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $raw = curl_exec($ch); $err = curl_error($ch); $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($raw === false) { throw new PayenyException('cURL transport error: ' . $err, 0); } $decoded = json_decode((string)$raw, true); if (!is_array($decoded)) { throw new PayenyException('Invalid JSON response from Payeny API (HTTP ' . $status . ')', $status); } if ($status >= 400 || (isset($decoded['success']) && $decoded['success'] === false)) { $msg = $decoded['error']['message'] ?? ($decoded['message'] ?? ('Payeny API error (HTTP ' . $status . ')')); throw new PayenyException((string)$msg, $status, $decoded); } return $decoded; } } if (!class_exists('Payeny\\Sdk\\PayenyClient', false)) { class_alias(PayenyClient::class, 'Payeny\\Sdk\\PayenyClient'); } if (!class_exists('PayenyClient', false)) { class_alias(PayenyClient::class, 'PayenyClient'); }