\WP_REST_Server::CREATABLE, 'callback' => array( __CLASS__, 'createPayment' ), 'permission_callback' => function ( \WP_REST_Request $request ) { return self::checkPublicAccess( $request, 'create' ); }, ) ); register_rest_route( self::NAMESPACE_V1, '/payments/(?P[A-Za-z0-9_-]{1,64})', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => array( __CLASS__, 'getPaymentStatus' ), 'permission_callback' => function ( \WP_REST_Request $request ) { return self::checkPublicAccess( $request, 'status' ); }, 'args' => array( 'id' => array( 'type' => 'string', 'required' => true, ), ), ) ); register_rest_route( self::NAMESPACE_V1, '/payments', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => array( __CLASS__, 'listPayments' ), 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, 'args' => array( 'limit' => array( 'type' => 'integer', 'default' => 20, 'minimum' => 1, 'maximum' => 100, ), 'offset' => array( 'type' => 'integer', 'default' => 0, 'minimum' => 0, ), ), ) ); } // ═══════════════════════════════════════════════════════════════════════ // Access control // ═══════════════════════════════════════════════════════════════════════ /** * Public endpoints: valid wp_rest nonce + per-IP rate limit. * * @param \WP_REST_Request $request Request. * @param string $action "create" | "status". * @return true|\WP_Error */ private static function checkPublicAccess( \WP_REST_Request $request, $action ) { /** * Require a valid `wp_rest` nonce (X-WP-Nonce) on public SablePay endpoints. * Disable only if full-page caching serves pages older than the nonce lifetime. * * @param bool $require Default true. */ if ( apply_filters( 'sablepay_rest_require_nonce', true ) ) { $nonce = $request->get_header( 'X-WP-Nonce' ); if ( ! $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new \WP_Error( 'sablepay_invalid_nonce', __( 'Your session has expired. Please reload the page and try again.', 'sablepay' ), array( 'status' => 403 ) ); } } $limited = self::rateLimit( $action ); if ( is_wp_error( $limited ) ) { return $limited; } /** * Final say on whether the current visitor may use a public SablePay endpoint. * * @param bool $allowed Default true. * @param \WP_REST_Request $request Request. * @param string $action "create" | "status". */ $allowed = apply_filters( 'sablepay_rest_permission', true, $request, $action ); if ( true !== $allowed ) { return is_wp_error( $allowed ) ? $allowed : new \WP_Error( 'sablepay_forbidden', __( 'Not allowed.', 'sablepay' ), array( 'status' => 403 ) ); } return true; } /** * Fixed-window per-IP rate limit stored in transients. * * @return true|\WP_Error */ private static function rateLimit( $action ) { $defaults = array( 'create' => array( 'limit' => 20, 'window' => 10 * MINUTE_IN_SECONDS, ), 'status' => array( 'limit' => 600, 'window' => 10 * MINUTE_IN_SECONDS, ), ); /** * Filter the per-IP rate limits. Set limit to 0 to disable. * * @param array $limits { create: {limit, window}, status: {limit, window} } */ $limits = apply_filters( 'sablepay_rate_limits', $defaults ); $conf = isset( $limits[ $action ] ) ? $limits[ $action ] : $defaults[ $action ]; $limit = (int) ( $conf['limit'] ?? 0 ); $window = max( 1, (int) ( $conf['window'] ?? 600 ) ); if ( $limit <= 0 ) { return true; } $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown'; $bucket = (int) floor( time() / $window ); $key = 'sablepay_rl_' . $action . '_' . md5( $ip . '|' . $bucket ); $count = (int) get_transient( $key ); if ( $count >= $limit ) { $error = new \WP_Error( 'sablepay_rate_limited', __( 'Too many requests. Please wait a moment and try again.', 'sablepay' ), array( 'status' => 429 ) ); return $error; } set_transient( $key, $count + 1, $window ); return true; } // ═══════════════════════════════════════════════════════════════════════ // Handlers // ═══════════════════════════════════════════════════════════════════════ /** * POST /payments/create */ public static function createPayment( \WP_REST_Request $request ) { $sdk = self::sdk(); if ( $sdk instanceof \WP_REST_Response ) { return $sdk; } $params = $request->get_json_params(); if ( ! is_array( $params ) ) { $params = $request->get_body_params(); } $paymentRequest = array( 'amount' => $params['amount'] ?? null, 'items' => $params['items'] ?? null, 'metadata' => $params['metadata'] ?? null, 'expiresIn' => $params['expiresIn'] ?? null, ); /** * Filter the payment request before it is sent to SablePay. * * IMPORTANT for stores: the amount comes from the browser. Use this filter to * recompute the amount from your own server-side cart / order, or return a * WP_Error to reject the request. * * @param array $paymentRequest { amount, items, metadata, expiresIn } * @param \WP_REST_Request $request REST request. */ $paymentRequest = apply_filters( 'sablepay_create_payment_request', $paymentRequest, $request ); if ( is_wp_error( $paymentRequest ) ) { return self::error( 400, $paymentRequest->get_error_message() ); } try { $response = $sdk->createPayment( array_filter( (array) $paymentRequest, static function ( $v ) { return null !== $v; } ) ); } catch ( \Throwable $e ) { return self::fromException( $e ); } /** * Fires after a payment was created through the REST proxy. * * @param array $response CreatePaymentResponse. * @param array $paymentRequest Request sent to SablePay. * @param \WP_REST_Request $request REST request. */ do_action( 'sablepay_payment_created', $response, $paymentRequest, $request ); return self::noCache( new \WP_REST_Response( $response, 200 ) ); } /** * GET /payments/{id} */ public static function getPaymentStatus( \WP_REST_Request $request ) { $sdk = self::sdk(); if ( $sdk instanceof \WP_REST_Response ) { return $sdk; } try { // The browser SDK retries on its own; keep the proxy single-shot. $status = $sdk->getPaymentStatus( (string) $request['id'], false ); } catch ( \Throwable $e ) { return self::fromException( $e ); } /** * Fires every time a payment status is fetched through the proxy. * The data comes from the SablePay API (trusted), so this is a good place * to mark an order as paid when PaymentStatus::isCompleted( $status['status'] ). * * @param array $status PaymentStatusResponse. * @param \WP_REST_Request $request REST request. */ do_action( 'sablepay_payment_status_checked', $status, $request ); if ( isset( $status['status'] ) && PaymentStatus::isCompleted( $status['status'] ) ) { /** * Fires when a payment fetched through the proxy is COMPLETED. * May fire more than once for the same payment — make handlers idempotent. * * @param array $status PaymentStatusResponse. */ do_action( 'sablepay_payment_completed', $status ); } return self::noCache( new \WP_REST_Response( $status, 200 ) ); } /** * GET /payments (admins only) */ public static function listPayments( \WP_REST_Request $request ) { $sdk = self::sdk(); if ( $sdk instanceof \WP_REST_Response ) { return $sdk; } try { $list = $sdk->listPayments( (int) $request['limit'], (int) $request['offset'] ); } catch ( \Throwable $e ) { return self::fromException( $e ); } return self::noCache( new \WP_REST_Response( $list, 200 ) ); } // ═══════════════════════════════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════════════════════════════ /** * @return SablePay|\WP_REST_Response */ private static function sdk() { if ( Settings::initializeSdk() ) { return SablePay::getInstance(); } return self::error( 503, __( 'SablePay is not configured on this site.', 'sablepay' ) ); } private static function canSeeDetails() { return ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || current_user_can( 'manage_options' ); } /** * Error body in the SablePay API format: { error, details, requestId }. */ private static function error( $status, $message, $details = null, $requestId = null, $retryAfter = null ) { $response = new \WP_REST_Response( array( 'error' => $message, 'details' => self::canSeeDetails() ? $details : null, 'requestId' => $requestId, ), $status ); if ( $retryAfter ) { $response->header( 'Retry-After', (string) $retryAfter ); } return self::noCache( $response ); } private static function fromException( \Throwable $e ) { if ( $e instanceof ApiException ) { $status = $e->getStatusCode() >= 400 ? $e->getStatusCode() : 502; return self::error( $status, $e->getMessage(), $e->getDetails(), $e->getRequestId(), $e->getRetryAfter() ); } if ( $e instanceof \InvalidArgumentException ) { return self::error( 400, $e->getMessage() ); } if ( $e instanceof NetworkException ) { return self::error( 502, __( 'Could not reach SablePay. Please try again.', 'sablepay' ), $e->getMessage() ); } return self::error( 500, __( 'Unexpected error.', 'sablepay' ), $e->getMessage() ); } private static function noCache( \WP_REST_Response $response ) { $response->header( 'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0' ); return $response; } }