JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | WebhookRoute.php
<?php namespace WPForms\Integrations\PayPalCommerce\Api; use Exception; use RuntimeException; use BadMethodCallException; use WPForms\Integrations\PayPalCommerce\Api\Webhooks\Exceptions\AmountMismatchException; use WPForms\Integrations\PayPalCommerce\Connection; use WPForms\Integrations\PayPalCommerce\Helpers; use WPForms\Integrations\PayPalCommerce\WebhooksHealthCheck; /** * Webhooks Rest Route handler. * * @since 1.10.0 */ class WebhookRoute { /** * Event type. * * @since 1.10.0 * * @var string */ private $event_type = 'unknown'; /** * Raw payload. * * @since 1.10.0 * * @var array */ private $payload = []; /** * Response message. * * @since 1.10.0 * * @var string */ private $response = ''; /** * Response code. * * @since 1.10.0 * * @var int */ private $response_code = 200; /** * Initialize. * * @since 1.10.0 */ public function init(): void { $this->hooks(); } /** * Register hooks. * * @since 1.10.0 */ private function hooks(): void { if ( $this->is_rest_verification() ) { add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] ); return; } // Do not serve the regular page when it seems PayPal Webhooks are still sending requests to disabled PHP endpoint. // phpcs:disable WordPress.Security.NonceVerification.Recommended if ( isset( $_GET[ Helpers::get_webhook_endpoint_data()['fallback'] ] ) && ( ! Helpers::is_webhook_enabled() || $this->is_rest_api_set() ) ) { add_action( 'wp', [ $this, 'dispatch_with_error_500' ] ); return; } // phpcs:enable WordPress.Security.NonceVerification.Recommended // Check if the PayPal connection is configured. if ( ! Connection::get() ) { return; } if ( ! Helpers::is_webhook_enabled() || ! $this->is_webhook_configured() ) { return; } if ( $this->is_rest_api_set() ) { add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] ); return; } add_action( 'wp', [ $this, 'dispatch_with_url_param' ] ); } /** * Register webhook REST route. * * @since 1.10.0 */ public function register_rest_routes(): void { $methods = [ 'POST' ]; if ( $this->is_rest_verification() ) { $methods[] = 'GET'; } register_rest_route( Helpers::get_webhook_endpoint_data()['namespace'], '/' . Helpers::get_webhook_endpoint_data()['route'], [ 'methods' => $methods, 'callback' => [ $this, 'dispatch_paypal_webhooks_payload' ], 'show_in_index' => false, 'permission_callback' => '__return_true', ] ); } /** * Dispatch PayPal webhooks payload for the URL param (PHP listener) method. * * @since 1.10.0 */ public function dispatch_with_url_param(): void { // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( ! isset( $_GET[ Helpers::get_webhook_endpoint_data()['fallback'] ] ) ) { return; } $this->dispatch_paypal_webhooks_payload(); } /** * Dispatch PayPal webhooks payload for the URL param with error 500. * Runs when the URL param is not configured or webhooks are not enabled at all. * * @since 1.10.0 */ public function dispatch_with_error_500(): void { $this->response = esc_html__( 'It seems to be request to PayPal PHP Listener method handler but the site is not configured to use it.', 'wpforms-lite' ); $this->response_code = 500; $this->respond(); } /** * Dispatch PayPal webhooks payload. * * @since 1.10.0 * * @throws RuntimeException Error in reading and handling the payload. */ public function dispatch_paypal_webhooks_payload(): void { if ( $this->is_rest_verification() ) { wp_send_json_success(); } try { // Get raw payload. $this->payload = file_get_contents( 'php://input' ); if ( empty( $this->payload ) ) { throw new RuntimeException( 'Empty webhook payload.' ); } // Verify the webhook signature before processing. if ( ! $this->verify_webhook_signature( $this->payload ) ) { throw new RuntimeException( 'Webhook signature verification failed.' ); } $event = json_decode( $this->payload, false ); $event_whitelist = self::get_webhooks_events_list(); if ( ! in_array( $event->event_type, $event_whitelist, true ) ) { throw new RuntimeException( 'PayPal event type is not whitelisted.' ); } // Update webhook site health status. WebhooksHealthCheck::save_status( WebhooksHealthCheck::ENDPOINT_OPTION, WebhooksHealthCheck::STATUS_OK ); $this->event_type = $event->event_type; $this->response = 'WPForms PayPal: ' . $this->event_type . ' event received.'; $processed = $this->process_event( $event ); $this->response_code = $processed ? 200 : 202; // 202 Accepted if unhandled. $this->respond(); } catch ( AmountMismatchException $exception ) { $this->response_code = $exception->getCode(); $this->response = $exception->getMessage(); $this->respond(); } catch ( Exception $e ) { $this->response = $e->getMessage(); $this->response_code = $e instanceof BadMethodCallException ? 501 : 500; $this->respond(); } } /** * Retrieve stored webhook ID. * * @since 1.10.0 * * @return string */ private function get_webhook_id(): string { $mode = Helpers::get_mode(); $webhook_id = wpforms_setting( 'paypal-commerce-webhooks-id-' . $mode ); return is_string( $webhook_id ) ? $webhook_id : ''; } /** * Determine if the REST API is selected in settings. * * @since 1.10.0 * * @return bool */ private function is_rest_api_set(): bool { return Helpers::get_webhook_communication() === 'rest'; } /** * Process PayPal event. * Map the event to a handler if it exists. If no handler is registered, return false. * * @since 1.10.0 * * @param object $event PayPal event object. * * @return bool True if processed by a handler, false otherwise. */ private function process_event( object $event ): bool { $webhooks = self::get_event_whitelist(); // Event can't be handled. if ( ! isset( $webhooks[ $event->event_type ] ) || ! class_exists( $webhooks[ $event->event_type ] ) ) { return false; } /* @var Webhooks\Base $handler Webhook handler instance. */ $handler = new $webhooks[ $event->event_type ](); $handler->setup( $event ); return $handler->handle(); } /** * Get event allowlist mapping to handlers (if available). * * @since 1.10.0 * * @return array */ private static function get_event_whitelist(): array { // Placeholder for potential future handlers. Keep keys in sync with the registration list. return [ 'PAYMENT.CAPTURE.COMPLETED' => Webhooks\PaymentCaptureCompleted::class, 'PAYMENT.CAPTURE.DENIED' => Webhooks\PaymentCaptureDenied::class, 'PAYMENT.CAPTURE.REFUNDED' => Webhooks\PaymentCaptureRefunded::class, 'CHECKOUT.ORDER.COMPLETED' => Webhooks\CheckoutOrderCompleted::class, 'BILLING.SUBSCRIPTION.ACTIVATED' => Webhooks\BillingSubscriptionActivated::class, 'BILLING.SUBSCRIPTION.CANCELLED' => Webhooks\BillingSubscriptionCancelled::class, 'BILLING.SUBSCRIPTION.SUSPENDED' => Webhooks\BillingSubscriptionSuspended::class, 'BILLING.SUBSCRIPTION.UPDATED' => Webhooks\BillingSubscriptionUpdated::class, 'BILLING.SUBSCRIPTION.EXPIRED' => Webhooks\BillingSubscriptionExpired::class, 'PAYMENT.SALE.COMPLETED' => Webhooks\PaymentSaleCompleted::class, 'PAYMENT.SALE.REFUNDED' => Webhooks\PaymentSaleRefunded::class, ]; } /** * Get a webhook events list (keys of whitelist). * * @since 1.10.0 * * @return array */ public static function get_webhooks_events_list(): array { return array_keys( self::get_event_whitelist() ); } /** * Check if REST verification is requested. * * @since 1.10.0 * * @return bool */ private function is_rest_verification(): bool { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return isset( $_GET['verify'] ) && $_GET['verify'] === '1'; } /** * Respond to the request and exit. * * @since 1.10.0 */ private function respond(): void { $this->log_webhook(); wp_die( esc_html( $this->response ), '', (int) $this->response_code ); } /** * Log webhook request when debugging is enabled. * * @since 1.10.0 */ private function log_webhook(): void { // log only if WP_DEBUG_LOG and WPFORMS_WEBHOOKS_DEBUG are set to true. if ( ! defined( 'WPFORMS_WEBHOOKS_DEBUG' ) || ! WPFORMS_WEBHOOKS_DEBUG || ! defined( 'WP_DEBUG_LOG' ) || ! WP_DEBUG_LOG ) { return; } // If it is set to explicitly display logs on output, return: this would make the response malformed. if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) { return; } $webhook_log = maybe_serialize( [ 'event_type' => $this->event_type, 'response_code' => $this->response_code, 'response' => $this->response, 'payload' => $this->payload, ] ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( $webhook_log ); } /** * Check if the webhook is configured (webhook ID stored). * * @since 1.10.0 * * @return bool */ private function is_webhook_configured(): bool { return $this->get_webhook_id() !== ''; } /** * Verify webhook signature. * * Routes to the appropriate verification method based on connection type: * - Legacy (first-party) connections verify directly with PayPal API via the addon's WebhooksManager. * - Third-party connections verify the HMAC signature added by the Product API. * * @since 1.10.0.5 * * @param string $payload Raw webhook payload body. * * @return bool True if signature is valid, false otherwise. */ private function verify_webhook_signature( string $payload ): bool { if ( Helpers::is_legacy() ) { // phpcs:ignore WPForms.PHP.BackSlash.UseShortSyntax if ( ! method_exists( \WPFormsPaypalCommerce\Api\WebhooksManager::class, 'verify_webhook_signature' ) ) { return false; } // phpcs:ignore WPForms.PHP.BackSlash.UseShortSyntax return ( new \WPFormsPaypalCommerce\Api\WebhooksManager() )->verify_webhook_signature( $payload, $this->get_webhook_id() ); } return $this->verify_product_api_webhook_signature( $payload ); } /** * Verify the HMAC-SHA256 signature added by the Product API when forwarding webhooks. * * Checks the X-WPForms-Signature and X-WPForms-Timestamp headers against * the raw payload body using the shared secret established during onboarding. * Rejects payloads older than 5 minutes to prevent replay attacks. * * @since 1.10.0.5 * * @param string $payload Raw webhook payload body. * * @return bool True if signature is valid, false otherwise. */ private function verify_product_api_webhook_signature( string $payload ): bool { $signature = isset( $_SERVER['HTTP_X_WPFORMS_SIGNATURE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_WPFORMS_SIGNATURE'] ) ) : ''; $timestamp = isset( $_SERVER['HTTP_X_WPFORMS_TIMESTAMP'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_WPFORMS_TIMESTAMP'] ) ) : ''; if ( empty( $signature ) || empty( $timestamp ) ) { return false; } /** * Filter the maximum age (in seconds) for webhook signature timestamps. * * @since 1.10.0.5 * * @param int $max_age Maximum allowed age in seconds. Default 300 (5 minutes). */ $max_age = (int) apply_filters( 'wpforms_integrations_pay_pal_commerce_api_webhook_route_signature_max_age', 5 * MINUTE_IN_SECONDS ); if ( abs( time() - (int) $timestamp ) > $max_age ) { return false; } $connection = Connection::get(); if ( ! $connection ) { return false; } $secret = $connection->get_secret(); $expected = hash_hmac( 'sha256', $timestamp . '.' . $payload, $secret ); return hash_equals( $expected, $signature ); } }