Automattic\WooCommerce\Blocks\Domain\Services

CheckoutLink::get_checkout_linkprotectedWC 1.0

Process the query params and return the checkout link to redirect to complete with session token.

Method of the class: CheckoutLink{}

No Hooks.

Returns

String. The checkout link.

Usage

// protected - for code of main (parent) or child class
$result = $this->get_checkout_link();

CheckoutLink::get_checkout_link() code WC 10.8.1

protected function get_checkout_link() {
	$controller = new CartController();
	$products   = $this->get_products_from_checkout_link();
	$errors     = new \WP_Error();

	foreach ( $products as $product_id => $qty ) {
		try {
			$controller->add_to_cart(
				[
					'id'       => $product_id,
					'quantity' => $qty,
				]
			);
		} catch ( \Exception $e ) {
			$errors->add( 'error', $e->getMessage() );
		}
	}

	// Nothing was added to the cart. We need to redirect to the cart page with an error notice. Since guests may not
	// have a session, add the notice in the query string.
	if ( wc()->cart->is_empty() ) {
		$errors->add( 'error', __( 'The provided checkout link was out of date or invalid. No products were added to the cart.', 'woocommerce' ) );

		if ( ! wc()->session->has_session() ) {
			return add_query_arg( 'wc_error', rawurlencode( $errors->get_error_message() ), wc_get_cart_url() );
		} else {
			$this->add_error_notices( $errors );
		}

		return wc_get_cart_url();
	}

	// Apply coupon if provided.
	$coupon = wc_format_coupon_code( wp_unslash( $_GET['coupon'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

	if ( wc_coupons_enabled() && ! empty( $coupon ) ) {
		try {
			$controller->apply_coupon( $coupon );
		} catch ( \Exception $e ) {
			$errors->add( 'error', $e->getMessage() );
		}
	}

	// Add error notices to the cart. This requires a session otherwise the notices will not be displayed.
	$this->add_error_notices( $errors );

	$redirect_url = wc_get_checkout_url();

	// Preserve the query string--pass it to the checkout page.
	if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {
		$redirect_url = remove_query_arg(
			[
				'products',
				'coupon',
				'checkout-link',
			],
			add_query_arg( wp_unslash( $_SERVER['QUERY_STRING'] ), '', $redirect_url ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		);
	}

	// If the user is logged in, the session is tied to the user ID. Do not use a cart token.
	if ( ! is_user_logged_in() ) {
		$session_token = CartTokenUtils::get_cart_token( (string) wc()->session->get_customer_id() );
		$redirect_url  = add_query_arg( 'session', $session_token, $redirect_url );
	}

	return $redirect_url;
}