How to Integrate SMS Validation and Notifications in WooCommerce’s New Gutenberg Checkout Block

Updated on Apr 28, 2024

WooCommerce recently introduced a new Gutenberg-based checkout block, enhancing the checkout process with more flexibility and customization options. This guide will demonstrate how to validate phone numbers and send SMS notifications using the woocommerce_store_api_checkout_order_processed hook, specifically designed for this new checkout block.

Prerequisites

  • Ensure you installed the latest version of the WooCommerce plugin is installed and active.
  • Ensure you installed the latest version of the WP SMS plugin is installed and active.

Validate Phone Numbers in the New WooCommerce Gutenberg Checkout Block

To ensure phone numbers are valid during the checkout process in the new Gutenberg block, introduced in WooCommerce version 8.3, implement the following in your theme’s functions.php file:

add_action('woocommerce_store_api_checkout_order_processed', function ( $order_id, $order_object, $request ) {
    $phone = $order_object->get_billing_phone();

    if ( !preg_match('/^\+[1-9]\d{1,14}$/', $phone) ) {
        throw new Exception('Please enter a valid international phone number to complete your order.');
    }
} );

This snippet checks the phone number against an international format. For more details, see the official documentation at WooCommerce Cart & Checkout Blocks Status.

Send SMS Notifications After Order Processing

Send an SMS confirmation automatically after processing the order using the validated phone number:

add_action('woocommerce_store_api_checkout_order_processed', function ( $order_id, $order_object, $request ) {
    $phone = $order_object->get_billing_phone();

    // Assuming WP SMS Pro is configured and active
    if ( function_exists('wp_sms_send') ) {
        wp_sms_send($phone, 'Thank you for your order! Your order ID is ' . $order_id . '.');
    }
});

Handling Errors with SMS Notifications

In case of issues during the order process, notify customers by SMS:

add_action('woocommerce_store_api_checkout_order_processed', function ( $order_id, $order_object, $request ) {
    try {
        // Validation and SMS sending logic here
    } catch (Exception $e) {
        if ( function_exists('wp_sms_send') ) {
            wp_sms_send($order_object->get_billing_phone(), 'Error processing your order: ' . $e->getMessage());
        }
        throw $e;
    }
});

You can find further information on the woocommerce_store_api_checkout_order_processed hook and its implementation at the WooCommerce GitHub repository.

Conclusion

Integrating SMS validation and notifications in WooCommerce’s new Gutenberg checkout block enhances customer data accuracy and the overall checkout experience. Follow the steps outlined in this guide to implement these SMS features effectively in your WooCommerce store.