'sable_sk_sand_...', * 'merchantId' => '00000000-0000-0000-0000-000000000000', * ) ); * * $payment = SablePay::getInstance()->createPayment( array( * 'amount' => 10.50, * 'metadata' => array( 'order_id' => '12345' ), * ) ); * * $status = SablePay::getInstance()->getPaymentStatus( $payment['paymentId'] ); * * Inside WordPress the plugin initializes the SDK lazily from the settings * page / wp-config.php constants — call sablepay() to get the instance. * * The UI pieces (launchPayment, PaymentFlow, QR code, payment window) live in * the browser SDK: window.SablePay (assets/js/sablepay.js). */ class SablePay { /** @var SablePay|null */ private static $instance = null; /** @var ApiClient */ private $apiClient; /** @var ApiKeyManager */ private $apiKeyManager; /** @var string */ private $baseUrl; private function __construct( ApiClient $apiClient, ApiKeyManager $apiKeyManager, $baseUrl ) { $this->apiClient = $apiClient; $this->apiKeyManager = $apiKeyManager; $this->baseUrl = $baseUrl; } // ═══════════════════════════════════════════════════════════════════════ // Instance Methods // ═══════════════════════════════════════════════════════════════════════ /** * Create a new payment transaction. * * @param array $request { * @type float $amount Required. 0.01 – 1,000,000. * @type array $items Optional. List of { name, quantity, price, sku }. * @type array $metadata Optional. Map of string => string. * @type int $expiresIn Optional. Seconds; default PaymentConfig::DEFAULT_EXPIRES_IN_SECONDS. * } * @param bool $enableRetry Retry network / retryable API errors with backoff (default true). * @return array CreatePaymentResponse. * * @throws ApiException For API errors. * @throws \InvalidArgumentException For invalid input. * @throws \RuntimeException If not configured. */ public function createPayment( array $request, $enableRetry = true ) { $apiKey = $this->apiKeyManager->getApiKey(); if ( ! $apiKey ) { throw new \RuntimeException( 'API key not configured. Call SablePay::initialize() first' ); } $merchantId = $this->apiKeyManager->getMerchantId(); if ( ! $merchantId ) { throw new \RuntimeException( 'Merchant ID not configured. Call SablePay::initialize() first' ); } $finalRequest = self::sanitizeRequest( $request ); Logger::debug( sprintf( 'Creating payment: amount=%s, expiresIn=%ss', $finalRequest['amount'], $finalRequest['expiresIn'] ) ); $client = $this->apiClient; $doRequest = static function () use ( $client, $apiKey, $merchantId, $finalRequest ) { return $client->createPayment( $apiKey, $merchantId, $finalRequest ); }; $response = $enableRetry ? Retry::withExponentialBackoff( $doRequest, array( 'shouldRetry' => array( __CLASS__, 'shouldRetry' ) ) ) : $doRequest(); Logger::debug( 'Payment created successfully: paymentId=' . ( isset( $response['paymentId'] ) ? $response['paymentId'] : '?' ) ); return $response; } /** * Get the status of an existing payment. * * @param string $paymentId Payment identifier. * @param bool $enableRetry Retry with backoff (default true). * @return array PaymentStatusResponse. */ public function getPaymentStatus( $paymentId, $enableRetry = true ) { $apiKey = $this->apiKeyManager->getApiKey(); if ( ! $apiKey ) { throw new \RuntimeException( 'API key not configured' ); } $merchantId = $this->apiKeyManager->getMerchantId(); if ( ! $merchantId ) { throw new \RuntimeException( 'Merchant ID not configured' ); } Logger::debug( "Checking payment status: paymentId={$paymentId}" ); $client = $this->apiClient; $doRequest = static function () use ( $client, $paymentId, $apiKey, $merchantId ) { return $client->getPaymentStatus( $paymentId, $apiKey, $merchantId ); }; $response = $enableRetry ? Retry::withExponentialBackoff( $doRequest, array( 'shouldRetry' => array( __CLASS__, 'shouldRetry' ) ) ) : $doRequest(); Logger::debug( 'Payment status retrieved: status=' . ( isset( $response['status'] ) ? $response['status'] : '?' ) ); return $response; } /** * List payments for the merchant. * * @param int $limit Max results (default 20). * @param int $offset Pagination offset (default 0). * @return array[] PaymentStatusResponse list. */ public function listPayments( $limit = 20, $offset = 0 ) { $apiKey = $this->apiKeyManager->getApiKey(); if ( ! $apiKey ) { throw new \RuntimeException( 'API key not configured' ); } $merchantId = $this->apiKeyManager->getMerchantId(); if ( ! $merchantId ) { throw new \RuntimeException( 'Merchant ID not configured' ); } return $this->apiClient->listPayments( $apiKey, $merchantId, $limit, $offset ); } /** Check if the SDK is configured with credentials. */ public function isConfigured() { return $this->apiKeyManager->isConfigured(); } /** * Current environment based on the API key. * * @return string|null "sandbox", "production", "unknown", or null if not configured. */ public function getEnvironment() { $apiKey = $this->apiKeyManager->getApiKey(); if ( ! $apiKey ) { return null; } return self::environmentForKey( $apiKey ); } /** Configured API base URL. */ public function getBaseUrl() { return $this->baseUrl; } /** * Create a server-side poller bound to this instance. * * @return PaymentPoller */ public function createPoller() { $sdk = $this; return new PaymentPoller( static function ( $paymentId ) use ( $sdk ) { return $sdk->getPaymentStatus( $paymentId ); } ); } // ═══════════════════════════════════════════════════════════════════════ // Static Methods (Singleton Pattern) // ═══════════════════════════════════════════════════════════════════════ /** * Initialize the SablePay SDK. * * @param array $config { * @type string $apiKey Required. sable_sk_sand_... or sable_sk_live_... * @type string $merchantId Required. Merchant UUID. * @type string $baseUrl Optional. Defaults from the API key environment. * @type bool $enableLogging Optional. Debug logging to the PHP error log. * } * @throws \LogicException If already initialized. * @throws \InvalidArgumentException If credentials are invalid. */ public static function initialize( array $config ) { if ( null !== self::$instance ) { throw new \LogicException( 'SablePay already initialized. Call SablePay::release() first to re-initialize.' ); } $apiKey = isset( $config['apiKey'] ) ? trim( (string) $config['apiKey'] ) : ''; $merchantId = isset( $config['merchantId'] ) ? trim( (string) $config['merchantId'] ) : ''; $baseUrl = isset( $config['baseUrl'] ) ? trim( (string) $config['baseUrl'] ) : ''; if ( '' === $baseUrl ) { $baseUrl = strpos( $apiKey, '_sand_' ) !== false ? NetworkConfig::BASE_URL_SANDBOX : NetworkConfig::BASE_URL_PRODUCTION; } if ( ! empty( $config['enableLogging'] ) ) { Logger::setLogLevel( 'debug' ); } $apiKeyManager = new ApiKeyManager(); $apiKeyManager->saveApiKey( $apiKey ); $apiKeyManager->saveMerchantId( $merchantId ); self::$instance = new self( new ApiClient( $baseUrl ), $apiKeyManager, $baseUrl ); Logger::debug( 'SablePay SDK initialized' ); } /** * Get the initialized SDK instance. * * @return SablePay * @throws \LogicException If initialize() has not been called. */ public static function getInstance() { if ( null === self::$instance ) { throw new \LogicException( 'SablePay not initialized. Call SablePay::initialize() first.' ); } return self::$instance; } /** Check if the SDK has been initialized. */ public static function isInitialized() { return null !== self::$instance; } /** * Pre-warm the HTTP connection to the API host (DNS/TLS). * Failures are non-fatal by design. * * @param bool $establishConnection Send a HEAD request (default true). */ public static function warmUp( $establishConnection = true ) { $sdk = self::getInstance(); if ( ! $establishConnection ) { return; } wp_remote_head( $sdk->baseUrl, array( 'timeout' => NetworkConfig::CONNECT_TIMEOUT_MS / 1000, 'redirection' => 0, ) ); } /** * Release SDK resources and clear stored credentials. */ public static function release() { if ( null !== self::$instance ) { self::$instance->apiKeyManager->clearCredentials(); self::$instance = null; Logger::debug( 'SablePay SDK released' ); } } /** * Create an instance for testing with custom dependencies. * * @internal */ public static function createForTesting( ApiClient $apiClient, ApiKeyManager $apiKeyManager, $baseUrl = NetworkConfig::BASE_URL_SANDBOX ) { return new self( $apiClient, $apiKeyManager, $baseUrl ); } // ═══════════════════════════════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════════════════════════════ /** * Environment label for an API key. * * @param string $apiKey API key. * @return string "sandbox" | "production" | "unknown" */ public static function environmentForKey( $apiKey ) { if ( strpos( (string) $apiKey, '_sand_' ) !== false ) { return 'sandbox'; } if ( strpos( (string) $apiKey, '_live_' ) !== false ) { return 'production'; } return 'unknown'; } /** @internal Retry policy: network errors and retryable API errors. */ public static function shouldRetry( $error ) { if ( Retry::isNetworkError( $error ) ) { return true; } return $error instanceof ApiException && $error->isRetryable(); } /** * Validate and normalize a CreatePaymentRequest. * * @param array $request Raw request. * @return array * @throws \InvalidArgumentException On invalid input. */ public static function sanitizeRequest( array $request ) { if ( ! isset( $request['amount'] ) || ! is_numeric( $request['amount'] ) ) { throw new \InvalidArgumentException( 'Amount is required and must be a number' ); } $amount = (float) $request['amount']; if ( $amount < 0.01 ) { throw new \InvalidArgumentException( 'Amount must be at least 0.01' ); } if ( $amount > 1000000 ) { throw new \InvalidArgumentException( 'Amount must not exceed 1,000,000' ); } $out = array( 'amount' => round( $amount, 2 ) ); if ( ! empty( $request['items'] ) && is_array( $request['items'] ) ) { $items = array(); foreach ( $request['items'] as $item ) { if ( ! is_array( $item ) ) { continue; } $clean = array(); if ( isset( $item['name'] ) ) { $clean['name'] = substr( (string) $item['name'], 0, 255 ); } if ( isset( $item['quantity'] ) && is_numeric( $item['quantity'] ) ) { $clean['quantity'] = (int) $item['quantity']; } if ( isset( $item['price'] ) && is_numeric( $item['price'] ) ) { $clean['price'] = (float) $item['price']; } if ( isset( $item['sku'] ) ) { $clean['sku'] = substr( (string) $item['sku'], 0, 128 ); } if ( $clean ) { $items[] = $clean; } } if ( $items ) { $out['items'] = $items; } } if ( ! empty( $request['metadata'] ) && is_array( $request['metadata'] ) ) { $metadata = array(); foreach ( $request['metadata'] as $key => $value ) { if ( is_scalar( $value ) || null === $value ) { $metadata[ substr( (string) $key, 0, 64 ) ] = substr( (string) $value, 0, 500 ); } } if ( $metadata ) { $out['metadata'] = $metadata; } } $out['expiresIn'] = isset( $request['expiresIn'] ) && is_numeric( $request['expiresIn'] ) && (int) $request['expiresIn'] > 0 ? (int) $request['expiresIn'] : PaymentConfig::DEFAULT_EXPIRES_IN_SECONDS; return $out; } }