$v ) { $key = $prefix ? $prefix . '[' . $k . ']' : $k; if ( is_array( $v ) ) { $out = array_merge( $out, self::encode( $v, $key ) ); } elseif ( is_bool( $v ) ) { $out[ $key ] = $v ? 'true' : 'false'; } elseif ( null !== $v ) { $out[ $key ] = (string) $v; } } return $out; } /** * @return array|\WP_Error */ public static function request( $method, $path, array $params = array(), $idempotency_key = '' ) { $key = self::secret_key(); if ( ! $key ) { return new \WP_Error( 'tableengine_stripe_key', __( 'Stripe is not configured.', 'tableengine' ) ); } $headers = array( 'Authorization' => 'Bearer ' . $key, 'Stripe-Version' => self::VERSION, 'User-Agent' => 'TableEngine/' . TABLEENGINE_VERSION . ' WordPress/' . get_bloginfo( 'version' ), ); if ( $idempotency_key ) { $headers['Idempotency-Key'] = $idempotency_key; } $url = self::API . ltrim( $path, '/' ); $args = array( 'method' => $method, 'headers' => $headers, 'timeout' => 30, ); if ( 'GET' === $method ) { $url = $params ? add_query_arg( array_map( 'rawurlencode', self::encode( $params ) ), $url ) : $url; } else { $args['body'] = self::encode( $params ); } $response = wp_remote_request( $url, $args ); if ( is_wp_error( $response ) ) { self::log( 'HTTP error: ' . $response->get_error_message() ); return $response; } $code = wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); self::log( sprintf( '%s %s → %d', $method, $path, $code ) ); if ( $code >= 400 || ! is_array( $body ) ) { $msg = isset( $body['error']['message'] ) ? $body['error']['message'] : __( 'Unexpected response from Stripe.', 'tableengine' ); self::log( 'Error: ' . $msg ); return new \WP_Error( 'tableengine_stripe', $msg, array( 'status' => 502 ) ); } return $body; } public static function log( $msg ) { if ( Settings::get( 'debug_log' ) ) { error_log( '[TableEngine Stripe] ' . $msg ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions } } /** * Create (or reuse) a PaymentIntent for a reservation. * * @return array|\WP_Error */ public static function create_intent( array $reservation ) { $params = array( 'amount' => (int) $reservation['amount'], 'currency' => strtolower( $reservation['currency'] ), 'automatic_payment_methods' => array( 'enabled' => true ), 'description' => sprintf( '%s — %s (%d guests, %s)', Settings::get( 'deposit_label' ), $reservation['reference'], $reservation['party_size'], $reservation['start_at'] ), 'receipt_email' => $reservation['email'], 'metadata' => array( 'tableengine_reservation' => $reservation['id'], 'reference' => $reservation['reference'], 'site' => home_url(), ), ); $suffix = trim( (string) Settings::get( 'statement_descriptor' ) ); if ( $suffix ) { $params['statement_descriptor_suffix'] = mb_substr( preg_replace( '/[<>\\\\\'"*]/', '', $suffix ), 0, 22 ); } $params = apply_filters( 'tableengine_payment_intent_params', $params, $reservation ); return self::request( 'POST', 'payment_intents', $params, 'tableengine_pi_' . $reservation['reference'] ); } public static function retrieve_intent( $id ) { return self::request( 'GET', 'payment_intents/' . rawurlencode( $id ) ); } public static function cancel_intent( $id ) { return self::request( 'POST', 'payment_intents/' . rawurlencode( $id ) . '/cancel' ); } /** * @return array|\WP_Error */ public static function refund( array $reservation, $amount = 0 ) { if ( ! $reservation['stripe_intent'] ) { return new \WP_Error( 'tableengine_refund', __( 'No payment to refund.', 'tableengine' ) ); } $params = array( 'payment_intent' => $reservation['stripe_intent'], 'metadata' => array( 'tableengine_reservation' => $reservation['id'] ), ); if ( $amount > 0 ) { $params['amount'] = (int) $amount; } $refund = self::request( 'POST', 'refunds', $params, 'tableengine_refund_' . $reservation['reference'] . '_' . (int) $amount ); if ( ! is_wp_error( $refund ) ) { $full = ! $amount || (int) $amount >= (int) $reservation['amount']; Reservations::update( $reservation['id'], array( 'payment_status' => $full ? 'refunded' : 'partially_refunded' ) ); } return $refund; } /** * Apply a PaymentIntent's state to its reservation. Shared by the webhook * and the client-side verify fallback, so it must be idempotent. */ public static function sync_intent( array $intent ) { $row = Reservations::get_by_intent( $intent['id'] ); if ( ! $row && ! empty( $intent['metadata']['tableengine_reservation'] ) ) { $row = Reservations::get( (int) $intent['metadata']['tableengine_reservation'] ); if ( $row && $row['stripe_intent'] && $row['stripe_intent'] !== $intent['id'] ) { $row = null; } } if ( ! $row ) { return null; } switch ( $intent['status'] ) { case 'succeeded': if ( 'paid' !== $row['payment_status'] && 'refunded' !== $row['payment_status'] ) { $row = Reservations::update( $row['id'], array( 'payment_status' => 'paid' ) ); } if ( 'expired' === $row['status'] && ! Availability::reservation_table_free( $row ) ) { // Paid after the hold lapsed and someone else took the table: refund. self::refund( $row ); $note = trim( $row['internal_notes'] . "\n" . sprintf( '[%s] Payment arrived after hold expired and table was taken — refunded automatically.', current_time( 'mysql' ) ) ); $row = Reservations::update( $row['id'], array( 'internal_notes' => $note ) ); $row = Reservations::set_status( $row['id'], 'cancelled' ); break; } if ( 'pending_payment' === $row['status'] || 'expired' === $row['status'] ) { $target = Settings::get( 'auto_confirm' ) ? 'confirmed' : 'pending'; $row = Reservations::set_status( $row['id'], $target ); do_action( 'tableengine_payment_completed', $row, $intent ); } break; case 'requires_capture': // Card authorised but not captured (manual capture, e.g. a pre-authorised deposit): the booking stands. if ( in_array( $row['payment_status'], array( 'unpaid', 'processing', 'failed' ), true ) ) { $row = Reservations::update( $row['id'], array( 'payment_status' => 'authorized' ) ); } if ( 'pending_payment' === $row['status'] ) { $row = Reservations::set_status( $row['id'], Settings::get( 'auto_confirm' ) ? 'confirmed' : 'pending' ); do_action( 'tableengine_payment_authorized', $row, $intent ); } break; case 'processing': if ( 'unpaid' === $row['payment_status'] || 'failed' === $row['payment_status'] ) { // Keep the hold alive while the bank processes the payment. $row = Reservations::update( $row['id'], array( 'payment_status' => 'processing', 'hold_expires_gmt' => gmdate( 'Y-m-d H:i:s', time() + DAY_IN_SECONDS ), ) ); } break; case 'requires_payment_method': if ( ! empty( $intent['last_payment_error'] ) && 'paid' !== $row['payment_status'] ) { $row = Reservations::update( $row['id'], array( 'payment_status' => 'failed' ) ); } break; case 'canceled': if ( 'authorized' === $row['payment_status'] ) { $row = Reservations::update( $row['id'], array( 'payment_status' => 'released' ) ); } elseif ( 'paid' !== $row['payment_status'] && 'released' !== $row['payment_status'] ) { $row = Reservations::update( $row['id'], array( 'payment_status' => 'cancelled' ) ); if ( 'pending_payment' === $row['status'] ) { $row = Reservations::set_status( $row['id'], 'expired', false ); } } break; } return $row; } /** * Verify the Stripe-Signature header (v1 scheme). */ public static function verify_signature( $payload, $header, $secret, $tolerance = 300 ) { if ( ! $header || ! $secret ) { return false; } $timestamp = 0; $signatures = array(); foreach ( explode( ',', $header ) as $part ) { $kv = explode( '=', trim( $part ), 2 ); if ( 2 !== count( $kv ) ) { continue; } if ( 't' === $kv[0] ) { $timestamp = (int) $kv[1]; } elseif ( 'v1' === $kv[0] ) { $signatures[] = $kv[1]; } } if ( ! $timestamp || ! $signatures || abs( time() - $timestamp ) > $tolerance ) { return false; } $expected = hash_hmac( 'sha256', $timestamp . '.' . $payload, $secret ); foreach ( $signatures as $sig ) { if ( hash_equals( $expected, $sig ) ) { return true; } } return false; } /** * Webhook entry point. */ public static function handle_webhook( \WP_REST_Request $request ) { $payload = $request->get_body(); $header = $request->get_header( 'stripe_signature' ); if ( ! self::verify_signature( $payload, $header, self::webhook_secret() ) ) { self::log( 'Webhook signature verification failed.' ); return new \WP_REST_Response( array( 'error' => 'invalid_signature' ), 400 ); } $event = json_decode( $payload, true ); if ( ! is_array( $event ) || empty( $event['id'] ) || empty( $event['type'] ) ) { return new \WP_REST_Response( array( 'error' => 'invalid_payload' ), 400 ); } global $wpdb; $events = Install::table( 'events' ); // Idempotency: claim the event id atomically. $claimed = $wpdb->query( // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $wpdb->prepare( "INSERT IGNORE INTO {$events} (event_id, type, livemode, status, created_gmt) VALUES (%s, %s, %d, 'received', %s)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Only the internal table name is interpolated. $event['id'], $event['type'], empty( $event['livemode'] ) ? 0 : 1, current_time( 'mysql', true ) ) ); if ( ! $claimed ) { return new \WP_REST_Response( array( 'received' => true, 'duplicate' => true ), 200 ); } $object = isset( $event['data']['object'] ) ? $event['data']['object'] : array(); $row = null; $message = ''; try { switch ( $event['type'] ) { case 'payment_intent.succeeded': case 'payment_intent.processing': case 'payment_intent.payment_failed': case 'payment_intent.canceled': case 'payment_intent.amount_capturable_updated': $row = self::sync_intent( $object ); $message = isset( $object['last_payment_error']['message'] ) ? $object['last_payment_error']['message'] : ''; break; case 'charge.refunded': if ( ! empty( $object['payment_intent'] ) ) { $row = Reservations::get_by_intent( $object['payment_intent'] ); if ( $row ) { $full = (int) $object['amount_refunded'] >= (int) $object['amount']; $row = Reservations::update( $row['id'], array( 'payment_status' => $full ? 'refunded' : 'partially_refunded' ) ); $message = sprintf( 'Refunded %d of %d', $object['amount_refunded'], $object['amount'] ); } } break; case 'charge.dispute.created': if ( ! empty( $object['payment_intent'] ) ) { $row = Reservations::get_by_intent( $object['payment_intent'] ); $message = 'Dispute: ' . ( isset( $object['reason'] ) ? $object['reason'] : '' ); if ( $row ) { $note = trim( $row['internal_notes'] . "\n" . sprintf( '[%s] Stripe dispute opened (%s).', current_time( 'mysql' ), $object['reason'] ?? '' ) ); Reservations::update( $row['id'], array( 'internal_notes' => $note ) ); } } break; default: $message = 'Ignored'; } do_action( 'tableengine_stripe_event', $event, $row ); $wpdb->update( // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $events, array( 'status' => $row ? 'processed' : 'unmatched', 'reservation_id' => $row ? (int) $row['id'] : 0, 'message' => mb_substr( $message, 0, 500 ), ), array( 'event_id' => $event['id'] ) ); } catch ( \Throwable $e ) { // Release the claim so Stripe's retry can be processed. $wpdb->delete( $events, array( 'event_id' => $event['id'] ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. self::log( 'Webhook processing error: ' . $e->getMessage() ); return new \WP_REST_Response( array( 'error' => 'processing_failed' ), 500 ); } return new \WP_REST_Response( array( 'received' => true ), 200 ); } public static function recent_events( $limit = 25, $reservation_id = 0 ) { global $wpdb; $table = Install::table( 'events' ); if ( $reservation_id ) { return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE reservation_id = %d ORDER BY id DESC LIMIT %d", $reservation_id, $limit ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} ORDER BY id DESC LIMIT %d", $limit ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } }