Skip to content

PayPal WPS migration - #60578

Merged
Mayisha merged 65 commits into
trunkfrom
feature/paypal-wps-migration
Sep 19, 2025
Merged

Mayisha merged 65 commits into
trunkfrom
feature/paypal-wps-migration

Conversation

@annemirasol

@annemirasol annemirasol commented Aug 23, 2025 •

Copy link
Copy Markdown

Submission Review Guidelines:

Changes proposed in this Pull Request:

Feature branch for the PayPal WPS migration project.

How to test the changes in this Pull Request:

Server setup
Follow the instructions in PeNR48-1NQ-p2 to set up the server.

Client setup

  1. Checkout and build this feature branch.
  2. Enable PayPal Standard: wp option patch update woocommerce_paypal_settings _should_load 'yes'
  3. Go to WooCommerce > Settings > Payments, and enable PayPal Standard
  4. Go to PayPal settings,
    • Enable PayPal sandbox.
    • Enter your PayPal sandbox merchant account email in the PayPal email field.
      • Check the P2 page (PeNR48-1NQ-p2) for instructions on how to access Business Sandbox (merchant) Account information.
    • Make sure API credentials (username, password, signature) are empty.
  5. Enable the feature by adding this code snippet:
    add_filter( 'woocommerce_paypal_use_orders_v2', '__return_true' );
    
  6. Trigger Transact onboarding, using any of the following triggers.
    • Via plugin update: Set your WooCommerce version to an older version (wp option update woocommerce_version 10.1.0) then reload wp-admin.
    • Via settings save: Change a PayPal standard setting and click Save Changes.
  7. Verify Transact onboarding completed: wp option pluck woocommerce_paypal_settings transact_onboarding_complete should be a yes
  8. As a shopper, verify that you are able to complete purchases using PayPal.
    • Shopper credentials: Check the P2 page (PeNR48-1NQ-p2) for access to PayPal dev credentials, including the username and password for the Personal Sandbox (shopper) Account.

Testing that has already taken place:

Changelog entry

  • Automatically create a changelog entry from the details below.
  • This Pull Request does not require a changelog entry. (Comment required below)
Changelog Entry Details

Significance

  • Patch
  • Minor
  • Major

Type

  • Fix - Fixes an existing bug
  • Add - Adds functionality
  • Update - Update existing functionality
  • Dev - Development related task
  • Tweak - A minor adjustment to the codebase
  • Performance - Address performance issues
  • Enhancement - Improvement to existing functionality

Message

Changelog Entry Comment

Comment

