'POST', 'callback' => array( self::class, 'handle' ), 'permission_callback' => '__return_true', // authenticated by PayPal signature ) ); } public static function handle( \WP_REST_Request $req ) { $webhookId = (string) Settings::get( 'paypal_webhook_id', '' ); if ( '' === $webhookId ) { return new \WP_Error( 'sg_webhook_unconfigured', 'Webhook is not configured.', array( 'status' => 503 ) ); } $raw = $req->get_body(); if ( ! Client::fromSettings()->verifyWebhook( $req->get_headers(), $raw, $webhookId ) ) { return new \WP_Error( 'sg_webhook_signature', 'Invalid signature.', array( 'status' => 401 ) ); } $data = json_decode( $raw, true ); if ( ! is_array( $data ) ) { return new \WP_Error( 'sg_webhook_body', 'Bad payload.', array( 'status' => 400 ) ); } $ev = WebhookEvent::fromArray( $data ); $cache = new WpCache(); $seen = 'sg_wh_' . md5( $ev->eventId ); if ( '' !== $ev->eventId && false !== $cache->get( $seen ) ) { return rest_ensure_response( array( 'result' => 'duplicate' ) ); } $result = self::process( $ev ); if ( '' !== $ev->eventId ) { $cache->set( $seen, 1, DAY_IN_SECONDS ); } return rest_ensure_response( array( 'result' => $result ) ); } /** Only PAYMENT.CAPTURE.COMPLETED is acted on; every other event is acknowledged (200) so PayPal stops retrying. */ private static function process( WebhookEvent $ev ): string { if ( 'PAYMENT.CAPTURE.COMPLETED' === $ev->type ) { return self::completed( $ev ); } return 'ignored'; } private static function locate( WebhookEvent $ev ): ?object { $row = null; if ( ctype_digit( $ev->customId ) && '' !== $ev->customId ) { $row = DonationStore::find( (int) $ev->customId ); } if ( ! $row && '' !== $ev->captureId ) { $row = DonationStore::find_by_capture( $ev->captureId ); } if ( ! $row && '' !== $ev->orderId ) { $row = DonationStore::find_by_order( $ev->orderId ); } return $row; } private static function completed( WebhookEvent $ev ): string { $row = self::locate( $ev ); if ( ! $row || '' === $ev->captureId ) { return 'ignored'; } $res = CaptureFinalizer::finalize( $row, 'COMPLETED', $ev->captureId, $ev->amount, array( DonationStore::class, 'mark_completed' ), array( DonationStore::class, 'notify_applied' ) ); if ( CaptureFinalizer::PENDING === $res ) { error_log( 'StreamGoals: webhook capture does not match donation ' . $row->id . '; left pending' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions return 'ignored'; } return $res; } }