Commit 19dba95f060 for woocommerce
commit 19dba95f060e6b6b2f31286e1bcaed23fbbdeb36
Author: Luigi Teschio <gigitux@gmail.com>
Date: Mon Nov 23 21:30:59 2026 +0100
Preserve the priced delivery address in PayPal checkout (#71258)
Forward-port the corresponding WooCommerce 11.3.1 fix to trunk.
diff --git a/plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php b/plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php
index 16061e861ab..d4485d6afe5 100644
--- a/plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php
+++ b/plugins/woocommerce/includes/gateways/paypal/includes/settings-paypal.php
@@ -80,6 +80,7 @@ $settings = array(
'desc_tip' => true,
),
'send_shipping' => array(
+ 'is_legacy' => true,
'title' => __( 'Shipping details', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Send shipping details to PayPal instead of billing.', 'woocommerce' ),
diff --git a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller.php b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller.php
index d0001afb032..0c92e90a1be 100644
--- a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller.php
+++ b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller.php
@@ -167,12 +167,28 @@ class WC_REST_Paypal_Standard_Controller extends WC_REST_Controller {
return new WP_REST_Response( $response, 422 );
}
+ $address_context = $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_CONTEXT, true );
+ if ( 'shipping' !== ( $address_context['address_source'] ?? '' ) ) {
+ WC_Gateway_Paypal::log(
+ 'PayPal order was not created from the shipping address, cannot update shipping. Order ID: ' . $order->get_id()
+ );
+ return new WP_REST_Response( $this->get_update_shipping_error_response(), 422 );
+ }
+ if ( PayPalConstants::SHIPPING_GET_FROM_FILE !== ( $address_context['shipping_preference'] ?? '' ) ) {
+ WC_Gateway_Paypal::log(
+ 'PayPal order does not allow shipping address changes, cannot update shipping. Order ID: ' . $order->get_id() .
+ '. Shipping preference: ' . ( $address_context['shipping_preference'] ?? '' )
+ );
+ return new WP_REST_Response( $this->get_update_shipping_error_response(), 422 );
+ }
+
if ( ! WC()->session ) {
WC()->session = new WC_Session_Handler();
}
WC()->session->init();
// Update the shipping address before we do anything else.
+ $previous_shipping_address = $order->get_address( 'shipping' );
$this->update_order_shipping_address( $order, $shipping_address );
$re_add_cart_item_fees = static function ( $cart ) use ( $order ) {
@@ -194,6 +210,7 @@ class WC_REST_Paypal_Standard_Controller extends WC_REST_Controller {
};
add_action( 'woocommerce_cart_calculate_fees', $re_add_cart_item_fees );
+ $address_priced = false;
try {
// We need to rebuild the cart from the order, as we do not have session cart data
// for REST API requests.
@@ -235,6 +252,18 @@ class WC_REST_Paypal_Standard_Controller extends WC_REST_Controller {
$paypal_request = new PayPalRequest( WC_Gateway_Paypal::get_instance() );
$updated_amount = $paypal_request->get_paypal_order_purchase_unit_amount( $order );
+ $address_context['shipping_address'] = $order->get_address( 'shipping' );
+ $address_context['expected_address'] = array(
+ 'country_code' => $order->get_shipping_country(),
+ 'admin_area_1' => $order->get_shipping_state(),
+ 'admin_area_2' => $order->get_shipping_city(),
+ 'postal_code' => $order->get_shipping_postcode(),
+ );
+ $address_context['callback_amount'] = $updated_amount;
+ $order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_CONTEXT, $address_context );
+ $order->save();
+ $address_priced = true;
+
$response = array(
'id' => $paypal_order_id,
'purchase_units' => array(
@@ -249,6 +278,11 @@ class WC_REST_Paypal_Standard_Controller extends WC_REST_Controller {
return new WP_REST_Response( $response, 200 );
} finally {
remove_action( 'woocommerce_cart_calculate_fees', $re_add_cart_item_fees );
+ // A failed callback must not leave an address PayPal never priced on the order.
+ if ( ! $address_priced ) {
+ $order->set_shipping_address( $previous_shipping_address );
+ $order->save();
+ }
}
}
@@ -418,8 +452,14 @@ class WC_REST_Paypal_Standard_Controller extends WC_REST_Controller {
$order->save();
// Get customer from order and update their shipping location.
- $customer = new WC_Customer();
- $customer->set_location( $country, $state, $postcode, $city );
+ $customer = new WC_Customer();
+ $has_billing_country = (bool) $order->get_billing_country();
+ $customer->set_location(
+ $has_billing_country ? $order->get_billing_country() : $country,
+ $has_billing_country ? $order->get_billing_state() : $state,
+ $has_billing_country ? $order->get_billing_postcode() : $postcode,
+ $has_billing_country ? $order->get_billing_city() : $city
+ );
$customer->set_shipping_location( $country, $state, $postcode, $city );
$customer->set_calculated_shipping( true );
WC()->customer = $customer;
diff --git a/plugins/woocommerce/src/Gateways/PayPal/Constants.php b/plugins/woocommerce/src/Gateways/PayPal/Constants.php
index f2c2fa6d1d6..ca438a965af 100644
--- a/plugins/woocommerce/src/Gateways/PayPal/Constants.php
+++ b/plugins/woocommerce/src/Gateways/PayPal/Constants.php
@@ -432,4 +432,28 @@ class Constants {
* @since 10.5.0
*/
public const PAYPAL_ORDER_META_SHIPPING_CALLBACK_TOKEN = '_paypal_shipping_callback_token';
+
+ /**
+ * Address policy and priced destination for the current PayPal attempt.
+ *
+ * @since 11.4.0
+ * @var string
+ */
+ public const PAYPAL_ORDER_META_ADDRESS_CONTEXT = '_paypal_address_context';
+
+ /**
+ * Whether the PayPal destination requires merchant review.
+ *
+ * @since 11.4.0
+ * @var string
+ */
+ public const PAYPAL_ORDER_META_ADDRESS_REVIEW = '_paypal_address_review';
+
+ /**
+ * Whether an automatic capture hold awaits address confirmation.
+ *
+ * @since 11.4.0
+ * @var string
+ */
+ public const PAYPAL_ORDER_META_CAPTURE_AWAITING_ADDRESS = '_paypal_capture_awaiting_address';
}
diff --git a/plugins/woocommerce/src/Gateways/PayPal/Helper.php b/plugins/woocommerce/src/Gateways/PayPal/Helper.php
index 92d1adc3c55..f2ea2753a2b 100644
--- a/plugins/woocommerce/src/Gateways/PayPal/Helper.php
+++ b/plugins/woocommerce/src/Gateways/PayPal/Helper.php
@@ -5,6 +5,7 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\Gateways\PayPal;
use WC_Order;
+use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\Gateways\PayPal\Constants as PayPalConstants;
defined( 'ABSPATH' ) || exit;
@@ -174,32 +175,43 @@ class Helper {
return;
}
- // Bail early if '_paypal_addresses_updated' is 'yes', meaning the addresses update already have been successful.
- if ( 'yes' === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESSES_UPDATED, true ) ) {
+ $confirmed = 'yes' === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESSES_UPDATED, true );
+ if ( ! self::validate_shipping_address( $order, $paypal_order_details, $confirmed ) ) {
return;
}
- // Update the shipping information.
- $full_name = $paypal_order_details['purchase_units'][0]['shipping']['name']['full_name'] ?? '';
- if ( ! empty( $full_name ) ) {
- $name_parts = explode( ' ', $full_name, 2 );
- $approximate_first_name = $name_parts[0] ?? '';
- $approximate_last_name = isset( $name_parts[1] ) ? $name_parts[1] : '';
- $order->set_shipping_first_name( $approximate_first_name );
- $order->set_shipping_last_name( $approximate_last_name );
+ // Bail early if '_paypal_addresses_updated' is 'yes', meaning the addresses update already have been successful.
+ if ( $confirmed ) {
+ return;
}
- $shipping_address = $paypal_order_details['purchase_units'][0]['shipping']['address'] ?? array();
- if ( ! empty( $shipping_address ) ) {
- $order->set_shipping_country( $shipping_address['country_code'] ?? '' );
- $order->set_shipping_postcode( $shipping_address['postal_code'] ?? '' );
- $order->set_shipping_state( $shipping_address['admin_area_1'] ?? '' );
- $order->set_shipping_city( $shipping_address['admin_area_2'] ?? '' );
- $order->set_shipping_address_1( $shipping_address['address_line_1'] ?? '' );
- $order->set_shipping_address_2( $shipping_address['address_line_2'] ?? '' );
+ $context = $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_CONTEXT, true );
+ if ( ! empty( $context['callback_amount'] ) ) {
+ $full_name = $paypal_order_details['purchase_units'][0]['shipping']['name']['full_name'] ?? '';
+ if ( ! empty( $full_name ) ) {
+ $name_parts = explode( ' ', $full_name, 2 );
+ $approximate_first_name = $name_parts[0] ?? '';
+ $approximate_last_name = isset( $name_parts[1] ) ? $name_parts[1] : '';
+ $order->set_shipping_first_name( $approximate_first_name );
+ $order->set_shipping_last_name( $approximate_last_name );
+ }
+
+ $shipping_address = $paypal_order_details['purchase_units'][0]['shipping']['address'] ?? array();
+ if ( ! empty( $shipping_address ) ) {
+ $order->set_shipping_country( $shipping_address['country_code'] ?? '' );
+ $order->set_shipping_postcode( $shipping_address['postal_code'] ?? '' );
+ $order->set_shipping_state( $shipping_address['admin_area_1'] ?? '' );
+ $order->set_shipping_city( $shipping_address['admin_area_2'] ?? '' );
+ $order->set_shipping_address_1( $shipping_address['address_line_1'] ?? '' );
+ $order->set_shipping_address_2( $shipping_address['address_line_2'] ?? '' );
+ }
+
+ $context['expected_address'] = $shipping_address;
+ $context['shipping_address'] = $order->get_address( 'shipping' );
+ $order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_CONTEXT, $context );
}
- // Update the billing information.
+ // Update contact details, preserving the billing location used to calculate taxes.
$full_name = $paypal_order_details['payer']['name'] ?? array();
$email = $paypal_order_details['payer']['email_address'] ?? '';
if ( ! empty( $full_name ) ) {
@@ -208,8 +220,9 @@ class Helper {
$order->set_billing_email( $email );
}
+ // Orders created without a billing location, such as from product page buttons, take it from the payer.
$billing_address = $paypal_order_details['payer']['address'] ?? array();
- if ( ! empty( $billing_address ) ) {
+ if ( ! empty( $billing_address ) && ! $order->get_billing_country() ) {
$order->set_billing_country( $billing_address['country_code'] ?? '' );
$order->set_billing_postcode( $billing_address['postal_code'] ?? '' );
$order->set_billing_state( $billing_address['admin_area_1'] ?? '' );
@@ -220,5 +233,129 @@ class Helper {
$order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_ADDRESSES_UPDATED, 'yes' );
$order->save();
+ self::complete_order_after_address_confirmation( $order );
+ }
+
+ /**
+ * Mark a captured order paid after its approved address is saved.
+ *
+ * @param WC_Order $order The order object.
+ * @return void
+ */
+ private static function complete_order_after_address_confirmation( WC_Order $order ): void {
+ if ( 'yes' === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_CAPTURE_AWAITING_ADDRESS, true )
+ && PayPalConstants::STATUS_COMPLETED === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_STATUS, true )
+ && $order->get_transaction_id()
+ && $order->has_status( OrderStatus::ON_HOLD ) ) {
+ $order->delete_meta_data( PayPalConstants::PAYPAL_ORDER_META_CAPTURE_AWAITING_ADDRESS );
+ $order->save();
+ $order->payment_complete( $order->get_transaction_id() );
+ }
+ }
+
+ /**
+ * Check the final destination against the address used to price this attempt.
+ *
+ * @param WC_Order $order The order object.
+ * @param array $details The PayPal order details.
+ * @param bool $confirmed Whether an earlier approval already confirmed this attempt's addresses.
+ * @return bool Whether the destination is safe to use.
+ */
+ private static function validate_shipping_address( WC_Order $order, array $details, bool $confirmed = false ): bool {
+ if ( 'yes' === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW, true ) ) {
+ return false;
+ }
+
+ $context = $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_CONTEXT, true );
+ if ( PayPalConstants::SHIPPING_NO_SHIPPING === ( $context['shipping_preference'] ?? '' ) ) {
+ return true;
+ }
+ if ( ! $context && ( $confirmed || ! $order->needs_shipping() ) ) {
+ return true;
+ }
+
+ $address = $details['purchase_units'][0]['shipping']['address'] ?? array();
+ $fields = array(
+ 'country_code' => 'country',
+ 'admin_area_1' => 'state',
+ 'admin_area_2' => 'city',
+ 'postal_code' => 'postcode',
+ 'address_line_1' => 'address_1',
+ 'address_line_2' => 'address_2',
+ );
+
+ // Legacy attempts have no reliable settings snapshot. Only an unchanged destination is safe.
+ $expected_address = $context['expected_address'] ?? array();
+ $priced_address = $context['shipping_address'] ?? $order->get_address( 'shipping' );
+ $address_valid = ! empty( $address );
+ foreach ( $fields as $provider_field => $order_field ) {
+ $expected = $priced_address[ $order_field ] ?? '';
+ if ( $context && 'billing' !== ( $context['address_source'] ?? '' ) ) {
+ $expected = $expected_address[ $provider_field ] ?? '';
+ }
+ // Callbacks supply only the pricing location. Street details arrive with approval.
+ if ( ! empty( $context['callback_amount'] ) && ! array_key_exists( $provider_field, $expected_address ) ) {
+ continue;
+ }
+ $address_valid = $address_valid && self::normalize_address_field( $address[ $provider_field ] ?? '' ) === self::normalize_address_field( $expected );
+ // Once confirmed, order edits are the merchant's. Only a different PayPal destination needs review.
+ if ( ! $confirmed ) {
+ $address_valid = $address_valid && self::normalize_address_field( $order->{"get_shipping_{$order_field}"}() ) === self::normalize_address_field( $priced_address[ $order_field ] ?? '' );
+ }
+ }
+
+ $currency_valid = true;
+ $amount_valid = true;
+ if ( ! empty( $context['callback_amount'] ) ) {
+ $amount = $details['purchase_units'][0]['amount'] ?? array();
+ $currency_valid = ( $amount['currency_code'] ?? '' ) === $context['callback_amount']['currency_code'];
+ $amount_valid = isset( $amount['value'] ) && is_string( $amount['value'] ) && wc_format_decimal( $amount['value'], wc_get_price_decimals() ) === $context['callback_amount']['value'];
+ $amount_valid = $amount_valid && ( $confirmed || wc_format_decimal( $order->get_total(), wc_get_price_decimals() ) === $context['callback_amount']['value'] );
+ }
+
+ if ( $address_valid && $currency_valid && $amount_valid ) {
+ return true;
+ }
+
+ $differences = array();
+ if ( ! $address_valid ) {
+ $differences[] = __( 'shipping address', 'woocommerce' );
+ }
+ if ( ! $currency_valid ) {
+ $differences[] = __( 'payment currency', 'woocommerce' );
+ }
+ if ( ! $amount_valid ) {
+ $differences[] = __( 'payment amount', 'woocommerce' );
+ }
+ $note = sprintf(
+ /* translators: %s: comma-separated list of mismatched checkout details. */
+ __( 'PayPal checkout details differ from this order: %s. Review the payment and delivery address before fulfilling.', 'woocommerce' ),
+ implode( ', ', $differences )
+ );
+ if ( PayPalConstants::STATUS_COMPLETED === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_STATUS, true ) ) {
+ $note .= ' ' . __( 'PayPal reported this payment as captured. This hold does not issue a refund; verify the payment in PayPal.', 'woocommerce' );
+ } else {
+ $note .= ' ' . __( 'WooCommerce will skip automatic capture while this order needs review. Verify the payment status in PayPal before fulfilling.', 'woocommerce' );
+ }
+ $order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW, 'yes' );
+ $order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_SHIPPING_CALLBACK_TOKEN, '' );
+ if ( $order->has_status( OrderStatus::ON_HOLD ) ) {
+ $order->add_order_note( $note );
+ } else {
+ $order->update_status( OrderStatus::ON_HOLD, $note );
+ }
+ $order->save();
+
+ return false;
+ }
+
+ /**
+ * Normalize harmless case and surrounding whitespace differences in addresses.
+ *
+ * @param mixed $value Address field.
+ * @return string Normalized value.
+ */
+ private static function normalize_address_field( $value ): string {
+ return is_string( $value ) ? strtoupper( trim( $value ) ) : '';
}
}
diff --git a/plugins/woocommerce/src/Gateways/PayPal/Request.php b/plugins/woocommerce/src/Gateways/PayPal/Request.php
index 07c81ddb3bf..ea3efcebdc4 100644
--- a/plugins/woocommerce/src/Gateways/PayPal/Request.php
+++ b/plugins/woocommerce/src/Gateways/PayPal/Request.php
@@ -225,6 +225,11 @@ class Request {
return;
}
+ if ( 'yes' === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW, true ) ) {
+ \WC_Gateway_Paypal::log( 'PayPal delivery address needs review. Cannot ' . $action . ' payment. Order ID: ' . $order->get_id() );
+ return;
+ }
+
$paypal_debug_id = null;
$paypal_order_id = $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ORDER_ID );
if ( ! $paypal_order_id ) {
@@ -355,6 +360,13 @@ class Request {
return;
}
+ // Skip if the delivery address needs review. Merchants move these orders by hand, so leave a note.
+ if ( 'yes' === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW, true ) ) {
+ \WC_Gateway_Paypal::log( 'PayPal delivery address needs review. Skipping capture. Order ID: ' . $order->get_id() );
+ $order->add_order_note( __( 'PayPal payment was not captured because the delivery address needs review. Verify the payment in PayPal before fulfilling this order.', 'woocommerce' ) );
+ return;
+ }
+
$authorization_id = $this->get_authorization_id_for_capture( $order );
if ( ! $authorization_id ) {
\WC_Gateway_Paypal::log( 'Authorization ID not found to capture authorized payment. Order ID: ' . $order->get_id() );
@@ -794,6 +806,19 @@ class Request {
throw new Exception( 'Shipping address is required for PayPal create-order request. Order ID: ' . esc_html( (string) $order->get_id() ) );
}
+ $order->update_meta_data(
+ PayPalConstants::PAYPAL_ORDER_META_ADDRESS_CONTEXT,
+ array(
+ 'address_source' => 'shipping',
+ 'shipping_preference' => $shipping_preference,
+ 'shipping_address' => $order->get_address( 'shipping' ),
+ 'expected_address' => $shipping['address'] ?? array(),
+ )
+ );
+ $order->delete_meta_data( PayPalConstants::PAYPAL_ORDER_META_ADDRESSES_UPDATED );
+ $order->delete_meta_data( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW );
+ $order->delete_meta_data( PayPalConstants::PAYPAL_ORDER_META_CAPTURE_AWAITING_ADDRESS );
+
return $params;
}
@@ -972,7 +997,7 @@ class Request {
return null;
}
- $address_type = 'yes' === $this->gateway->get_option( 'send_shipping' ) ? 'shipping' : 'billing';
+ $address_type = 'shipping';
$full_name = trim( $order->{"get_formatted_{$address_type}_full_name"}() );
$address_line_1 = trim( $order->{"get_{$address_type}_address_1"}() );
diff --git a/plugins/woocommerce/src/Gateways/PayPal/WebhookHandler.php b/plugins/woocommerce/src/Gateways/PayPal/WebhookHandler.php
index 14c50fe39d3..b042a2d87c2 100644
--- a/plugins/woocommerce/src/Gateways/PayPal/WebhookHandler.php
+++ b/plugins/woocommerce/src/Gateways/PayPal/WebhookHandler.php
@@ -74,14 +74,26 @@ class WebhookHandler {
return;
}
+ $paypal_order_id = $event['resource']['id'] ?? null;
+ $current_paypal_order_id = $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ORDER_ID, true );
+ if ( $current_paypal_order_id && $paypal_order_id !== $current_paypal_order_id ) {
+ \WC_Gateway_Paypal::log( 'Ignoring approval for a replaced PayPal attempt. Order ID: ' . $order->get_id() );
+ return;
+ }
+
// Skip if the payment is already processed.
$paypal_status = $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_STATUS, true );
- if ( in_array( $paypal_status, array( PayPalConstants::STATUS_COMPLETED, PayPalConstants::STATUS_APPROVED ), true ) ) {
+ if ( PayPalConstants::STATUS_COMPLETED === $paypal_status ) {
+ if ( PayPalConstants::STATUS_APPROVED === ( $event['resource']['status'] ?? null ) ) {
+ PayPalHelper::update_addresses_in_order( $order, $event['resource'] );
+ }
+ return;
+ }
+ if ( PayPalConstants::STATUS_APPROVED === $paypal_status ) {
return;
}
- $status = $event['resource']['status'] ?? null;
- $paypal_order_id = $event['resource']['id'] ?? null;
+ $status = $event['resource']['status'] ?? null;
if ( PayPalConstants::STATUS_APPROVED === $status ) {
\WC_Gateway_Paypal::log( 'PayPal payment approved. Order ID: ' . $order->get_id() );
$order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_STATUS, $status );
@@ -99,6 +111,9 @@ class WebhookHandler {
// Update the addresses in the order with the addresses from the PayPal order details.
PayPalHelper::update_addresses_in_order( $order, $event['resource'] );
+ if ( 'yes' === $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW, true ) ) {
+ return;
+ }
// Authorize or capture the payment after approval.
$paypal_intent = $event['resource']['intent'] ?? null;
@@ -150,7 +165,16 @@ class WebhookHandler {
$order->set_transaction_id( $transaction_id );
$order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_CAPTURE_ID, $transaction_id );
$order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_STATUS, $status );
- $order->payment_complete();
+ $order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_SHIPPING_CALLBACK_TOKEN, '' );
+ if ( 'yes' !== $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW, true ) ) {
+ $requires_address_confirmation = $order->needs_shipping() && 'yes' !== $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESSES_UPDATED, true );
+ if ( ! $requires_address_confirmation ) {
+ $order->payment_complete();
+ } elseif ( $order->has_status( array( OrderStatus::PENDING, OrderStatus::CHECKOUT_DRAFT, OrderStatus::FAILED ) ) ) {
+ $order->update_meta_data( PayPalConstants::PAYPAL_ORDER_META_CAPTURE_AWAITING_ADDRESS, 'yes' );
+ $order->update_status( OrderStatus::ON_HOLD, __( 'PayPal captured the payment. Waiting for delivery address confirmation before fulfilling the order.', 'woocommerce' ) );
+ }
+ }
$order->add_order_note(
sprintf(
/* translators: %1$s: Transaction ID */
diff --git a/plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-test.php b/plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-test.php
index 205184da187..f7a484cf614 100644
--- a/plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-test.php
+++ b/plugins/woocommerce/tests/php/includes/gateways/paypal/class-wc-gateway-paypal-test.php
@@ -188,8 +188,9 @@ class WC_Gateway_Paypal_Test extends \WC_Unit_Test_Case {
$form_fields = $mock_gateway->get_form_fields();
- // Verify that the number of fields are correct.
- $this->assertEquals( count( $form_fields ), 12 );
+ // Orders v2 always sends shipping details, but merchants can still lock the address.
+ $this->assertArrayNotHasKey( 'send_shipping', $form_fields );
+ $this->assertArrayHasKey( 'address_override', $form_fields );
// When Orders v2 is enabled, paypal_buttons field should be present.
$this->assertArrayHasKey( 'paypal_buttons', $form_fields );
diff --git a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller-test.php b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller-test.php
index 253975fa8f3..d61c6418161 100644
--- a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller-test.php
+++ b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-paypal-standard-controller-test.php
@@ -516,6 +516,14 @@ class WC_REST_Paypal_Standard_Controller_Test extends WC_REST_Unit_Test_Case {
* @param string $shipping_cost The shipping cost of the order.
*/
private function finalize_paypal_order( WC_Order $order, string $shipping_rate_id, string $paypal_order_id, string $shipping_cost = '10' ): void {
+ // Callbacks only update attempts created from the shipping address with an editable preference.
+ $order->update_meta_data(
+ '_paypal_address_context',
+ array(
+ 'address_source' => 'shipping',
+ 'shipping_preference' => 'GET_FROM_FILE',
+ )
+ );
$order->set_shipping_country( 'US' );
$order->set_shipping_state( 'CA' );
$order->set_shipping_postcode( '90210' );
diff --git a/plugins/woocommerce/tests/php/src/Gateways/PayPal/AddressIntegrityTest.php b/plugins/woocommerce/tests/php/src/Gateways/PayPal/AddressIntegrityTest.php
new file mode 100644
index 00000000000..ba8f7756a03
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Gateways/PayPal/AddressIntegrityTest.php
@@ -0,0 +1,871 @@
+<?php
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Gateways\PayPal;
+
+use Automattic\WooCommerce\Gateways\PayPal\Constants;
+use Automattic\WooCommerce\Gateways\PayPal\Helper;
+use Automattic\WooCommerce\Gateways\PayPal\Request;
+use Automattic\WooCommerce\Gateways\PayPal\WebhookHandler;
+
+/**
+ * Tests that PayPal address echoes cannot replace a priced destination.
+ */
+class AddressIntegrityTest extends \WC_Unit_Test_Case {
+ /**
+ * Last mocked provider order payload.
+ *
+ * @var array
+ */
+ private $payload = array();
+
+ /**
+ * Provider details returned to the thank-you fallback.
+ *
+ * @var array
+ */
+ private $details = array();
+
+ /**
+ * Number of capture requests.
+ *
+ * @var int
+ */
+ private $captures = 0;
+
+ /**
+ * ID returned by the mocked provider for a new order.
+ *
+ * @var string
+ */
+ private $provider_order_id = 'TEST-PAYPAL-ORDER';
+
+ /**
+ * Payment gateway registry restored after each test.
+ *
+ * @var array
+ */
+ private $gateways;
+
+ /**
+ * Customer singleton restored after each test.
+ *
+ * @var \WC_Customer|null
+ */
+ private $original_customer;
+
+ /**
+ * Session singleton replaced while rebuilding the callback cart.
+ *
+ * @var \WC_Session|null
+ */
+ private $original_session;
+
+ /**
+ * Set up mocked provider requests.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->gateways = WC()->payment_gateways()->payment_gateways;
+ $this->original_customer = WC()->customer;
+ $this->original_session = WC()->session;
+ add_filter(
+ 'pre_option_jetpack_options',
+ static function () {
+ return array( 'id' => 12345 );
+ }
+ );
+ add_filter(
+ 'pre_option_jetpack_private_options',
+ static function () {
+ return array( 'blog_token' => 'TEST.TOKEN' );
+ }
+ );
+ add_filter( 'pre_http_request', array( $this, 'mock_provider' ), 10, 3 );
+ }
+
+ /**
+ * Restore the process-wide gateway, customer and session state.
+ */
+ public function tearDown(): void {
+ try {
+ parent::tearDown();
+ } finally {
+ WC()->payment_gateways()->payment_gateways = $this->gateways;
+ WC()->customer = $this->original_customer;
+ WC()->session = $this->original_session;
+ }
+ }
+
+ /**
+ * Return local provider fixtures for every HTTP request.
+ *
+ * @param mixed $preempt Previous response.
+ * @param array $args Request arguments.
+ * @param string $url Request URL.
+ * @return array Mock response.
+ */
+ public function mock_provider( $preempt, array $args, string $url ): array {
+ unset( $preempt );
+ if ( false !== strpos( $url, 'payment/capture' ) || false !== strpos( $url, 'payment/authorize' ) ) {
+ ++$this->captures;
+ }
+ if ( 'GET' === $args['method'] ) {
+ return array(
+ 'response' => array( 'code' => 200 ),
+ 'body' => wp_json_encode( $this->details ),
+ );
+ }
+ $body = json_decode( $args['body'] ?? '{}', true );
+ if ( isset( $body['order'] ) ) {
+ $this->payload = $body['order'];
+ }
+ return array(
+ 'response' => array( 'code' => 201 ),
+ 'body' => wp_json_encode(
+ array(
+ 'id' => $this->provider_order_id,
+ 'status' => 'CREATED',
+ 'links' => array(
+ array(
+ 'rel' => 'approve',
+ 'method' => 'GET',
+ 'href' => 'https://example.com/approve',
+ ),
+ ),
+ )
+ ),
+ );
+ }
+
+ /**
+ * Create a physical order with different billing and shipping addresses.
+ *
+ * @param string $send_shipping Whether shipping is sent.
+ * @param string $override Whether the merchant locks the address.
+ * @return \WC_Order Order with a newly created payment attempt.
+ */
+ private function create_attempt( string $send_shipping = 'yes', string $override = 'no' ): \WC_Order {
+ update_option(
+ 'woocommerce_paypal_settings',
+ array(
+ 'send_shipping' => $send_shipping,
+ 'address_override' => $override,
+ )
+ );
+ $order = \WC_Helper_Order::create_order();
+ $order->set_payment_method( 'paypal' );
+ $order->set_status( 'pending' );
+ $order->set_shipping_address_1( '10 Delivery Street' );
+ $order->set_shipping_city( 'Los Angeles' );
+ $order->set_shipping_state( 'CA' );
+ $order->set_shipping_postcode( '90210' );
+ $order->set_shipping_country( 'US' );
+ $order->set_billing_address_1( '20 Billing Street' );
+ $order->set_billing_city( 'New York' );
+ $order->set_billing_state( 'NY' );
+ $order->set_billing_postcode( '10001' );
+ $order->set_billing_country( 'US' );
+ $order->save();
+ $gateway = new \WC_Gateway_Paypal();
+ WC()->payment_gateways()->payment_gateways['paypal'] = $gateway;
+ $this->assertNotNull( ( new Request( $gateway ) )->create_paypal_order( $order ) );
+ return $order;
+ }
+
+ /**
+ * Build approval details from the outbound order.
+ *
+ * @return array Provider order details.
+ */
+ private function approval(): array {
+ return array_merge(
+ $this->payload,
+ array(
+ 'id' => $this->provider_order_id,
+ 'status' => Constants::STATUS_APPROVED,
+ 'links' => array(
+ array(
+ 'rel' => 'capture',
+ 'method' => 'POST',
+ 'href' => 'https://example.com/capture',
+ ),
+ ),
+ )
+ );
+ }
+
+ /**
+ * @testdox Preserves distinct priced addresses despite later setting changes.
+ * @testWith ["no", "no", true]
+ * ["no", "yes", false]
+ * ["yes", "yes", false]
+ * ["yes", "no", true]
+ * @param string $send_shipping Shipping setting.
+ * @param string $override Address lock setting.
+ * @param bool $callback Whether the attempt permits shipping callbacks.
+ */
+ public function test_attempt_policy_survives_setting_changes( string $send_shipping, string $override, bool $callback ): void {
+ $order = $this->create_attempt( $send_shipping, $override );
+ $shipping = $order->get_address( 'shipping' );
+ $billing = $order->get_address( 'billing' );
+ $total = $order->get_total();
+ $context = $this->payload['payment_source']['paypal']['experience_context'];
+ $this->assertSame( $callback, isset( $context['order_update_callback_config'] ) );
+ $this->assertSame( '10 Delivery Street', $this->payload['purchase_units'][0]['shipping']['address']['address_line_1'] );
+ update_option(
+ 'woocommerce_paypal_settings',
+ array(
+ 'send_shipping' => 'yes' === $send_shipping ? 'no' : 'yes',
+ 'address_override' => 'yes' === $override ? 'no' : 'yes',
+ )
+ );
+ $details = $this->approval();
+ $details['payer']['address'] = array(
+ 'country_code' => 'GB',
+ 'postal_code' => 'SW1A 1AA',
+ );
+
+ Helper::update_addresses_in_order( $order, $details );
+ Helper::update_addresses_in_order( $order, $details );
+
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( $billing, $order->get_address( 'billing' ) );
+ $this->assertSame( $total, $order->get_total() );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ }
+
+ /**
+ * @testdox Rejects an unpriced destination before capture, including after the return fallback ran.
+ * @testWith [false]
+ * [true]
+ * @param bool $return_first Whether the return fallback runs first.
+ */
+ public function test_unpriced_approval_stops_capture( bool $return_first ): void {
+ $order = $this->create_attempt();
+ $shipping = $order->get_address( 'shipping' );
+ $details = $this->approval();
+ if ( $return_first ) {
+ Helper::update_addresses_in_order( $order, $details );
+ }
+ $details['purchase_units'][0]['shipping']['address']['postal_code'] = '10001';
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $details );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( 'on-hold', $order->get_status() );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ $this->assertSame( 0, $this->captures );
+ $notes = implode( ' ', wp_list_pluck( wc_get_order_notes( array( 'order_id' => $order->get_id() ) ), 'content' ) );
+ $this->assertStringContainsString( 'shipping address', $notes );
+ $this->assertStringContainsString( 'skip automatic capture', $notes );
+ $request = new Request( new \WC_Gateway_Paypal() );
+ $request->authorize_or_capture_payment( $order, 'https://example.com/capture' );
+ $request->capture_authorized_payment( $order );
+ $this->assertSame( 0, $this->captures );
+ }
+
+ /**
+ * Send a local webhook fixture.
+ *
+ * @param string $type Event type.
+ * @param array $event_resource Provider resource.
+ */
+ private function send_webhook( string $type, array $event_resource ): void {
+ $request = new \WP_REST_Request( 'POST' );
+ $request->set_header( 'content-type', 'application/json' );
+ $request->set_body(
+ wp_json_encode(
+ array(
+ 'event_type' => $type,
+ 'resource' => $event_resource,
+ )
+ )
+ );
+ ( new WebhookHandler() )->process_webhook( $request );
+ }
+
+ /**
+ * @testdox Keeps a captured mismatched payment on hold without changing totals or claiming a refund.
+ */
+ public function test_capture_notification_preserves_review(): void {
+ $order = $this->create_attempt();
+ $total = $order->get_total();
+ $details = $this->approval();
+ $details['purchase_units'][0]['shipping']['address']['country_code'] = 'GB';
+ Helper::update_addresses_in_order( $order, $details );
+ $this->send_webhook(
+ 'PAYMENT.CAPTURE.COMPLETED',
+ array(
+ 'id' => 'TEST-CAPTURE',
+ 'status' => 'COMPLETED',
+ 'custom_id' => $this->payload['purchase_units'][0]['custom_id'],
+ )
+ );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'on-hold', $order->get_status() );
+ $this->assertSame( 'TEST-CAPTURE', $order->get_transaction_id() );
+ $this->assertSame( 'COMPLETED', $order->get_meta( Constants::PAYPAL_ORDER_META_STATUS ) );
+ $this->assertSame( $total, $order->get_total() );
+ $this->assertEquals( 0, $order->get_total_refunded() );
+ }
+
+ /**
+ * @testdox Notes a skipped capture when a merchant processes an uncaptured order held for address review.
+ * @testWith [false]
+ * [true]
+ * @param bool $captured Whether PayPal captured the payment before the hold.
+ */
+ public function test_processing_held_order_notes_skipped_capture( bool $captured ): void {
+ $order = $this->create_attempt();
+ $gateway = $this->getMockBuilder( \WC_Gateway_Paypal::class )->onlyMethods( array( 'should_use_orders_v2' ) )->getMock();
+ $gateway->method( 'should_use_orders_v2' )->willReturn( true );
+ WC()->payment_gateways()->payment_gateways['paypal'] = $gateway;
+ $details = $this->approval();
+ $details['purchase_units'][0]['shipping']['address']['postal_code'] = '10001';
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $details );
+ if ( $captured ) {
+ $this->send_webhook(
+ 'PAYMENT.CAPTURE.COMPLETED',
+ array(
+ 'id' => 'TEST-HELD-CAPTURE',
+ 'status' => Constants::STATUS_COMPLETED,
+ 'custom_id' => $this->payload['purchase_units'][0]['custom_id'],
+ )
+ );
+ }
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'on-hold', $order->get_status() );
+
+ $order->update_status( 'processing' );
+
+ $notes = implode( ' ', wp_list_pluck( wc_get_order_notes( array( 'order_id' => $order->get_id() ) ), 'content' ) );
+ if ( $captured ) {
+ $this->assertStringNotContainsString( 'PayPal payment was not captured', $notes );
+ } else {
+ $this->assertStringContainsString( 'PayPal payment was not captured', $notes );
+ }
+ $this->assertSame( 0, $this->captures );
+ }
+
+ /**
+ * @testdox A late approval for a paid order keeps merchant address edits and holds only a different destination.
+ * @testWith [false, "processing", ""]
+ * [true, "on-hold", "yes"]
+ * @param bool $different Whether the late approval carries a different destination.
+ * @param string $status Expected order status.
+ * @param string $review Expected review flag.
+ */
+ public function test_late_approval_after_merchant_address_edit( bool $different, string $status, string $review ): void {
+ $order = $this->create_attempt();
+ $details = $this->approval();
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $details );
+ $this->send_webhook(
+ 'PAYMENT.CAPTURE.COMPLETED',
+ array(
+ 'id' => 'TEST-PAID-CAPTURE',
+ 'status' => Constants::STATUS_COMPLETED,
+ 'custom_id' => $this->payload['purchase_units'][0]['custom_id'],
+ )
+ );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'processing', $order->get_status() );
+ $order->set_shipping_address_1( '30 Moved Street' );
+ $order->set_shipping_postcode( '90211' );
+ $order->save();
+ if ( $different ) {
+ $details['purchase_units'][0]['shipping']['address']['postal_code'] = '10001';
+ }
+
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $details );
+
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( $status, $order->get_status() );
+ $this->assertSame( $review, $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ $this->assertSame( '30 Moved Street', $order->get_shipping_address_1() );
+ $this->assertSame( '90211', $order->get_shipping_postcode() );
+ }
+
+ /**
+ * @testdox A capture before address confirmation waits for a matching approval or return without capturing twice.
+ * @testWith [false, false]
+ * [false, true]
+ * [true, false]
+ * [true, true]
+ * @param bool $return_path Whether confirmation arrives through the return page.
+ * @param bool $different Whether the provider destination differs.
+ */
+ public function test_capture_before_address_confirmation( bool $return_path, bool $different ): void {
+ $order = $this->create_attempt();
+ $total = $order->get_total();
+ $shipping = $order->get_address( 'shipping' );
+ $capture = array(
+ 'id' => 'TEST-EARLY-CAPTURE',
+ 'status' => Constants::STATUS_COMPLETED,
+ 'custom_id' => $this->payload['purchase_units'][0]['custom_id'],
+ );
+ $this->send_webhook( 'PAYMENT.CAPTURE.COMPLETED', $capture );
+ $this->assertSame( 'on-hold', wc_get_order( $order->get_id() )->get_status(), 'Captured physical orders must wait for their destination to be checked.' );
+ $this->details = $this->approval();
+ if ( $different ) {
+ $this->details['purchase_units'][0]['shipping']['address']['postal_code'] = '10001';
+ }
+ if ( $return_path ) {
+ $gateway = $this->getMockBuilder( \WC_Gateway_Paypal::class )->onlyMethods( array( 'should_use_orders_v2' ) )->getMock();
+ $gateway->method( 'should_use_orders_v2' )->willReturn( true );
+ $gateway->update_addresses_in_order( $order->get_id() );
+ } else {
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $this->details );
+ }
+ $this->send_webhook( 'PAYMENT.CAPTURE.COMPLETED', $capture );
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $this->details );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( $different ? 'on-hold' : 'processing', $order->get_status(), 'Only a confirmed matching destination may leave the address hold.' );
+ $this->assertSame( 'TEST-EARLY-CAPTURE', $order->get_transaction_id() );
+ $this->assertSame( Constants::STATUS_COMPLETED, $order->get_meta( Constants::PAYPAL_ORDER_META_STATUS ) );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( $total, $order->get_total() );
+ $this->assertEquals( 0, $order->get_total_refunded() );
+ $this->assertSame( 0, $this->captures, 'An already captured payment must not be captured again.' );
+ }
+
+ /**
+ * @testdox Address confirmation does not release a merchant hold or reopen a canceled or refunded order.
+ * @testWith ["on-hold"]
+ * ["cancelled"]
+ * ["refunded"]
+ * @param string $status Existing merchant status.
+ */
+ public function test_capture_preserves_existing_order_disposition( string $status ): void {
+ $order = $this->create_attempt();
+ $order->set_status( $status );
+ $order->save();
+ $this->send_webhook(
+ 'PAYMENT.CAPTURE.COMPLETED',
+ array(
+ 'id' => 'TEST-HELD-CAPTURE',
+ 'status' => Constants::STATUS_COMPLETED,
+ 'custom_id' => $this->payload['purchase_units'][0]['custom_id'],
+ )
+ );
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $this->approval() );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( $status, $order->get_status(), 'Address confirmation must not reverse an unrelated order decision.' );
+ $this->assertSame( 'TEST-HELD-CAPTURE', $order->get_transaction_id() );
+ $this->assertSame( 0, $this->captures );
+ }
+
+ /**
+ * @testdox Allows unchanged legacy shipping but requires review for a different destination.
+ * @testWith [false, ""]
+ * [true, "yes"]
+ * @param bool $different Whether the returned location differs.
+ * @param string $review Expected review flag.
+ */
+ public function test_legacy_attempt( bool $different, string $review ): void {
+ $order = $this->create_attempt();
+ $shipping = $order->get_address( 'shipping' );
+ $order->delete_meta_data( Constants::PAYPAL_ORDER_META_ADDRESS_CONTEXT );
+ $details = $this->approval();
+ if ( $different ) {
+ $details['purchase_units'][0]['shipping']['address']['country_code'] = 'GB';
+ }
+ Helper::update_addresses_in_order( $order, $details );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( $review, $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ }
+
+ /**
+ * @testdox Records a successful callback quote before allowing final street details.
+ * @testWith ["shipping"]
+ * ["billing"]
+ * @param string $tax_based_on Tax location setting.
+ */
+ public function test_callback_quote_and_duplicate_approval( string $tax_based_on ): void {
+ update_option( 'woocommerce_tax_based_on', $tax_based_on );
+ update_option( 'woocommerce_calc_taxes', 'yes' );
+ update_option( 'woocommerce_prices_include_tax', 'no' );
+ foreach ( array(
+ 'CA' => '10',
+ 'NY' => '5',
+ ) as $state => $rate ) {
+ \WC_Tax::_insert_tax_rate(
+ array(
+ 'tax_rate_country' => 'US',
+ 'tax_rate_state' => $state,
+ 'tax_rate' => $rate,
+ 'tax_rate_name' => 'Test tax',
+ 'tax_rate_priority' => 1,
+ 'tax_rate_compound' => 0,
+ 'tax_rate_shipping' => 1,
+ 'tax_rate_order' => 1,
+ 'tax_rate_class' => '',
+ )
+ );
+ }
+ $order = $this->create_attempt();
+ $zone = new \WC_Shipping_Zone();
+ $zone->set_zone_name( 'Callback test zone' );
+ $zone->add_location( 'US', 'country' );
+ $zone->save();
+ $method = $zone->add_shipping_method( 'flat_rate' );
+ update_option(
+ 'woocommerce_flat_rate_' . $method . '_settings',
+ array(
+ 'cost' => '15',
+ 'enabled' => 'yes',
+ )
+ );
+ \WC_Cache_Helper::get_transient_version( 'shipping', true );
+ delete_transient( 'wc_shipping_method_count' );
+ $request = new \WP_REST_Request( 'POST' );
+ $request->set_param( 'id', 'TEST-PAYPAL-ORDER' );
+ $request->set_param( 'purchase_units', $this->payload['purchase_units'] );
+ $request->set_param(
+ 'shipping_address',
+ array(
+ 'country_code' => 'US',
+ 'admin_area_1' => 'CA',
+ 'admin_area_2' => 'San Francisco',
+ 'postal_code' => '94103',
+ )
+ );
+ $request->set_param( 'shipping_option', array( 'id' => 'flat_rate:' . $method ) );
+ $controller = new \WC_REST_PayPal_Standard_Controller();
+ $response = $controller->process_shipping_callback( $request );
+ $this->assertSame( 200, $response->get_status() );
+ $response = $controller->process_shipping_callback( $request );
+ $this->assertSame( 200, $response->get_status() );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'NY', WC()->customer->get_billing_state() );
+ $this->assertSame( 'CA', WC()->customer->get_shipping_state() );
+ $this->assertSame( '15', $order->get_shipping_total() );
+ $this->assertSame( 'shipping' === $tax_based_on ? '5.50' : '2.75', wc_format_decimal( $order->get_total_tax(), 2 ) );
+ $total = $order->get_total();
+ $details = $this->approval();
+ $details['purchase_units'][0]['amount'] = $response->get_data()['purchase_units'][0]['amount'];
+ $details['purchase_units'][0]['shipping']['address'] = array_merge(
+ $request->get_param( 'shipping_address' ),
+ array(
+ 'address_line_1' => '30 Approved Street',
+ 'address_line_2' => '',
+ )
+ );
+ Helper::update_addresses_in_order( $order, $details );
+ Helper::update_addresses_in_order( $order, $details );
+ $this->assertSame( '30 Approved Street', $order->get_shipping_address_1() );
+ $this->assertSame( '94103', $order->get_shipping_postcode() );
+ $this->assertSame( $total, $order->get_total() );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ $details['purchase_units'][0]['amount']['value'] = '1.00';
+ Helper::update_addresses_in_order( $order, $details );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ $this->assertSame( $total, $order->get_total() );
+ $notes = implode( ' ', wp_list_pluck( wc_get_order_notes( array( 'order_id' => $order->get_id() ) ), 'content' ) );
+ $this->assertStringContainsString( 'payment amount', $notes );
+ }
+
+ /**
+ * @testdox Allows a normal payment once with either webhook and thank-you ordering.
+ * @testWith [false]
+ * [true]
+ * @param bool $return_first Whether the return runs first.
+ */
+ public function test_normal_fallback_and_webhook_ordering( bool $return_first ): void {
+ $order = $this->create_attempt( 'no', 'no' );
+ $shipping = $order->get_address( 'shipping' );
+ $this->details = $this->approval();
+ $gateway = $this->getMockBuilder( \WC_Gateway_Paypal::class )->onlyMethods( array( 'should_use_orders_v2' ) )->getMock();
+ $gateway->method( 'should_use_orders_v2' )->willReturn( true );
+ if ( $return_first ) {
+ $gateway->update_addresses_in_order( $order->get_id() );
+ }
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $this->details );
+ $gateway->update_addresses_in_order( $order->get_id() );
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $this->details );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ $this->assertSame( 1, $this->captures );
+ }
+
+ /**
+ * @testdox Keeps a late return mismatch on hold after a payment has been captured.
+ */
+ public function test_captured_payment_return_mismatch(): void {
+ $order = $this->create_attempt();
+ $order->set_transaction_id( 'TEST-CAPTURE' );
+ $order->update_meta_data( Constants::PAYPAL_ORDER_META_STATUS, Constants::STATUS_COMPLETED );
+ $order->set_status( 'processing' );
+ $order->save();
+ $shipping = $order->get_address( 'shipping' );
+ $total = $order->get_total();
+ $this->details = $this->approval();
+ $this->details['purchase_units'][0]['shipping']['address']['postal_code'] = '10001';
+ $gateway = $this->getMockBuilder( \WC_Gateway_Paypal::class )->onlyMethods( array( 'should_use_orders_v2' ) )->getMock();
+ $gateway->method( 'should_use_orders_v2' )->willReturn( true );
+ $gateway->update_addresses_in_order( $order->get_id() );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'on-hold', $order->get_status() );
+ $this->assertSame( 'TEST-CAPTURE', $order->get_transaction_id() );
+ $this->assertSame( 'COMPLETED', $order->get_meta( Constants::PAYPAL_ORDER_META_STATUS ) );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( $total, $order->get_total() );
+ $notes = implode( ' ', wp_list_pluck( wc_get_order_notes( array( 'order_id' => $order->get_id() ) ), 'content' ) );
+ $this->assertStringContainsString( 'reported this payment as captured', $notes );
+ $this->assertStringNotContainsString( 'skip automatic capture', $notes );
+ }
+
+ /**
+ * @testdox Adds the mismatch note when the order is already on hold.
+ */
+ public function test_mismatch_note_on_already_held_order(): void {
+ $order = $this->create_attempt();
+ $order->set_status( 'on-hold' );
+ $order->save();
+ $notes_before = wc_get_order_notes( array( 'order_id' => $order->get_id() ) );
+ $details = $this->approval();
+ $details['purchase_units'][0]['shipping']['address']['postal_code'] = '10001';
+
+ Helper::update_addresses_in_order( $order, $details );
+
+ $this->assertSame( 'on-hold', $order->get_status() );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ $notes_after = wc_get_order_notes( array( 'order_id' => $order->get_id() ) );
+ $this->assertCount( count( $notes_before ) + 1, $notes_after );
+ $this->assertStringContainsString( 'shipping address', $notes_after[0]->content );
+ $this->assertStringContainsString( 'skip automatic capture', $notes_after[0]->content );
+ }
+
+ /**
+ * @testdox Fills an empty billing location from the PayPal payer on approval.
+ */
+ public function test_approval_fills_empty_billing_location(): void {
+ $order = $this->create_attempt();
+ foreach ( array( 'address_1', 'address_2', 'city', 'state', 'postcode', 'country' ) as $field ) {
+ $order->{"set_billing_{$field}"}( '' );
+ }
+ $order->save();
+ $shipping = $order->get_address( 'shipping' );
+ $details = $this->approval();
+ $details['payer']['address'] = array(
+ 'country_code' => 'GB',
+ 'postal_code' => 'SW1A 1AA',
+ 'admin_area_2' => 'London',
+ 'address_line_1' => '1 Payer Road',
+ );
+
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $details );
+
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'GB', $order->get_billing_country() );
+ $this->assertSame( 'SW1A 1AA', $order->get_billing_postcode() );
+ $this->assertSame( 'London', $order->get_billing_city() );
+ $this->assertSame( '1 Payer Road', $order->get_billing_address_1() );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ }
+
+ /**
+ * @testdox Skips address imports and shipping callbacks for virtual orders.
+ */
+ public function test_virtual_attempt(): void {
+ $order = $this->create_attempt();
+ foreach ( $order->get_items() as $item ) {
+ $product = $item->get_product();
+ $product->set_virtual( true );
+ $product->save();
+ }
+ $order = wc_get_order( $order->get_id() );
+ $this->assertNotNull( ( new Request( new \WC_Gateway_Paypal() ) )->create_paypal_order( $order ) );
+ $shipping = $order->get_address( 'shipping' );
+ $context = $this->payload['payment_source']['paypal']['experience_context'];
+ $this->assertSame( Constants::SHIPPING_NO_SHIPPING, $context['shipping_preference'] );
+ $this->assertArrayNotHasKey( 'order_update_callback_config', $context );
+ Helper::update_addresses_in_order( $order, $this->approval() );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ }
+
+ /**
+ * @testdox Rejects shipping callbacks when the payment attempt retained merchant shipping.
+ * @testWith ["no", "yes"]
+ * ["yes", "yes"]
+ * @param string $send_shipping Address source setting.
+ * @param string $override Address lock setting.
+ */
+ public function test_callback_cannot_change_preserved_shipping( string $send_shipping, string $override ): void {
+ $order = $this->create_attempt( $send_shipping, $override );
+ $shipping = $order->get_address( 'shipping' );
+ $request = new \WP_REST_Request( 'POST' );
+ $request->set_param( 'id', 'TEST-PAYPAL-ORDER' );
+ $request->set_param( 'purchase_units', $this->payload['purchase_units'] );
+ $request->set_param(
+ 'shipping_address',
+ array(
+ 'country_code' => 'GB',
+ 'postal_code' => 'SW1A 1AA',
+ )
+ );
+ $response = ( new \WC_REST_PayPal_Standard_Controller() )->process_shipping_callback( $request );
+ $this->assertSame( 422, $response->get_status() );
+ $this->assertSame( $shipping, wc_get_order( $order->get_id() )->get_address( 'shipping' ) );
+ }
+
+ /**
+ * @testdox Preserves the previous quote when a callback cannot price the new address ($failure).
+ * @testWith ["no_rate"]
+ * ["cart_rebuild"]
+ *
+ * @param string $failure Why the callback fails.
+ */
+ public function test_failed_callback_preserves_priced_destination( string $failure ): void {
+ $order = $this->create_attempt();
+ if ( 'no_rate' === $failure ) {
+ \WC_Helper_Shipping::delete_simple_flat_rate();
+ } else {
+ foreach ( $order->get_items() as $item ) {
+ $product = $item->get_product();
+ $product->set_stock_status( 'outofstock' );
+ $product->save();
+ }
+ }
+ $shipping = $order->get_address( 'shipping' );
+ $total = $order->get_total();
+ $context = $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_CONTEXT );
+ $meta = $this->get_shipping_post_meta( $order->get_id() );
+ $request = new \WP_REST_Request( 'POST' );
+ $request->set_param( 'id', 'TEST-PAYPAL-ORDER' );
+ $request->set_param( 'purchase_units', $this->payload['purchase_units'] );
+ $request->set_param(
+ 'shipping_address',
+ array(
+ 'country_code' => 'GB',
+ 'postal_code' => 'SW1A 1AA',
+ )
+ );
+ $response = ( new \WC_REST_PayPal_Standard_Controller() )->process_shipping_callback( $request );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 422, $response->get_status() );
+ $this->assertSame( $shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( $total, $order->get_total() );
+ $this->assertSame( $context, $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_CONTEXT ) );
+ $this->assertSame( $meta, $this->get_shipping_post_meta( $order->get_id() ), 'Restoring the quote must go through the order data store.' );
+ }
+
+ /**
+ * Read the order's shipping post meta, sorted by key.
+ *
+ * The posts data store deletes and re-adds meta on save, so row order is not stable.
+ *
+ * @param int $order_id Order ID.
+ * @return array Shipping post meta keyed by meta key.
+ */
+ private function get_shipping_post_meta( int $order_id ): array {
+ $meta = array_filter(
+ get_post_meta( $order_id ),
+ static function ( $key ) {
+ return 0 === strpos( $key, '_shipping_' );
+ },
+ ARRAY_FILTER_USE_KEY
+ );
+ ksort( $meta );
+ return $meta;
+ }
+
+ /**
+ * @testdox Starts a replacement attempt with its own source policy and address-update state.
+ */
+ public function test_replacement_attempt_resets_address_state(): void {
+ $order = $this->create_attempt();
+ $order->update_meta_data( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW, 'yes' );
+ $order->update_meta_data( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED, 'yes' );
+ $order->save();
+ update_option(
+ 'woocommerce_paypal_settings',
+ array(
+ 'send_shipping' => 'no',
+ 'address_override' => 'yes',
+ )
+ );
+ $this->assertNotNull( ( new Request( new \WC_Gateway_Paypal() ) )->create_paypal_order( $order ) );
+ $order = wc_get_order( $order->get_id() );
+ $context = $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_CONTEXT );
+ $this->assertSame( 'shipping', $context['address_source'] );
+ $this->assertSame( Constants::SHIPPING_SET_PROVIDED_ADDRESS, $context['shipping_preference'] );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ }
+
+ /**
+ * @testdox Ignores approval for a replaced PayPal attempt before changing the current attempt.
+ */
+ public function test_stale_approval_does_not_confirm_replacement_attempt(): void {
+ $order = $this->create_attempt();
+ $old_approval = $this->approval();
+
+ $old_approval['links'][0]['href'] = 'https://example.com/payment/capture';
+
+ $this->provider_order_id = 'TEST-PAYPAL-ORDER-B';
+ $this->assertNotNull( ( new Request( new \WC_Gateway_Paypal() ) )->create_paypal_order( $order ) );
+ $order->update_meta_data( Constants::PAYPAL_ORDER_META_SHIPPING_CALLBACK_TOKEN, 'CURRENT-TOKEN' );
+ $order->save();
+
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $old_approval );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'TEST-PAYPAL-ORDER-B', $order->get_meta( Constants::PAYPAL_ORDER_META_ORDER_ID ) );
+ $this->assertSame( 'CREATED', $order->get_meta( Constants::PAYPAL_ORDER_META_STATUS ) );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ $this->assertSame( 'CURRENT-TOKEN', $order->get_meta( Constants::PAYPAL_ORDER_META_SHIPPING_CALLBACK_TOKEN ) );
+ $this->assertSame( 0, $this->captures, 'A replaced attempt must not trigger a capture request.' );
+
+ $current_approval = $this->approval();
+
+ $current_approval['links'][0]['href'] = 'https://example.com/payment/capture';
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $current_approval );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( Constants::STATUS_APPROVED, $order->get_meta( Constants::PAYPAL_ORDER_META_STATUS ) );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ $this->assertSame( 1, $this->captures, 'The current attempt must retain its normal capture path.' );
+ }
+
+ /**
+ * @testdox Ignores a replaced attempt's approval after the current payment was captured.
+ */
+ public function test_stale_approval_does_not_confirm_captured_replacement_attempt(): void {
+ $order = $this->create_attempt();
+ $old_approval = $this->approval();
+
+ $this->provider_order_id = 'TEST-PAYPAL-ORDER-B';
+ $this->assertNotNull( ( new Request( new \WC_Gateway_Paypal() ) )->create_paypal_order( $order ) );
+ $order->update_meta_data( Constants::PAYPAL_ORDER_META_STATUS, Constants::STATUS_COMPLETED );
+ $order->update_meta_data( Constants::PAYPAL_ORDER_META_SHIPPING_CALLBACK_TOKEN, 'CURRENT-TOKEN' );
+ $order->save();
+
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $old_approval );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( Constants::STATUS_COMPLETED, $order->get_meta( Constants::PAYPAL_ORDER_META_STATUS ) );
+ $this->assertEmpty( $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ $this->assertSame( 'CURRENT-TOKEN', $order->get_meta( Constants::PAYPAL_ORDER_META_SHIPPING_CALLBACK_TOKEN ) );
+
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $this->approval() );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ }
+
+ /**
+ * @testdox Preserves approval for an existing attempt without a stored PayPal order ID.
+ */
+ public function test_approval_without_stored_paypal_order_id(): void {
+ $order = $this->create_attempt();
+ $order->delete_meta_data( Constants::PAYPAL_ORDER_META_ORDER_ID );
+ $order->save();
+
+ $this->send_webhook( 'CHECKOUT.ORDER.APPROVED', $this->approval() );
+ $order = wc_get_order( $order->get_id() );
+ $this->assertSame( Constants::STATUS_APPROVED, $order->get_meta( Constants::PAYPAL_ORDER_META_STATUS ) );
+ $this->assertSame( 'yes', $order->get_meta( Constants::PAYPAL_ORDER_META_ADDRESSES_UPDATED ) );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Gateways/PayPal/HelperTest.php b/plugins/woocommerce/tests/php/src/Gateways/PayPal/HelperTest.php
index b0ac2c943aa..a2e30453736 100644
--- a/plugins/woocommerce/tests/php/src/Gateways/PayPal/HelperTest.php
+++ b/plugins/woocommerce/tests/php/src/Gateways/PayPal/HelperTest.php
@@ -424,7 +424,7 @@ class HelperTest extends \WC_Unit_Test_Case {
}
/**
- * Test update_addresses_in_order updates both shipping and billing addresses.
+ * @testdox Completes a repriced shipping address while preserving the billing tax location.
*/
public function test_update_addresses_in_order_updates_addresses() {
$order = \WC_Helper_Order::create_order();
@@ -465,6 +465,30 @@ class HelperTest extends \WC_Unit_Test_Case {
),
);
+ $order->set_shipping_country( 'US' );
+ $order->set_shipping_postcode( '12345' );
+ $order->set_shipping_state( 'CA' );
+ $order->set_shipping_city( 'San Francisco' );
+ $billing_address = $order->get_address( 'billing' );
+ $amount = array(
+ 'value' => wc_format_decimal( $order->get_total(), 2 ),
+ 'currency_code' => $order->get_currency(),
+ );
+ $paypal_order_details['purchase_units'][0]['amount'] = $amount;
+ $order->update_meta_data(
+ PayPalConstants::PAYPAL_ORDER_META_ADDRESS_CONTEXT,
+ array(
+ 'shipping_address' => $order->get_address( 'shipping' ),
+ 'expected_address' => array(
+ 'country_code' => 'US',
+ 'postal_code' => '12345',
+ 'admin_area_1' => 'CA',
+ 'admin_area_2' => 'San Francisco',
+ ),
+ 'callback_amount' => $amount,
+ )
+ );
+
Helper::update_addresses_in_order( $order, $paypal_order_details );
// Verify shipping address was updated.
@@ -481,12 +505,12 @@ class HelperTest extends \WC_Unit_Test_Case {
$this->assertEquals( 'Jane', $order->get_billing_first_name() );
$this->assertEquals( 'Smith', $order->get_billing_last_name() );
$this->assertEquals( 'jane.smith@example.com', $order->get_billing_email() );
- $this->assertEquals( 'US', $order->get_billing_country() );
- $this->assertEquals( '54321', $order->get_billing_postcode() );
- $this->assertEquals( 'NY', $order->get_billing_state() );
- $this->assertEquals( 'New York', $order->get_billing_city() );
- $this->assertEquals( '456 Broadway', $order->get_billing_address_1() );
- $this->assertEquals( 'Suite 100', $order->get_billing_address_2() );
+ $this->assertEquals( $billing_address['country'], $order->get_billing_country() );
+ $this->assertEquals( $billing_address['postcode'], $order->get_billing_postcode() );
+ $this->assertEquals( $billing_address['state'], $order->get_billing_state() );
+ $this->assertEquals( $billing_address['city'], $order->get_billing_city() );
+ $this->assertEquals( $billing_address['address_1'], $order->get_billing_address_1() );
+ $this->assertEquals( $billing_address['address_2'], $order->get_billing_address_2() );
// Verify meta flag was set.
$this->assertEquals( 'yes', $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESSES_UPDATED, true ) );
@@ -569,10 +593,12 @@ class HelperTest extends \WC_Unit_Test_Case {
}
/**
- * Test update_addresses_in_order handles partial address data.
+ * @testdox Does not replace a legacy priced destination with partial address data.
*/
public function test_update_addresses_in_order_handles_partial_address_data() {
- $order = \WC_Helper_Order::create_order();
+ $order = \WC_Helper_Order::create_order();
+ $original_shipping = $order->get_address( 'shipping' );
+ $original_billing = $order->get_address( 'billing' );
$order->save();
$paypal_order_details = array(
@@ -603,15 +629,9 @@ class HelperTest extends \WC_Unit_Test_Case {
Helper::update_addresses_in_order( $order, $paypal_order_details );
- // Shipping country should be set, other fields should be empty strings.
- $this->assertEquals( 'US', $order->get_shipping_country() );
- $this->assertEquals( '', $order->get_shipping_postcode() );
- $this->assertEquals( '', $order->get_shipping_state() );
-
- // Billing should have given name and postal code.
- $this->assertEquals( 'Jane', $order->get_billing_first_name() );
- $this->assertEquals( '', $order->get_billing_last_name() );
- $this->assertEquals( '12345', $order->get_billing_postcode() );
+ $this->assertSame( $original_shipping, $order->get_address( 'shipping' ) );
+ $this->assertSame( $original_billing, $order->get_address( 'billing' ) );
+ $this->assertSame( 'yes', $order->get_meta( PayPalConstants::PAYPAL_ORDER_META_ADDRESS_REVIEW ) );
// Clean up.
$order->delete( true );