Anne Mirasol and others added 23 commits July 21, 2025 22:12
…uest (#60242)

check status before sending capture request
* add blog_id in custom data

* update proxy webhook to generate endpoint from site url

* jp check

* remove test changes

* validate webhook

* validate test webhook

* remove backslash

* check if class & method exists

* fix return and log
* Add Transact merchant onboarding

* Add Transact provider onboarding

* Handle onboarding responses and set local flag

* Include PayPal account email in onboarding request

* Update is_transact_onboarded to use yes/no values

* Update should_use_orders_v2() check

* Move stuff to manager class, add caching

* Feedback: remove unnecessary store_url and statement_descriptor

* Remove error logs and fix phpcs errors

* Wrap API call in helper method; make class final for security

* Add unit tests

* Remove changes unrelated to branch

* Remove email from merchant onboarding request and response

* Fix onboarding logic, limit trigger

* Check use_orders_v2 filter before onboarding

* Feedback: fix GET request body

* Remove unused libraries

Co-authored-by: Mayisha <33387139+Mayisha@users.noreply.github.com>

* Fix class docblock typo

Co-authored-by: Mayisha <33387139+Mayisha@users.noreply.github.com>

* Add gateway type in constructor param

Co-authored-by: Mayisha <33387139+Mayisha@users.noreply.github.com>

* Revert changes to API loaders

* Use already available response data

Co-authored-by: Mayisha <33387139+Mayisha@users.noreply.github.com>

* Remove unused libraries in test

Co-authored-by: Mayisha <33387139+Mayisha@users.noreply.github.com>

* Move onboarding trigger to plugin update and settings save

* Cache merchant and provider data on onboarding complete

* Fix onboarding status checking, caching

---------

Co-authored-by: Mayisha <33387139+Mayisha@users.noreply.github.com>
* Implement singleton for WC_Gateway_Paypal

* Fix unit tests

* Remove unnecessary changes to unit test
* Handle 201 in capture/authorize payment

* Use Jetpack for authenticated requests to proxy

* Update proxy endpoints

* Fix unit tests
@github-actions github-actions Bot added the plugin: woocommerce Issues related to the WooCommerce Core plugin. label Aug 23, 2025
@annemirasol
annemirasol marked this pull request as ready for review August 26, 2025 15:07
@github-actions

github-actions Bot commented Aug 26, 2025 •

Copy link
Copy Markdown
Contributor

Test using WordPress Playground

The changes in this pull request can be previewed and tested using a WordPress Playground instance.
WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Test this pull request with WordPress Playground.

Note that this URL is valid for 30 days from when this comment was last updated. You can update it by closing/reopening the PR or pushing a new commit.

@wjrosa wjrosa left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome work! Code looks to me. Left multiple optional comments

@malithsen malithsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies for the delayed review. This took some time to set up, and I've made progress with help from @annemirasol. Thank you!!

✅ I see the registration requests hitting my sandbox as expected when updating settings.
✅ After placing an order, I see an event in the webhook logs to my sandbox.
⚠️ The webhook receives a 403 response from my sandbox.
⚠️ In the merchant store, the order remains in the "Pending payment" status.

I've double-checked that my sandbox secrets, and they all appear to be correct. I've enabled other sandbox access requirements mentioned in PeNR48-1NQ-p2

I'd appreciate some additional assistance in figuring out the issue.

@Mayisha

Mayisha commented Sep 11, 2025

Copy link
Copy Markdown
Contributor

⚠️ The webhook receives a 403 response from my sandbox.
⚠️ In the merchant store, the order remains in the "Pending payment" status.

These 2 are related. Since the webhooks are not processed, the order never reaches the processing state.
@malithsen could you please check if your server has the latest code (check if git pull is needed). I have changed the webhook ID constant name in my last server PR and the ID is used in the validation callback. Is it possible that you have the old code? Considering you are getting 403 response, it might be failing the REST validation there. 👀

@malithsen

Copy link
Copy Markdown
Contributor

@Mayisha My trunk on the sandbox is up-to-date. Testing this today, I am seeing a different behavior than yesterday. Order is in the completed status, but I don't see a webhook attempt on the sandbox. I am using the default sandbox merchant and the default sandbox shopper (if that helps).

CleanShot 2025-09-11 at 13 37 33@2x

@Mayisha Mayisha mentioned this pull request Sep 12, 2025
12 tasks

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (1)

711-720: Fix bug: has_paypal_orders returns true only when exactly one order exists.

Use > 0 instead of === 1.

-		return is_countable( $paypal_orders ) ? 1 === count( $paypal_orders ) : false;
+		return is_countable( $paypal_orders ) ? count( $paypal_orders ) > 0 : false;
♻️ Duplicate comments (2)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (1)

441-451: Remove inline assignments; sanitize item fields; cast quantity to string.

Eliminates PHPMD warnings and formats values per PayPal schema.

 	foreach ( $order->get_items() as $item ) {
 		$items[] = array(
-			'name'        => $this->limit_length( $item->get_name(), WC_Gateway_Paypal_Constants::PAYPAL_ORDER_ITEM_NAME_MAX_LENGTH ),
-			'quantity'    => $item->get_quantity(),
+			'name'        => $this->limit_length( wp_strip_all_tags( $item->get_name() ), WC_Gateway_Paypal_Constants::PAYPAL_ORDER_ITEM_NAME_MAX_LENGTH ),
+			'quantity'    => (string) max( 1, (int) $item->get_quantity() ),
 			'unit_amount' => array(
 				'currency_code' => $order->get_currency(),
 				// Use the subtotal before discounts.
-				'value'         => wc_format_decimal(
-					$order->get_item_subtotal( $item, $include_tax = false, $rounding_enabled = false ),
-					wc_get_price_decimals()
-				),
+				'value'         => wc_format_decimal( $order->get_item_subtotal( $item, false, false ), wc_get_price_decimals() ),
 			),
 		);
 	}
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (1)

665-677: Optional: restrict hiding actions to pending orders.

Previously discussed; noting for completeness.

-		if ( $this->should_use_orders_v2() && $this->id === $order->get_payment_method() ) {
+		if ( $this->should_use_orders_v2() && $this->id === $order->get_payment_method() && $order->has_status( 'pending' ) ) {
 			unset( $actions['pay'], $actions['cancel'] );
 		}
🧹 Nitpick comments (10)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php (1)

33-66: Add missing constants for custom_id and link rel/method; remove magic strings.

These are used in request/webhook code; defining them here improves consistency and avoids typos.

@@
 	/**
 	 * PayPal payment intents.
 	 */
 	const INTENT_CAPTURE   = 'CAPTURE';
 	const INTENT_AUTHORIZE = 'AUTHORIZE';
 
+	/**
+	 * PayPal additional statuses.
+	 */
+	const STATUS_PAYER_ACTION_REQUIRED = 'PAYER_ACTION_REQUIRED';
+
 	/**
 	 * PayPal payment actions.
 	 */
 	const PAYMENT_ACTION_CAPTURE   = 'capture';
 	const PAYMENT_ACTION_AUTHORIZE = 'authorize';
@@
 	const USER_ACTION_PAY_NOW = 'PAY_NOW';
 
 	/**
 	 * Maximum lengths for PayPal fields.
 	 */
+	const PAYPAL_CUSTOM_ID_MAX_LENGTH       = 127;
 	const PAYPAL_ORDER_ITEM_NAME_MAX_LENGTH = 127;
 	const PAYPAL_INVOICE_ID_MAX_LENGTH      = 127;
 	const PAYPAL_ADDRESS_LINE_MAX_LENGTH    = 300;
 	const PAYPAL_STATE_MAX_LENGTH           = 300;
 	const PAYPAL_CITY_MAX_LENGTH            = 120;
 	const PAYPAL_POSTAL_CODE_MAX_LENGTH     = 60;
+
+	/**
+	 * PayPal HATEOAS link rel and method constants.
+	 */
+	const LINK_REL_APPROVE      = 'approve';
+	const LINK_REL_PAYER_ACTION = 'payer-action';
+	const LINK_METHOD_GET       = 'GET';
+	const LINK_METHOD_POST      = 'POST';
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (5)

140-152: Guard JSON decode and log failures at error level.

Avoid notices when JSON is invalid and surface failures clearly.

-		$http_code     = wp_remote_retrieve_response_code( $response );
-		$body          = wp_remote_retrieve_body( $response );
-		$response_data = json_decode( $body, true );
+		$http_code     = wp_remote_retrieve_response_code( $response );
+		$body          = wp_remote_retrieve_body( $response );
+		$response_data = json_decode( $body, true );
+		if ( ! is_array( $response_data ) ) {
+			throw new Exception( 'PayPal order creation failed. Invalid JSON response.' );
+		}
@@
-	} catch ( Exception $e ) {
-		WC_Gateway_Paypal::log( $e->getMessage() );
+	} catch ( Exception $e ) {
+		WC_Gateway_Paypal::log( $e->getMessage(), 'error' );

149-152: Silence PHPMD unused parameter or remove it.

$http_code is unused in get_approve_link; rename to $_http_code to satisfy PHPMD with minimal churn.

-			$redirect_url = $this->get_approve_link( $http_code, $response_data );
+			$redirect_url = $this->get_approve_link( $http_code, $response_data );
@@
-	private function get_approve_link( $http_code, $response_data ) {
+	private function get_approve_link( $_http_code, $response_data ) {

Also applies to: 326-341


349-403: Only include shipping when present; keep payee email sanitized.

Avoid sending "shipping": null. This matches PayPal’s expectations and reduces payload noise.

-	private function get_paypal_create_order_request_params( $order ) {
-		$currency    = $order->get_currency();
-		$payee_email = sanitize_email( (string) $this->gateway->get_option( 'email' ) );
+	private function get_paypal_create_order_request_params( $order ) {
+		$currency    = $order->get_currency();
+		$payee_email = sanitize_email( (string) $this->gateway->get_option( 'email' ) );
+		$shipping    = $this->get_paypal_order_shipping( $order );
@@
-			'purchase_units' => array(
-				array(
+			'purchase_units' => array(
+				array_merge(
+					array(
 					'custom_id'  => $this->get_paypal_order_custom_id( $order ),
@@
-					'payee'      => array(
-						'email_address' => $payee_email,
-					),
-					'shipping'   => $this->get_paypal_order_shipping( $order ),
-				),
+					'payee'      => array(
+						'email_address' => $payee_email,
+					),
+					),
+					null !== $shipping ? array( 'shipping' => $shipping ) : array()
+				),

506-516: Fix return type in docblock.

Method returns null when no shipping; align docblock.

-	 * @return array
+	 * @return array|null

537-545: Correct proxy helper docblock and log severity for missing site ID.

Reflect WP_Error return and mark log as error for better observability.

-	 * @return array|null The API response body, or null if the request fails.
-	 * @throws Exception If the site ID is not found.
+	 * @return array|WP_Error Response or WP_Error.
+	 * @throws Exception If the site ID is not found.
@@
-		if ( ! $site_id ) {
-			WC_Gateway_Paypal::log( sprintf( 'Site ID not found. Cannot send request to %s.', $endpoint ) );
+		if ( ! $site_id ) {
+			WC_Gateway_Paypal::log( sprintf( 'Site ID not found. Cannot send request to %s.', $endpoint ), 'error' );
 			throw new Exception( 'Site ID not found. Cannot send proxy request.' );
 		}

Also applies to: 551-564

plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (3)

58-66: Guard nested purchase_units indexing; avoid notices on malformed payloads.

Defensive check prevents undefined index notices.

-	$custom_id = $event['resource']['purchase_units'][0]['custom_id'];
+	if ( empty( $event['resource']['purchase_units'][0]['custom_id'] ) ) {
+		WC_Gateway_Paypal::log( 'Missing custom_id in CHECKOUT.ORDER.APPROVED.', 'warning' );
+		return;
+	}
+	$custom_id = $event['resource']['purchase_units'][0]['custom_id'];

71-88: Use constants for status and rel; small consistency cleanup.

Avoid magic strings and align with constants class.

-		if ( 'APPROVED' === $status ) {
+		if ( WC_Gateway_Paypal_Constants::STATUS_APPROVED === $status ) {
@@
-			$action = WC_Gateway_Paypal_Constants::INTENT_CAPTURE === $event['resource']['intent'] ? WC_Gateway_Paypal_Constants::PAYMENT_ACTION_CAPTURE : WC_Gateway_Paypal_Constants::PAYMENT_ACTION_AUTHORIZE;
+			$action = WC_Gateway_Paypal_Constants::INTENT_CAPTURE === ( $event['resource']['intent'] ?? '' )
+				? WC_Gateway_Paypal_Constants::PAYMENT_ACTION_CAPTURE
+				: WC_Gateway_Paypal_Constants::PAYMENT_ACTION_AUTHORIZE;

120-131: Validate required resource keys before use.

Guard id/status to avoid notices on malformed events.

-	$order->set_transaction_id( $event['resource']['id'] );
-	$order->update_meta_data( '_paypal_status', $event['resource']['status'] );
+	if ( empty( $event['resource']['id'] ) || empty( $event['resource']['status'] ) ) {
+		WC_Gateway_Paypal::log( 'Incomplete capture payload.', 'warning' );
+		return;
+	}
+	$order->set_transaction_id( $event['resource']['id'] );
+	$order->update_meta_data( '_paypal_status', $event['resource']['status'] );
@@
-	$order->set_transaction_id( $event['resource']['id'] );
+	if ( empty( $event['resource']['id'] ) ) {
+		WC_Gateway_Paypal::log( 'Missing authorization id.', 'warning' );
+		return;
+	}
+	$order->set_transaction_id( $event['resource']['id'] );

Also applies to: 151-161

plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (1)

449-459: Typo: “fiels” → “fields”.

Minor docs cleanup.

-		// Remove legacy setting fiels when using Orders v2.
+		// Remove legacy setting fields when using Orders v2.
📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5e1d996 and 8b46bc6.

📒 Files selected for processing (6)
  • plugins/woocommerce/changelog/60578-feature-paypal-wps-migration (1 hunks)
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (13 hunks)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php (1 hunks)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (6 hunks)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (1 hunks)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • plugins/woocommerce/changelog/60578-feature-paypal-wps-migration
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{php,js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/code-quality.mdc)

**/*.{php,js,jsx,ts,tsx}: Guard against unexpected inputs
Sanitize and validate any potentially dangerous inputs
Ensure code is backwards compatible
Write code that is readable and intuitive
Ensure code has unit or E2E tests where applicable

Files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
**/*.{php,js,ts,jsx,tsx}

⚙️ CodeRabbit configuration file

**/*.{php,js,ts,jsx,tsx}: Don't trust that extension developers will follow the best practices, make sure the code:

  • Guards against unexpected inputs.
  • Sanitizes and validates any potentially dangerous inputs.
  • Is backwards compatible.
  • Is readable and intuitive.
  • Has unit or E2E tests where applicable.

Files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
🧠 Learnings (18)
📓 Common learnings
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php:104-113
Timestamp: 2025-09-03T17:16:04.109Z
Learning: For the PayPal WPS migration project in WooCommerce, legacy settings (marked with 'is_legacy' => true in settings-paypal.php) should not be modified as part of the migration work. Changes to legacy settings should be handled in separate PRs to maintain focused scope on the WPS migration functionality.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:0-0
Timestamp: 2025-08-26T20:17:52.027Z
Learning: In the PayPal WPS migration, webhook signature validation is handled at the controller level (WC_REST_Paypal_Webhooks_Controller) using Jetpack's REST authentication (is_signed_with_blog_token), not within the webhook handler itself. The webhooks are processed through WordPress.com proxy infrastructure.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: In WooCommerce PayPal gateway, the transact_onboarding_complete flag is used specifically in should_use_orders_v2() to determine Orders v2 API eligibility, but it should not prevent the onboarding flow from running account creation logic. The maybe_onboard_with_transact() method should still check and create merchant/provider accounts even when this flag is set, as account creation might need to happen multiple times to ensure proper setup.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: WooCommerce PayPal gateway onboarding via maybe_onboard_with_transact() should only run when the gateway is explicitly enabled (enabled === 'yes'), not when should_load() returns true. The should_load() method includes cases where the gateway is disabled but has existing PayPal orders, and onboarding should not occur in those scenarios since the merchant is not intending to actively use PayPal for new transactions.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/wc-update-functions.php:2753-2753
Timestamp: 2025-08-26T19:40:34.395Z
Learning: In WooCommerce PayPal gateway migration, direct instantiation with `new WC_Gateway_Paypal()` is acceptable and preferred in unit test code for better test isolation, even when production code uses the singleton pattern `WC_Gateway_Paypal::get_instance()`. Test code should maintain the ability to create fresh instances to avoid shared state between tests.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php:177-184
Timestamp: 2025-09-03T17:40:23.781Z
Learning: In the PayPal WPS migration project for WooCommerce, Jetpack Options is expected to be present as a required dependency. Defensive checks for class_exists('Jetpack_Options') are not needed in the WC_Gateway_Paypal_Transact_Account_Manager class methods.
📚 Learning: 2025-08-26T19:40:34.395Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/wc-update-functions.php:2753-2753
Timestamp: 2025-08-26T19:40:34.395Z
Learning: In WooCommerce PayPal gateway migration, direct instantiation with `new WC_Gateway_Paypal()` is acceptable and preferred in unit test code for better test isolation, even when production code uses the singleton pattern `WC_Gateway_Paypal::get_instance()`. Test code should maintain the ability to create fresh instances to avoid shared state between tests.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-08-26T20:27:43.267Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:58-83
Timestamp: 2025-08-26T20:27:43.267Z
Learning: The _paypal_order_id is persisted during PayPal order creation in the WC_Gateway_Paypal::process_payment() method at line 511, not in the webhook handler, so it's already available when webhooks are processed.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-08-26T20:27:43.267Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:58-83
Timestamp: 2025-08-26T20:27:43.267Z
Learning: In WC_Gateway_Paypal_Webhook_Handler, the get_wc_order() method already provides comprehensive validation for custom_id by JSON decoding it and validating both order_id presence and order_key matching against the WC order, making additional structure validation unnecessary.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
📚 Learning: 2025-08-26T20:17:52.027Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:0-0
Timestamp: 2025-08-26T20:17:52.027Z
Learning: In the PayPal WPS migration, webhook signature validation is handled at the controller level (WC_REST_Paypal_Webhooks_Controller) using Jetpack's REST authentication (is_signed_with_blog_token), not within the webhook handler itself. The webhooks are processed through WordPress.com proxy infrastructure.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
📚 Learning: 2025-09-03T16:16:11.508Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:586-592
Timestamp: 2025-09-03T16:16:11.508Z
Learning: The capture_authorized_payment() method in WC_Gateway_Paypal_Request has comprehensive internal exception handling - it catches exceptions, logs them via WC_Gateway_Paypal::log(), adds order notes with failure details, and doesn't rethrow exceptions, making it safe to call without additional try/catch blocks at the call site.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-03T16:16:11.508Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:586-592
Timestamp: 2025-09-03T16:16:11.508Z
Learning: In WC_Gateway_Paypal_Request::capture_authorized_payment(), exceptions are handled internally, so additional try/catch blocks at the call site in capture_payment() are not necessary.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-06-17T07:07:53.443Z
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:83-101
Timestamp: 2025-06-17T07:07:53.443Z
Learning: In WooCommerce blocks, when porting existing code patterns that have known issues (like parseInt truncating decimal money values), maintain consistency with existing implementation rather than making isolated fixes. The preference is for systematic refactoring approaches (like broader Dinero adoption) over piecemeal changes.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
📚 Learning: 2025-09-03T16:44:00.460Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php:225-239
Timestamp: 2025-09-03T16:44:00.460Z
Learning: PayPal Orders v2 API defines successful responses as only HTTP 200 and 201, not the broader 2xx range that is typical for REST APIs.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
📚 Learning: 2025-06-17T10:33:54.736Z
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/src/Internal/Admin/Settings/PaymentsProviders/WooPayments/WooPaymentsRestController.php:619-625
Timestamp: 2025-06-17T10:33:54.736Z
Learning: In the WooCommerce WooPayments REST controller, it's acceptable to let ApiException bubble up from onboarding-related method calls like get_onboarding_step_status() and mark_onboarding_step_completed() rather than wrapping them in local try/catch blocks.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-03T17:27:20.855Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php:331-346
Timestamp: 2025-09-03T17:27:20.855Z
Learning: The get_approve_link() method in WC_Gateway_Paypal_Request is only called on successful PayPal API responses (HTTP 200/201), so the links array will always be present in the response data and doesn't need null/empty guards.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
📚 Learning: 2025-09-03T17:40:23.781Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php:177-184
Timestamp: 2025-09-03T17:40:23.781Z
Learning: In the PayPal WPS migration project for WooCommerce, Jetpack Options is expected to be present as a required dependency. Defensive checks for class_exists('Jetpack_Options') are not needed in the WC_Gateway_Paypal_Transact_Account_Manager class methods.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-08-29T09:50:56.633Z
Learnt from: Aljullu
PR: woocommerce/woocommerce#60667
File: plugins/woocommerce/client/blocks/tests/e2e/tests/add-to-cart-with-options/add-to-cart-with-options.block_theme.spec.ts:187-193
Timestamp: 2025-08-29T09:50:56.633Z
Learning: Aljullu prefers to keep test timeouts consistent with existing similar tests and only increase them if actual flakiness is observed, rather than making preemptive changes.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
📚 Learning: 2025-09-03T17:11:34.772Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: WooCommerce PayPal gateway onboarding via maybe_onboard_with_transact() should only run when the gateway is explicitly enabled (enabled === 'yes'), not when should_load() returns true. The should_load() method includes cases where the gateway is disabled but has existing PayPal orders, and onboarding should not occur in those scenarios since the merchant is not intending to actively use PayPal for new transactions.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-08-22T15:20:09.770Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60563
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-helper.php:23-28
Timestamp: 2025-08-22T15:20:09.770Z
Learning: In WooCommerce PayPal gateway helper methods, `is_paypal_gateway_available()` should check only the `_should_load` flag, not the `enabled` setting, because `_should_load` is computed as `enabled || has_paypal_orders()` in the gateway's `should_load()` method and represents the authoritative decision on whether PayPal functionality should be initialized. The `enabled` setting always takes precedence in the loader logic.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-08-22T15:20:09.770Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60563
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-helper.php:23-28
Timestamp: 2025-08-22T15:20:09.770Z
Learning: In WooCommerce PayPal gateway helper methods, `is_paypal_gateway_available()` should check only the `_should_load` flag, not the `enabled` setting, because `_should_load` is computed as `enabled || has_paypal_orders()` in the gateway's `should_load()` method and represents the authoritative decision on whether PayPal functionality should be initialized.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-03T17:11:34.772Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: In WooCommerce PayPal gateway, the transact_onboarding_complete flag is used specifically in should_use_orders_v2() to determine Orders v2 API eligibility, but it should not prevent the onboarding flow from running account creation logic. The maybe_onboard_with_transact() method should still check and create merchant/provider accounts even when this flag is set, as account creation might need to happen multiple times to ensure proper setup.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-03T17:16:04.109Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php:104-113
Timestamp: 2025-09-03T17:16:04.109Z
Learning: For the PayPal WPS migration project in WooCommerce, legacy settings (marked with 'is_legacy' => true in settings-paypal.php) should not be modified as part of the migration work. Changes to legacy settings should be handled in separate PRs to maintain focused scope on the WPS migration functionality.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
🧬 Code graph analysis (3)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (7)
plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-webhooks-controller.php (1)
  • process_webhook (82-92)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (2)
  • WC_Gateway_Paypal (32-807)
  • log (248-260)
plugins/woocommerce/includes/wc-core-functions.php (1)
  • wc_print_r (2181-2216)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php (1)
  • WC_Gateway_Paypal_Constants (20-66)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (1)
  • authorize_or_capture_payment (184-256)
plugins/woocommerce/includes/class-wc-order.php (3)
  • set_transaction_id (1504-1506)
  • payment_complete (136-197)
  • update_status (387-411)
plugins/woocommerce/includes/wc-order-functions.php (1)
  • wc_get_order (88-94)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (5)
plugins/woocommerce/src/Utilities/NumberUtil.php (1)
  • NumberUtil (15-193)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (2)
  • WC_Gateway_Paypal (32-807)
  • log (248-260)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (1)
  • authorize_or_capture_payment (202-219)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php (1)
  • WC_Gateway_Paypal_Constants (20-66)
plugins/woocommerce/includes/wc-formatting-functions.php (2)
  • wc_format_decimal (288-317)
  • wc_get_price_decimals (562-564)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (3)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-helper.php (3)
  • WC_Gateway_Paypal_Helper (17-56)
  • is_orders_v2_migration_eligible (35-46)
  • is_orders_v2_feature_flag_enabled (53-55)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (4)
  • WC_Gateway_Paypal_Transact_Account_Manager (19-394)
  • do_onboarding (72-123)
  • get_merchant_account_data (131-147)
  • get_provider_account_data (155-170)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (2)
  • create_paypal_order (127-171)
  • capture_authorized_payment (265-317)
🪛 PHPMD (2.15.0)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php

326-326: Avoid unused parameters such as '$http_code'. (undefined)

(UnusedFormalParameter)


448-448: Avoid unused local variables such as '$include_tax'. (undefined)

(UnusedLocalVariable)


448-448: Avoid unused local variables such as '$rounding_enabled'. (undefined)

(UnusedLocalVariable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (23)
  • GitHub Check: Blocks e2e tests 9/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 7/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 8/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 10/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 5/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 2/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 6/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 3/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 6/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 1/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Metrics - @woocommerce/plugin-woocommerce [performance]
  • GitHub Check: Blocks e2e tests 4/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 5/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core API tests - @woocommerce/plugin-woocommerce [api]
  • GitHub Check: Core e2e tests 2/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 4/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.3] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Core e2e tests 1/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 3/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.3] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: build
🔇 Additional comments (6)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (1)

413-426: Handle wp_json_encode failure and enforce a configurable PayPal custom_id max length

File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (lines ~413-426)

  • Check for wp_json_encode === false before calling strlen (strlen(false) will error); throw on encode failure.
  • PayPal docs do not specify purchase_units[].custom_id length; use a constant WC_Gateway_Paypal_Constants::PAYPAL_CUSTOM_ID_MAX_LENGTH (conservative ≤256, e.g. 255) and verify the authoritative limit with PayPal support.
 	private function get_paypal_order_custom_id( $order ) {
-		$custom_id = wp_json_encode(
+		$custom_id = wp_json_encode(
 			array(
@@
-		);
+		);
+		if ( false === $custom_id ) {
+			throw new Exception( 'Failed to encode PayPal custom ID.' );
+		}
 
-		if ( strlen( $custom_id ) > 255 ) {
-			throw new Exception( 'PayPal order custom ID is too long. Max length is 255 chars.' );
+		if ( strlen( $custom_id ) > WC_Gateway_Paypal_Constants::PAYPAL_CUSTOM_ID_MAX_LENGTH ) {
+			throw new Exception( 'PayPal order custom ID is too long. Max length is ' . WC_Gateway_Paypal_Constants::PAYPAL_CUSTOM_ID_MAX_LENGTH . ' chars.' );
 		}
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (1)

28-36: Good: payload shape is validated before routing.

Early bail reduces notices from malformed requests.

plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (4)

248-259: Good: lazy-init logger from settings.

Keeps log level in sync without constructor side-effects.


189-226: Onboarding gating is clear and minimal.

Admin-only, capability-checked, feature-flagged, and respects overrides.


480-505: Orders v2 path: solid error handling and persistence.

Throws on failure, persists PayPal order ID, and cleanly falls back to legacy path.


589-596: OK to omit try/catch here.

capture_authorized_payment handles its own exceptions.

Comment on lines +8 to 13
declare(strict_types=1);

use Automattic\WooCommerce\Utilities\NumberUtil;
use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\Jetpack\Connection\Client as Jetpack_Connection_Client;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Prevent fatal: ensure constants are loaded before this file (used in default params).

This class references WC_Gateway_Paypal_Constants in default parameter values, which PHP resolves at load time. Require the constants file defensively.

 declare(strict_types=1);
 
+// Ensure constants class is available before this file is parsed.
+if ( ! class_exists( 'WC_Gateway_Paypal_Constants' ) ) {
+	require_once __DIR__ . '/class-wc-gateway-paypal-constants.php';
+}
+
 use Automattic\WooCommerce\Utilities\NumberUtil;

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
around lines 8–13, this file uses WC_Gateway_Paypal_Constants in default
parameter values which are resolved at load time; defensively require the
constants file before the class is declared by adding a require_once for the
constants file (e.g. require_once __DIR__ .
'/class-wc-gateway-paypal-constants.php';) near the top of the file (before the
class declaration / any function signatures that reference the constants) so the
constant definitions are loaded first.

Comment on lines +16 to +17
require_once __DIR__ . '/class-wc-gateway-paypal-request.php';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Prevent fatal: load constants before including request class.

Request class uses constants in default params; ensure constants are available.

-require_once __DIR__ . '/class-wc-gateway-paypal-request.php';
+if ( ! class_exists( 'WC_Gateway_Paypal_Constants' ) ) {
+	require_once __DIR__ . '/class-wc-gateway-paypal-constants.php';
+}
+require_once __DIR__ . '/class-wc-gateway-paypal-request.php';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
require_once __DIR__ . '/class-wc-gateway-paypal-request.php';
if ( ! class_exists( 'WC_Gateway_Paypal_Constants' ) ) {
require_once __DIR__ . '/class-wc-gateway-paypal-constants.php';
}
require_once __DIR__ . '/class-wc-gateway-paypal-request.php';
🤖 Prompt for AI Agents
In
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
around lines 16-17, the request class is required before the plugin constants it
depends on are defined, which can cause a fatal error; ensure any file that
defines those constants (e.g., plugin bootstrap or constants file) is
required/loaded before require_once __DIR__ .
'/class-wc-gateway-paypal-request.php'; update the file to require the
constants/bootstrap file first (or move the request include below the
constants-definition include), so the constants exist when the request class is
loaded.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (1)

717-720: Logic bug: has_paypal_orders() returns true only when exactly one order exists.

Should be “> 0”, not “=== 1”. This affects _should_load initialization on existing stores.

-		return is_countable( $paypal_orders ) ? 1 === count( $paypal_orders ) : false;
+		return is_countable( $paypal_orders ) ? count( $paypal_orders ) > 0 : false;
♻️ Duplicate comments (1)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (1)

16-16: Prevent fatal: load constants before loading the request class.

WC_Gateway_Paypal_Request references constants; ensure they’re defined first.

-require_once __DIR__ . '/class-wc-gateway-paypal-request.php';
+if ( ! class_exists( 'WC_Gateway_Paypal_Constants' ) ) {
+	require_once __DIR__ . '/class-wc-gateway-paypal-constants.php';
+}
+if ( ! class_exists( 'WC_Gateway_Paypal_Request' ) ) {
+	require_once __DIR__ . '/class-wc-gateway-paypal-request.php';
+}
🧹 Nitpick comments (10)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (5)

127-135: Fix return type in phpdoc (provider path returns bool).

get_transact_account_data() can return array (merchant) or bool (provider). Update the docblock to avoid misleading callers.

-	 * @return array|null Returns null if the transact account cannot be retrieved.
+	 * @return array|bool|null Returns merchant data (array), provider existence (bool), or null if unavailable.

301-307: Param type mismatch in cache updater.

$account_data is bool for provider accounts. Adjust phpdoc.

-	 * @param array  $account_data The transact account data.
+	 * @param mixed  $account_data The transact account data (array for merchant, bool for provider).

318-324: Cache getter docblock is incorrect.

Cache may contain merchant array or provider bool. Update return type.

-	 * @return bool|null The transact account data, or null if the cache is
+	 * @return array|bool|null The transact account data, or null if the cache is

338-344: send_transact_api_request() docblock return type is wrong.

Method returns the raw WP HTTP response array or WP_Error, not “array|null”.

-	 * @return array|null The API response body, or null if the request fails.
+	 * @return array|\WP_Error Raw WP HTTP response array or WP_Error.

196-199: Add diagnostics when Transact fetch fails (helps 403 debugging).

Log HTTP status/body or WP_Error for merchant/provider fetch failures.

-		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
-			return null;
-		}
+		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
+			WC_Gateway_Paypal::log(
+				'Failed to fetch Transact merchant account. ' .
+				( is_wp_error( $response )
+					? $response->get_error_message()
+					: 'HTTP ' . wp_remote_retrieve_response_code( $response ) . ' Body: ' . wp_remote_retrieve_body( $response )
+				),
+				'warning'
+			);
+			return null;
+		}
-		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
-			return false;
-		}
+		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
+			WC_Gateway_Paypal::log(
+				'Failed to fetch Transact provider account. ' .
+				( is_wp_error( $response )
+					? $response->get_error_message()
+					: 'HTTP ' . wp_remote_retrieve_response_code( $response ) . ' Body: ' . wp_remote_retrieve_body( $response )
+				),
+				'warning'
+			);
+			return false;
+		}

Also applies to: 230-233

plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (3)

29-33: Use warning level for invalid payload logs.

Surface malformed payloads as warnings.

-			WC_Gateway_Paypal::log( 'Invalid PayPal webhook payload: ' . wc_print_r( $data, true ) );
+			WC_Gateway_Paypal::log( 'Invalid PayPal webhook payload: ' . wc_print_r( $data, true ), 'warning' );

71-74: Prefer constant for status comparison.

Avoid magic string; use the PayPal status constant.

-		if ( 'APPROVED' === $status ) {
+		if ( WC_Gateway_Paypal_Constants::STATUS_APPROVED === $status ) {

227-235: Guard links type to avoid foreach warnings.

$links can be null; ensure it’s an array before iterating.

 	private function get_action_url( $links, $action ) {
 		$action_url = null;
+		if ( ! is_array( $links ) ) {
+			return null;
+		}
 		foreach ( $links as $link ) {
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (2)

41-46: Docblock type doesn’t match initialized value.

$log_enabled is initialized to null. Update the doc.

-	 * @var bool
+	 * @var bool|null

449-456: Typo in comment.

“fiels” → “fields”.

-		// Remove legacy setting fiels when using Orders v2.
+		// Remove legacy setting fields when using Orders v2.
📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b46bc6 and 91cc867.

📒 Files selected for processing (3)
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (13 hunks)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (1 hunks)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{php,js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/code-quality.mdc)

**/*.{php,js,jsx,ts,tsx}: Guard against unexpected inputs
Sanitize and validate any potentially dangerous inputs
Ensure code is backwards compatible
Write code that is readable and intuitive
Ensure code has unit or E2E tests where applicable

Files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
**/*.{php,js,ts,jsx,tsx}

⚙️ CodeRabbit configuration file

**/*.{php,js,ts,jsx,tsx}: Don't trust that extension developers will follow the best practices, make sure the code:

  • Guards against unexpected inputs.
  • Sanitizes and validates any potentially dangerous inputs.
  • Is backwards compatible.
  • Is readable and intuitive.
  • Has unit or E2E tests where applicable.

Files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
🧠 Learnings (16)
📓 Common learnings
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php:104-113
Timestamp: 2025-09-03T17:16:04.109Z
Learning: For the PayPal WPS migration project in WooCommerce, legacy settings (marked with 'is_legacy' => true in settings-paypal.php) should not be modified as part of the migration work. Changes to legacy settings should be handled in separate PRs to maintain focused scope on the WPS migration functionality.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: In WooCommerce PayPal gateway, the transact_onboarding_complete flag is used specifically in should_use_orders_v2() to determine Orders v2 API eligibility, but it should not prevent the onboarding flow from running account creation logic. The maybe_onboard_with_transact() method should still check and create merchant/provider accounts even when this flag is set, as account creation might need to happen multiple times to ensure proper setup.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: WooCommerce PayPal gateway onboarding via maybe_onboard_with_transact() should only run when the gateway is explicitly enabled (enabled === 'yes'), not when should_load() returns true. The should_load() method includes cases where the gateway is disabled but has existing PayPal orders, and onboarding should not occur in those scenarios since the merchant is not intending to actively use PayPal for new transactions.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/wc-update-functions.php:2753-2753
Timestamp: 2025-08-26T19:40:34.395Z
Learning: In WooCommerce PayPal gateway migration, direct instantiation with `new WC_Gateway_Paypal()` is acceptable and preferred in unit test code for better test isolation, even when production code uses the singleton pattern `WC_Gateway_Paypal::get_instance()`. Test code should maintain the ability to create fresh instances to avoid shared state between tests.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php:177-184
Timestamp: 2025-09-03T17:40:23.781Z
Learning: In the PayPal WPS migration project for WooCommerce, Jetpack Options is expected to be present as a required dependency. Defensive checks for class_exists('Jetpack_Options') are not needed in the WC_Gateway_Paypal_Transact_Account_Manager class methods.
📚 Learning: 2025-08-26T20:27:43.267Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:58-83
Timestamp: 2025-08-26T20:27:43.267Z
Learning: The _paypal_order_id is persisted during PayPal order creation in the WC_Gateway_Paypal::process_payment() method at line 511, not in the webhook handler, so it's already available when webhooks are processed.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-08-26T20:27:43.267Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:58-83
Timestamp: 2025-08-26T20:27:43.267Z
Learning: In WC_Gateway_Paypal_Webhook_Handler, the get_wc_order() method already provides comprehensive validation for custom_id by JSON decoding it and validating both order_id presence and order_key matching against the WC order, making additional structure validation unnecessary.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
📚 Learning: 2025-08-26T20:17:52.027Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:0-0
Timestamp: 2025-08-26T20:17:52.027Z
Learning: In the PayPal WPS migration, webhook signature validation is handled at the controller level (WC_REST_Paypal_Webhooks_Controller) using Jetpack's REST authentication (is_signed_with_blog_token), not within the webhook handler itself. The webhooks are processed through WordPress.com proxy infrastructure.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
📚 Learning: 2025-09-03T16:16:11.508Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:586-592
Timestamp: 2025-09-03T16:16:11.508Z
Learning: The capture_authorized_payment() method in WC_Gateway_Paypal_Request has comprehensive internal exception handling - it catches exceptions, logs them via WC_Gateway_Paypal::log(), adds order notes with failure details, and doesn't rethrow exceptions, making it safe to call without additional try/catch blocks at the call site.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-03T16:16:11.508Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:586-592
Timestamp: 2025-09-03T16:16:11.508Z
Learning: In WC_Gateway_Paypal_Request::capture_authorized_payment(), exceptions are handled internally, so additional try/catch blocks at the call site in capture_payment() are not necessary.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-15T16:05:40.461Z
Learnt from: gigitux
PR: woocommerce/woocommerce#60898
File: plugins/woocommerce/src/RestApi/Routes/V4/OrderNotes/Controller.php:160-160
Timestamp: 2025-09-15T16:05:40.461Z
Learning: In WooCommerce, system-generated order notes use `__( 'WooCommerce', 'woocommerce' )` as the comment_author value (note the capital 'W' in 'WooCommerce'). When checking if an order note is system-generated, compare against this translated string rather than a raw string to ensure it works correctly on localized sites.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php
📚 Learning: 2025-08-26T19:40:34.395Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/wc-update-functions.php:2753-2753
Timestamp: 2025-08-26T19:40:34.395Z
Learning: In WooCommerce PayPal gateway migration, direct instantiation with `new WC_Gateway_Paypal()` is acceptable and preferred in unit test code for better test isolation, even when production code uses the singleton pattern `WC_Gateway_Paypal::get_instance()`. Test code should maintain the ability to create fresh instances to avoid shared state between tests.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
📚 Learning: 2025-09-03T17:40:23.781Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php:177-184
Timestamp: 2025-09-03T17:40:23.781Z
Learning: In the PayPal WPS migration project for WooCommerce, Jetpack Options is expected to be present as a required dependency. Defensive checks for class_exists('Jetpack_Options') are not needed in the WC_Gateway_Paypal_Transact_Account_Manager class methods.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
📚 Learning: 2025-09-03T17:11:34.772Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: WooCommerce PayPal gateway onboarding via maybe_onboard_with_transact() should only run when the gateway is explicitly enabled (enabled === 'yes'), not when should_load() returns true. The should_load() method includes cases where the gateway is disabled but has existing PayPal orders, and onboarding should not occur in those scenarios since the merchant is not intending to actively use PayPal for new transactions.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-08-22T15:20:09.770Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60563
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-helper.php:23-28
Timestamp: 2025-08-22T15:20:09.770Z
Learning: In WooCommerce PayPal gateway helper methods, `is_paypal_gateway_available()` should check only the `_should_load` flag, not the `enabled` setting, because `_should_load` is computed as `enabled || has_paypal_orders()` in the gateway's `should_load()` method and represents the authoritative decision on whether PayPal functionality should be initialized. The `enabled` setting always takes precedence in the loader logic.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-03T17:11:34.772Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: In WooCommerce PayPal gateway, the transact_onboarding_complete flag is used specifically in should_use_orders_v2() to determine Orders v2 API eligibility, but it should not prevent the onboarding flow from running account creation logic. The maybe_onboard_with_transact() method should still check and create merchant/provider accounts even when this flag is set, as account creation might need to happen multiple times to ensure proper setup.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
📚 Learning: 2025-08-22T15:20:09.770Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60563
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-helper.php:23-28
Timestamp: 2025-08-22T15:20:09.770Z
Learning: In WooCommerce PayPal gateway helper methods, `is_paypal_gateway_available()` should check only the `_should_load` flag, not the `enabled` setting, because `_should_load` is computed as `enabled || has_paypal_orders()` in the gateway's `should_load()` method and represents the authoritative decision on whether PayPal functionality should be initialized.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-06-17T10:33:54.736Z
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/src/Internal/Admin/Settings/PaymentsProviders/WooPayments/WooPaymentsRestController.php:619-625
Timestamp: 2025-06-17T10:33:54.736Z
Learning: In the WooCommerce WooPayments REST controller, it's acceptable to let ApiException bubble up from onboarding-related method calls like get_onboarding_step_status() and mark_onboarding_step_completed() rather than wrapping them in local try/catch blocks.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
📚 Learning: 2025-09-03T17:16:04.109Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php:104-113
Timestamp: 2025-09-03T17:16:04.109Z
Learning: For the PayPal WPS migration project in WooCommerce, legacy settings (marked with 'is_legacy' => true in settings-paypal.php) should not be modified as part of the migration work. Changes to legacy settings should be handled in separate PRs to maintain focused scope on the WPS migration functionality.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
📚 Learning: 2025-08-29T09:50:56.633Z
Learnt from: Aljullu
PR: woocommerce/woocommerce#60667
File: plugins/woocommerce/client/blocks/tests/e2e/tests/add-to-cart-with-options/add-to-cart-with-options.block_theme.spec.ts:187-193
Timestamp: 2025-08-29T09:50:56.633Z
Learning: Aljullu prefers to keep test timeouts consistent with existing similar tests and only increase them if actual flakiness is observed, rather than making preemptive changes.

Applied to files:

  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
🧬 Code graph analysis (3)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php (7)
plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-webhooks-controller.php (1)
  • process_webhook (82-92)
plugins/woocommerce/includes/wc-core-functions.php (1)
  • wc_print_r (2181-2216)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php (1)
  • WC_Gateway_Paypal_Constants (20-66)
plugins/woocommerce/includes/abstracts/abstract-wc-data.php (2)
  • get_meta (357-385)
  • update_meta_data (463-504)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (1)
  • authorize_or_capture_payment (184-256)
plugins/woocommerce/includes/class-wc-order.php (3)
  • set_transaction_id (1504-1506)
  • payment_complete (136-197)
  • update_status (387-411)
plugins/woocommerce/includes/wc-order-functions.php (1)
  • wc_get_order (88-94)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (3)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-helper.php (3)
  • WC_Gateway_Paypal_Helper (17-56)
  • is_orders_v2_migration_eligible (35-46)
  • is_orders_v2_feature_flag_enabled (53-55)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (3)
  • WC_Gateway_Paypal_Transact_Account_Manager (19-363)
  • do_onboarding (72-125)
  • get_transact_account_data (135-155)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php (4)
  • WC_Gateway_Paypal_Request (21-1052)
  • create_paypal_order (127-171)
  • get_request_url (91-115)
  • capture_authorized_payment (265-317)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (3)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (5)
  • __construct (126-188)
  • WC_Gateway_Paypal (32-807)
  • get_jetpack_connection_manager (778-783)
  • log (248-260)
  • set_transact_onboarding_complete (799-806)
plugins/woocommerce/includes/wc-core-functions.php (1)
  • wc_print_r (2181-2216)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-constants.php (1)
  • WC_Gateway_Paypal_Constants (20-66)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (24)
  • GitHub Check: Blocks e2e tests 4/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 6/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 5/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 8/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 9/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 10/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 7/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 3/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 1/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 2/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core API tests - @woocommerce/plugin-woocommerce [api]
  • GitHub Check: Core e2e tests 6/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 3/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 5/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 4/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 1/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Metrics - @woocommerce/plugin-woocommerce [performance]
  • GitHub Check: Core e2e tests 2/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.3] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.3] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Lint - @woocommerce/plugin-woocommerce
  • GitHub Check: build

Comment on lines +136 to +143
if ( empty( $cache_key ) ) {
$cache_key = $this->get_cache_key( $account_type );
}

// Get transact account from cache. If not found, fetch/create it.
$transact_account = $this->get_transact_account_from_cache( $cache_key );
if ( empty( $transact_account ) ) {
$transact_account = 'merchant' === $account_type ? $this->fetch_merchant_account() : $this->fetch_provider_account();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Guard invalid account_type to avoid get_option(null).

If $account_type is invalid, $cache_key remains empty and get_option( null ) is unsafe. Bail early.

 		if ( empty( $cache_key ) ) {
 			$cache_key = $this->get_cache_key( $account_type );
 		}
 
+		if ( empty( $cache_key ) ) {
+			return null;
+		}

Also applies to: 163-173

🤖 Prompt for AI Agents
In
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
around lines 136-143 (and likewise 163-173), guard against invalid $account_type
before calling get_cache_key or fetching accounts: validate that $account_type
is one of the expected values (e.g., 'merchant' or 'provider') and if not, bail
early (return null or a WP_Error) instead of proceeding and calling
get_option(null); update both code paths to perform this validation and only
call get_cache_key, get_transact_account_from_cache, fetch_merchant_account or
fetch_provider_account when $account_type is valid.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php (1)

128-129: Fix pre_http_request callbacks: pass 0 accepted args to avoid "too many arguments" warnings

These helpers have 0 parameters but the default accepted args for add_filter is 1. Explicitly set accepted args to 0 for all pre_http_request filters listed above.

Apply across all occurrences:

- add_filter( 'pre_http_request', array( $this, 'return_api_error' ) );
+ add_filter( 'pre_http_request', array( $this, 'return_api_error' ), 10, 0 );

- add_filter( 'pre_http_request', array( $this, 'return_merchant_account_api_success' ) );
+ add_filter( 'pre_http_request', array( $this, 'return_merchant_account_api_success' ), 10, 0 );

- add_filter( 'pre_http_request', array( $this, 'return_provider_account_api_success' ) );
+ add_filter( 'pre_http_request', array( $this, 'return_provider_account_api_success' ), 10, 0 );
#!/bin/bash
# Verify all pre_http_request filters in this test pass accepted args = 0
rg -n "add_filter\(\s*'pre_http_request'.*\)" -n plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php \
  | sed -n 's/^\(.*\)$/CHECK: \1/p'
rg -n "add_filter\(\s*'pre_http_request'.*,\s*array\(.*\),\s*10,\s*0\s*\)" plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php

Also applies to: 164-165, 238-239, 321-321, 352-353, 380-381, 408-409, 438-439, 466-467, 498-499, 530-531, 558-559

🧹 Nitpick comments (3)
plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php (3)

609-618: Remove unused helper or add a usage

return_null_site_id() is dead code in this file. Drop it to reduce noise.

-	/**
-	 * Helper method to return null site ID for Jetpack options.
-	 *
-	 * @param mixed $value The option value.
-	 *
-	 * @return null
-	 */
-	public function return_null_site_id( $value ) {
-		return array( 'id' => null );
-	}

621-629: Docblock fixes + silence PHPMD UnusedFormalParameter on option stubs

Adjust @return types to match actual return shape and suppress PHPMD for the intentionally unused $value param.

 	/**
-	 * Helper method to return valid site ID for Jetpack options.
-	 *
-	 * @param mixed $value The option value.
-	 *
-	 * @return int
+	 * Helper method to return valid site ID for Jetpack options.
+	 *
+	 * @param mixed $value The option value.
+	 * @return array{id:int}
+	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 	 */
 	public function return_valid_site_id( $value ) {
 		return array( 'id' => 12345 );
 	}
@@
 	/**
-	 * Helper method to return valid blog token for Jetpack options.
-	 *
-	 * @param mixed $value The option value.
-	 *
-	 * @return array
+	 * Helper method to return valid blog token for Jetpack options.
+	 *
+	 * @param mixed $value The option value.
+	 * @return array{blog_token:string}
+	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 	 */
 	public function return_blog_token( $value ) {
 		return array( 'blog_token' => 'IAM.AJETPACKBLOGTOKEN' );
 	}

Also applies to: 699-706


70-80: Consider adding a happy‑path onboarding test

You cover early returns and failures well. Add one success-path test asserting that set_transact_onboarding_complete() is invoked and both caches get written when merchant/provider API calls succeed.

I can draft a test using your existing success fixtures and a partial mock of WC_Gateway_Paypal asserting the method call.

Also applies to: 106-140, 142-176

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 91cc867 and 11f862b.

📒 Files selected for processing (2)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (1 hunks)
  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{php,js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/code-quality.mdc)

**/*.{php,js,jsx,ts,tsx}: Guard against unexpected inputs
Sanitize and validate any potentially dangerous inputs
Ensure code is backwards compatible
Write code that is readable and intuitive
Ensure code has unit or E2E tests where applicable

Files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
plugins/woocommerce/tests/**/*.php

📄 CodeRabbit inference engine (.cursor/rules/woo-phpunit.mdc)

plugins/woocommerce/tests/**/*.php: Ensure test classes define public setUp() and tearDown() methods (not protected)
All PHPUnit test methods must be public, not protected
Add declare(strict_types=1); at the top of each test file
Test classes should extend WC_Unit_Test_Case

Files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
plugins/woocommerce/tests/php/**

📄 CodeRabbit inference engine (plugins/woocommerce/CLAUDE.md)

Store PHP test data and fixtures under tests/php/

Files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
**/*.{php,js,ts,jsx,tsx}

⚙️ CodeRabbit configuration file

**/*.{php,js,ts,jsx,tsx}: Don't trust that extension developers will follow the best practices, make sure the code:

  • Guards against unexpected inputs.
  • Sanitizes and validates any potentially dangerous inputs.
  • Is backwards compatible.
  • Is readable and intuitive.
  • Has unit or E2E tests where applicable.

Files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
🧠 Learnings (6)
📓 Common learnings
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php:104-113
Timestamp: 2025-09-03T17:16:04.109Z
Learning: For the PayPal WPS migration project in WooCommerce, legacy settings (marked with 'is_legacy' => true in settings-paypal.php) should not be modified as part of the migration work. Changes to legacy settings should be handled in separate PRs to maintain focused scope on the WPS migration functionality.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-webhook-handler.php:0-0
Timestamp: 2025-08-26T20:17:52.027Z
Learning: In the PayPal WPS migration, webhook signature validation is handled at the controller level (WC_REST_Paypal_Webhooks_Controller) using Jetpack's REST authentication (is_signed_with_blog_token), not within the webhook handler itself. The webhooks are processed through WordPress.com proxy infrastructure.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: In WooCommerce PayPal gateway, the transact_onboarding_complete flag is used specifically in should_use_orders_v2() to determine Orders v2 API eligibility, but it should not prevent the onboarding flow from running account creation logic. The maybe_onboard_with_transact() method should still check and create merchant/provider accounts even when this flag is set, as account creation might need to happen multiple times to ensure proper setup.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php:174-185
Timestamp: 2025-09-03T17:11:34.772Z
Learning: WooCommerce PayPal gateway onboarding via maybe_onboard_with_transact() should only run when the gateway is explicitly enabled (enabled === 'yes'), not when should_load() returns true. The should_load() method includes cases where the gateway is disabled but has existing PayPal orders, and onboarding should not occur in those scenarios since the merchant is not intending to actively use PayPal for new transactions.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/wc-update-functions.php:2753-2753
Timestamp: 2025-08-26T19:40:34.395Z
Learning: In WooCommerce PayPal gateway migration, direct instantiation with `new WC_Gateway_Paypal()` is acceptable and preferred in unit test code for better test isolation, even when production code uses the singleton pattern `WC_Gateway_Paypal::get_instance()`. Test code should maintain the ability to create fresh instances to avoid shared state between tests.
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php:177-184
Timestamp: 2025-09-03T17:40:23.781Z
Learning: In the PayPal WPS migration project for WooCommerce, Jetpack Options is expected to be present as a required dependency. Defensive checks for class_exists('Jetpack_Options') are not needed in the WC_Gateway_Paypal_Transact_Account_Manager class methods.
📚 Learning: 2025-08-26T19:40:34.395Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/wc-update-functions.php:2753-2753
Timestamp: 2025-08-26T19:40:34.395Z
Learning: In WooCommerce PayPal gateway migration, direct instantiation with `new WC_Gateway_Paypal()` is acceptable and preferred in unit test code for better test isolation, even when production code uses the singleton pattern `WC_Gateway_Paypal::get_instance()`. Test code should maintain the ability to create fresh instances to avoid shared state between tests.

Applied to files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
📚 Learning: 2025-09-11T07:18:56.828Z
Learnt from: CR
PR: woocommerce/woocommerce#0
File: plugins/woocommerce/CLAUDE.md:0-0
Timestamp: 2025-09-11T07:18:56.828Z
Learning: Applies to plugins/woocommerce/tests/php/src/Internal/Admin/Suggestions/**/*.php : Place unit tests for payment extension suggestions in tests/php/src/Internal/Admin/Suggestions/

Applied to files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
📚 Learning: 2025-09-03T17:40:23.781Z
Learnt from: annemirasol
PR: woocommerce/woocommerce#60578
File: plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php:177-184
Timestamp: 2025-09-03T17:40:23.781Z
Learning: In the PayPal WPS migration project for WooCommerce, Jetpack Options is expected to be present as a required dependency. Defensive checks for class_exists('Jetpack_Options') are not needed in the WC_Gateway_Paypal_Transact_Account_Manager class methods.

Applied to files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
📚 Learning: 2025-08-18T06:11:48.768Z
Learnt from: CR
PR: woocommerce/woocommerce#0
File: .cursor/rules/woo-phpunit.mdc:0-0
Timestamp: 2025-08-18T06:11:48.768Z
Learning: Applies to plugins/woocommerce/tests/**/*.php : Ensure test classes define public setUp() and tearDown() methods (not protected)

Applied to files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
📚 Learning: 2025-08-18T06:11:48.768Z
Learnt from: CR
PR: woocommerce/woocommerce#0
File: .cursor/rules/woo-phpunit.mdc:0-0
Timestamp: 2025-08-18T06:11:48.768Z
Learning: Applies to plugins/woocommerce/tests/**/*.php : Test classes should extend WC_Unit_Test_Case

Applied to files:

  • plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php
🧬 Code graph analysis (1)
plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php (2)
plugins/woocommerce/includes/gateways/paypal/class-wc-gateway-paypal.php (1)
  • WC_Gateway_Paypal (32-807)
plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-transact-account-manager.php (3)
  • WC_Gateway_Paypal_Transact_Account_Manager (19-364)
  • do_onboarding (72-129)
  • get_transact_account_data (138-156)
🪛 PHPMD (2.15.0)
plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php

616-616: Avoid unused parameters such as '$value'. (undefined)

(UnusedFormalParameter)


627-627: Avoid unused parameters such as '$value'. (undefined)

(UnusedFormalParameter)


704-704: Avoid unused parameters such as '$value'. (undefined)

(UnusedFormalParameter)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (24)
  • GitHub Check: Blocks e2e tests 2/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 10/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 9/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 7/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 8/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 4/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 1/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Metrics - @woocommerce/plugin-woocommerce [performance]
  • GitHub Check: Blocks e2e tests 6/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 5/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 3/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 5/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 6/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core API tests - @woocommerce/plugin-woocommerce [api]
  • GitHub Check: Core e2e tests 4/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 3/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.3] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Core e2e tests 2/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.3] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Core e2e tests 1/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Lint - @woocommerce/plugin-woocommerce
  • GitHub Check: build
🔇 Additional comments (1)
plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-transact-manager-account-test.php (1)

40-54: Good PHPUnit scaffolding

declare(strict_types=1); present; class extends WC_Unit_Test_Case; setUp()/tearDown() are public; cleans options. LGTM.

Also applies to: 711-719

@malithsen malithsen left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This tests well. In case anyone else runs into it, I had to disable Jetpack token verification on my local setup to get this working end-to-end due to a mismatch of $_SERVER['HTTP_HOST'] and the URL exposed via ngork.

✅ I see the registration requests hitting my sandbox as expected when updating settings.
✅ After placing an order, I see an event in the webhook logs in my sandbox.
✅ Sandbox receives the webhook request and proxies it to the correct merchant URL.
✅ Merchant site processes the webhook from the sandbox to updates the correct order.

Major kudos to @Mayisha for helping me debug various setup issues I encountered while testing this.

@Mayisha
Mayisha enabled auto-merge (squash) September 19, 2025 14:23
@Mayisha
Mayisha merged commit 7d9e72a into trunk Sep 19, 2025
@Mayisha
Mayisha deleted the feature/paypal-wps-migration branch September 19, 2025 14:33
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ API Documentation Reminder

Hi @annemirasol! Your PR contains REST API changes. Please consider updating the REST API documentation if your changes affect the public API.

Changed API files:

plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-webhooks-controller.php
plugins/woocommerce/includes/rest-api/Server.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

plugin: woocommerce Issues related to the WooCommerce Core plugin.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants