Automattic\WooCommerce\Internal\StockNotifications\Frontend

MyAccountEndpoint::maybe_handle_action │ public │ WC 1.0

Intercept a row-action link (resend or cancel) from the stock notifications tab.

Guards, shared by every action:

  • Must be on the My Account > stock-notifications endpoint.
  • Must be authenticated.
  • Nonce must be scoped to the action and the notification id ({@see ::get_nonce_action()}).
  • The notification must exist and belong to the current user.

Requests that aren't an action link, or that arrive anonymously, are dropped silently. Everything else redirects back to the clean endpoint URL with a notice, so the link never looks dead and a refresh can't replay it. A missing notification and one owned by someone else share the same error, so the response doesn't confirm whether the id exists.

Method of the class: MyAccountEndpoint{}

No Hooks.

Returns

null. Nothing (null).

Usage

$MyAccountEndpoint = new MyAccountEndpoint();
$MyAccountEndpoint->maybe_handle_action(): void;

MyAccountEndpoint::maybe_handle_action() code WC 11.2.1

public function maybe_handle_action(): void {
	global $wp;

	// phpcs:disable WordPress.Security.NonceVerification.Recommended
	if ( ! isset( $_GET[ self::ACTION_FIELD ] ) ) {
		return;
	}

	if ( ! isset( $wp->query_vars[ self::ENDPOINT ] ) ) {
		return;
	}

	if ( ! is_user_logged_in() ) {
		return;
	}

	$action = sanitize_key( wp_unslash( $_GET[ self::ACTION_FIELD ] ) );
	if ( ! in_array( $action, array( self::ACTION_RESEND, self::ACTION_CANCEL ), true ) ) {
		return;
	}

	$notification_id = isset( $_GET['notification_id'] ) ? absint( wp_unslash( $_GET['notification_id'] ) ) : 0;
	if ( $notification_id <= 0 ) {
		return;
	}

	$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';

	// The page the link was clicked on, so the redirect lands there instead of page 1.
	$page = isset( $_GET['notifications_page'] ) ? max( 1, absint( wp_unslash( $_GET['notifications_page'] ) ) ) : 1;
	// phpcs:enable WordPress.Security.NonceVerification.Recommended

	if ( ! wp_verify_nonce( $nonce, self::get_nonce_action( $action, $notification_id ) ) ) {
		$this->redirect_with_error( __( 'This link has expired. Please reload the page and try again.', 'woocommerce' ), $page );
	}

	$notification = Factory::get_notification( $notification_id );
	if ( ! $notification instanceof Notification || (int) $notification->get_user_id() !== get_current_user_id() ) {
		$this->redirect_with_error( __( 'We were unable to process your request. Notification not found.', 'woocommerce' ), $page );
	}

	$result = self::ACTION_RESEND === $action
		? $this->resend( $notification )
		: $this->cancel( $notification );

	if ( is_wp_error( $result ) ) {
		$this->redirect_with_error( $result->get_error_message(), $page );
	}

	\wc_add_notice( esc_html( $result ) );
	wp_safe_redirect( self::get_endpoint_url( $page ) );
	exit;
}