WooCommerce. * * Handles inbound requests from ACS (ACS -> store side): * - POST /wp-json/weship-acs-sync/v1/update-order-status (shipment + tracking, cancellation) * - POST /wp-json/weship-acs-sync/v1/update-inventory (stock reset by SKU) * - POST /wp-json/weship-acs-sync/v1/update-order-weather-hold * - GET /wp-json/weship-acs-sync/v1/products (paginated product list) * * Requests are authenticated with the same ApiKey / AccountId headers the * outbound calls use — no separate WooCommerce REST API keys required. * * @package Weship_ACS_Sync */ defined( 'ABSPATH' ) || exit; /** * Class Weship_ACS_Sync_Webhooks */ class Weship_ACS_Sync_Webhooks { const REST_NAMESPACE = 'weship-acs-sync/v1'; /** * ACS order status code meaning "shipped" (Constants.SIX_INT in the original). */ const STATUS_SHIPPED = 6; /** * Logger. * * @var Weship_ACS_Sync_Logger */ private $logger; /** * Constructor. * * @param Weship_ACS_Sync_Logger $logger Logger. */ public function __construct( Weship_ACS_Sync_Logger $logger ) { $this->logger = $logger; add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Register REST routes. */ public function register_routes() { register_rest_route( self::REST_NAMESPACE, '/update-order-status', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'update_order_status' ), 'permission_callback' => array( $this, 'authenticate' ), ) ); register_rest_route( self::REST_NAMESPACE, '/update-inventory', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'update_inventory' ), 'permission_callback' => array( $this, 'authenticate' ), ) ); register_rest_route( self::REST_NAMESPACE, '/update-order-weather-hold', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'update_weather_hold' ), 'permission_callback' => array( $this, 'authenticate' ), ) ); register_rest_route( self::REST_NAMESPACE, '/products', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_products' ), 'permission_callback' => array( $this, 'authenticate' ), ) ); } /** * Authenticate the request against the stored ApiKey/AccountId. * * @param WP_REST_Request $request Request. * @return bool|WP_Error */ public function authenticate( WP_REST_Request $request ) { $api_key = (string) $request->get_header( 'ApiKey' ); $account_id = (string) $request->get_header( 'AccountId' ); $expected_key = (string) Weship_ACS_Sync_Api_Client::get_setting( 'api_key' ); $expected_account = (string) Weship_ACS_Sync_Api_Client::get_setting( 'account_id' ); if ( '' === $expected_key || '' === $expected_account ) { return new WP_Error( 'weship_acs_sync_not_configured', __( 'Plugin is not configured.', 'weship-acs-sync-for-woocommerce' ), array( 'status' => 403 ) ); } if ( ! hash_equals( $expected_key, $api_key ) || ! hash_equals( $expected_account, $account_id ) ) { return new WP_Error( 'weship_acs_sync_forbidden', __( 'Invalid credentials.', 'weship-acs-sync-for-woocommerce' ), array( 'status' => 401 ) ); } return true; } /** * Handle shipment/status updates from ACS. * * Expected payload: { orderNumber, carrier, carrierTrackingId, trackingUrl, * trackingId, ..., subOrdersList: [ { boxId, orderStatus, carrier, * carrierService, carrierTrackingId, trackingId, trackingUrl, * deliveryDate, orderItems: [ { sku, quantity } ], ... } ] }. * * Each shipped box in subOrdersList gets its own tracking entry and order * note, so a multi-box shipment shows multiple trackings on the order. * * "Shipped" only updates META_FULFILLMENT_STATUS (shown alongside, not * instead of, the WooCommerce order status) — it does NOT change the * WooCommerce order status. Only "Delivered" moves the WooCommerce order * to Completed. * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function update_order_status( WP_REST_Request $request ) { $params = $request->get_json_params(); $order_number = isset( $params['orderNumber'] ) ? sanitize_text_field( $params['orderNumber'] ) : ''; if ( '' === $order_number ) { return new WP_REST_Response( array( 'status' => 'error', 'message' => 'Invalid request: Order number is missing.' ), 400 ); } $order = $this->find_order( $this->strip_child_suffix( $order_number ) ); if ( ! $order ) { $response_body = array( 'status' => 'error', 'message' => 'No matching order found.' ); $this->logger->log( 'update_order_status', 'inbound', rest_url( self::REST_NAMESPACE . '/update-order-status' ), 0, '400', 'No matching order found: ' . $order_number, wp_json_encode( $params ), wp_json_encode( $response_body ) ); return new WP_REST_Response( $response_body, 400 ); } if ( $this->is_cancelled_status( $params ) ) { return $this->handle_cancelled_status( $order, $params ); } $sub_orders = isset( $params['subOrdersList'] ) && is_array( $params['subOrdersList'] ) ? $params['subOrdersList'] : array(); $responses = array(); $shipped = false; $delivered = false; foreach ( $sub_orders as $sub ) { $status = isset( $sub['orderStatus'] ) ? (int) $sub['orderStatus'] : 0; $status_desc = isset( $sub['orderStatusDesc'] ) ? (string) $sub['orderStatusDesc'] : ''; $number = isset( $sub['orderNumber'] ) ? sanitize_text_field( $sub['orderNumber'] ) : $order_number; $box_id = isset( $sub['boxId'] ) ? sanitize_text_field( $sub['boxId'] ) : ''; if ( self::STATUS_SHIPPED === $status ) { $carrier = isset( $sub['carrier'] ) ? sanitize_text_field( $sub['carrier'] ) : 'Other'; $carrier_service = isset( $sub['carrierService'] ) ? sanitize_text_field( $sub['carrierService'] ) : ''; $tracking_number = isset( $sub['carrierTrackingId'] ) ? sanitize_text_field( $sub['carrierTrackingId'] ) : ''; $tracking_url = isset( $sub['trackingUrl'] ) ? esc_url_raw( $sub['trackingUrl'] ) : ''; $delivery_date = isset( $sub['deliveryDate'] ) ? sanitize_text_field( $sub['deliveryDate'] ) : ''; // Append (never overwrite) so every box shipped — now or in a // previous call — keeps its own tracking entry on the order. $tracking_list = (array) $order->get_meta( '_weship_acs_sync_tracking' ); $tracking_list[] = array( 'box_id' => $box_id, 'carrier' => $carrier, 'service' => $carrier_service, 'tracking_id' => $tracking_number, 'tracking_url' => $tracking_url, 'delivery_date' => $delivery_date, 'date' => current_time( 'mysql' ), ); $order->update_meta_data( '_weship_acs_sync_tracking', $tracking_list ); $note = $box_id ? sprintf( /* translators: 1: box ID, 2: carrier, 3: tracking number */ __( 'WSE ACS Sync: box %1$s shipped. Carrier: %2$s, Tracking: %3$s', 'weship-acs-sync-for-woocommerce' ), $box_id, $carrier, $tracking_number ) : sprintf( /* translators: 1: carrier, 2: tracking number */ __( 'WSE ACS Sync: shipment created. Carrier: %1$s, Tracking: %2$s', 'weship-acs-sync-for-woocommerce' ), $carrier, $tracking_number ); if ( $tracking_url ) { $note .= ' — ' . $tracking_url; } $order->add_order_note( $note, 1 ); // Note visible to the customer. $shipped = true; $responses[] = $number . ( $box_id ? " (box {$box_id})" : '' ) . ' - fulfilled'; continue; } if ( $this->is_delivered_status_desc( $status_desc ) ) { $order->add_order_note( $box_id /* translators: %s: box ID */ ? sprintf( __( 'WSE ACS Sync: box %s delivered.', 'weship-acs-sync-for-woocommerce' ), $box_id ) : __( 'WSE ACS Sync: order delivered.', 'weship-acs-sync-for-woocommerce' ), 1 // Note visible to the customer. ); $delivered = true; $responses[] = $number . ( $box_id ? " (box {$box_id})" : '' ) . ' - delivered'; continue; } $responses[] = $number . ' - Order not in shipped/delivered status.'; } // A custom fulfillment status, independent of the WooCommerce order // status: "Shipped" no longer bumps the WooCommerce status on its own // (see below) — only "Delivered" does, via the order status change // beneath it. If both arrive in the same call, Delivered wins since // it's the more advanced state. if ( $shipped ) { $order->update_meta_data( Weship_ACS_Sync_Order_Sync::META_FULFILLMENT_STATUS, 'Shipped' ); } if ( $delivered ) { $order->update_meta_data( Weship_ACS_Sync_Order_Sync::META_FULFILLMENT_STATUS, 'Delivered' ); if ( ! $order->has_status( array( 'completed', 'refunded', 'cancelled' ) ) ) { $order->update_status( 'completed', __( 'WSE ACS Sync: order delivered.', 'weship-acs-sync-for-woocommerce' ) ); } } $order->save(); $response_body = array( 'status' => 'success', 'message' => implode( '; ', $responses ), 'data' => $responses, ); $this->logger->log( 'update_order_status', 'inbound', rest_url( self::REST_NAMESPACE . '/update-order-status' ), $order->get_id(), '200', implode( '; ', $responses ), wp_json_encode( $params ), wp_json_encode( $response_body ) ); return new WP_REST_Response( $response_body, 200 ); } /** * Whether a sub-order's status text signals it was delivered. * * Like cancellation, ACS doesn't document a numeric orderStatus code for * "delivered" the way it does for "shipped" (6), so this matches on the * status text instead. Checked per sub-order (box), same as "shipped", * since delivery is naturally per-box too. * * @param string $status_desc Sub-order orderStatusDesc. * @return bool */ private function is_delivered_status_desc( $status_desc ) { return false !== strpos( strtolower( $status_desc ), 'deliver' ); } /** * Whether the payload signals the order was cancelled in ACS. * * Unlike "shipped" (a documented numeric orderStatus of 6), ACS doesn't * document a numeric code for cancellation, so this matches on the * human-readable status text instead — checking both the top-level * orderStatusDesc and orderState fields, since a whole-order * cancellation is naturally a top-level event rather than a per-box one. * * @param array $params Decoded request body. * @return bool */ private function is_cancelled_status( array $params ) { $desc = strtolower( ( isset( $params['orderStatusDesc'] ) ? (string) $params['orderStatusDesc'] : '' ) . ' ' . ( isset( $params['orderState'] ) ? (string) $params['orderState'] : '' ) ); return false !== strpos( $desc, 'cancel' ); } /** * Handle a cancelled-order notification from ACS. * * @param WC_Order $order Order. * @param array $params Decoded request body. * @return WP_REST_Response */ private function handle_cancelled_status( WC_Order $order, array $params ) { if ( $order->has_status( 'cancelled' ) ) { $response_body = array( 'status' => 'success', 'message' => 'Order already cancelled — ignored.' ); $this->logger->log( 'update_order_status', 'inbound', rest_url( self::REST_NAMESPACE . '/update-order-status' ), $order->get_id(), '200', 'Order already cancelled — webhook ignored.', wp_json_encode( $params ), wp_json_encode( $response_body ) ); return new WP_REST_Response( $response_body, 200 ); } // Persist the sync-status/message change before update_status(): the // status transition below fires woocommerce_order_status_cancelled, // which Weship_ACS_Sync_Order_Sync::cancel_order() also listens on to // push an outbound cancellation to ACS — but only when sync status is // 'synced'. Setting it to 'cancelled' first stops that handler from // looping the cancellation we just received from ACS straight back // out to ACS. $order->update_meta_data( Weship_ACS_Sync_Order_Sync::META_SYNC_STATUS, 'cancelled' ); $order->update_meta_data( Weship_ACS_Sync_Order_Sync::META_CANCEL_MESSAGE, __( 'Cancelled from ACS', 'weship-acs-sync-for-woocommerce' ) ); $order->save(); $order->update_status( 'cancelled', __( 'WSE ACS Sync: order cancelled in ACS.', 'weship-acs-sync-for-woocommerce' ) ); $response_body = array( 'status' => 'success', 'message' => 'Order cancelled.' ); $this->logger->log( 'update_order_status', 'inbound', rest_url( self::REST_NAMESPACE . '/update-order-status' ), $order->get_id(), '200', 'Order cancelled from ACS.', wp_json_encode( $params ), wp_json_encode( $response_body ) ); return new WP_REST_Response( $response_body, 200 ); } /** * Handle inventory updates from ACS. * * Expects an array of objects like the original UpdateInventoryRequest; * uses skuNumber + availableToPromise to reset WooCommerce stock. * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function update_inventory( WP_REST_Request $request ) { $items = $request->get_json_params(); if ( ! is_array( $items ) ) { return new WP_REST_Response( array( 'status' => 'error', 'message' => 'Invalid request body.' ), 400 ); } // Allow a single object as well as an array of objects. if ( isset( $items['skuNumber'] ) ) { $items = array( $items ); } $response = array(); foreach ( $items as $item ) { $sku = isset( $item['skuNumber'] ) ? sanitize_text_field( $item['skuNumber'] ) : ''; $qty = isset( $item['availableToPromise'] ) ? (int) $item['availableToPromise'] : null; if ( '' === trim( $sku ) ) { $response['UNKNOWN_SKU'] = 'Null or blank SKU in request'; continue; } if ( null === $qty ) { $response[ $sku ] = 'Missing availableToPromise'; continue; } $product_id = wc_get_product_id_by_sku( $sku ); if ( ! $product_id ) { $response[ $sku ] = 'SKU not found'; continue; } $product = wc_get_product( $product_id ); if ( ! $product ) { $response[ $sku ] = 'Product not found'; continue; } if ( ! $product->managing_stock() ) { // Initialise stock management, mirroring the "initialize inventory" fallback. $product->set_manage_stock( true ); } wc_update_product_stock( $product, $qty, 'set' ); $product->save(); $response[ $sku ] = array( 'availableForSaleCount' => $qty, 'action' => 'Reset', ); } $response_body = array( 'status' => 'success', 'message' => 'Accepted', 'data' => $response, ); $this->logger->log( 'update_inventory', 'inbound', rest_url( self::REST_NAMESPACE . '/update-inventory' ), 0, '200', wp_json_encode( array_keys( $response ) ), wp_json_encode( $items ), wp_json_encode( $response_body ) ); return new WP_REST_Response( $response_body, 200 ); } /** * Handle weather-hold updates from ACS. * * Expected payload: { orderId, channelName, weatherHold }. * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function update_weather_hold( WP_REST_Request $request ) { $params = $request->get_json_params(); $order_no = isset( $params['orderId'] ) ? sanitize_text_field( $params['orderId'] ) : ''; $hold = isset( $params['weatherHold'] ) ? (bool) $params['weatherHold'] : false; if ( '' === $order_no ) { return new WP_REST_Response( array( 'status' => 'error', 'message' => 'Invalid request: Order id is missing.' ), 400 ); } $order = $this->find_order( $this->strip_child_suffix( $order_no ) ); if ( ! $order ) { return new WP_REST_Response( array( 'status' => 'error', 'message' => 'No matching order found.' ), 400 ); } $order->update_meta_data( '_weship_acs_sync_weather_hold', $hold ? 1 : 0 ); $order->add_order_note( $hold ? __( 'WSE ACS Sync: order placed on weather hold.', 'weship-acs-sync-for-woocommerce' ) : __( 'WSE ACS Sync: weather hold released.', 'weship-acs-sync-for-woocommerce' ) ); $order->save(); $response_body = array( 'status' => 'success', 'message' => 'Request accepted for processing' ); $this->logger->log( 'update_weather_hold', 'inbound', rest_url( self::REST_NAMESPACE . '/update-order-weather-hold' ), $order->get_id(), '200', $hold ? 'hold' : 'release', wp_json_encode( $params ), wp_json_encode( $response_body ) ); return new WP_REST_Response( $response_body, 200 ); } /** * List products, paginated. Lets ACS pull the catalog using the * same ApiKey/AccountId headers as the other endpoints, instead of * separate WooCommerce REST API keys. * * Query params: page (default 1), per_page (default 20, max 100), * search, status (default publish), sku. * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function get_products( WP_REST_Request $request ) { $page = max( 1, (int) $request->get_param( 'page' ) ); $per_page = (int) $request->get_param( 'per_page' ); $per_page = $per_page > 0 ? min( 100, $per_page ) : 20; $search = sanitize_text_field( (string) $request->get_param( 'search' ) ); $status = sanitize_text_field( (string) $request->get_param( 'status' ) ); $sku = sanitize_text_field( (string) $request->get_param( 'sku' ) ); $args = array( 'status' => '' !== $status ? $status : 'publish', 'limit' => $per_page, 'page' => $page, 'paginate' => true, 'orderby' => 'ID', 'order' => 'ASC', ); if ( '' !== $search ) { $args['s'] = $search; } if ( '' !== $sku ) { $args['sku'] = $sku; } $results = wc_get_products( $args ); $products = array_map( array( $this, 'format_product' ), $results->products ); $this->logger->log( 'get_products', 'inbound', rest_url( self::REST_NAMESPACE . '/products' ), 0, '200', sprintf( 'page=%d perPage=%d total=%d', $page, $per_page, $results->total ), wp_json_encode( $request->get_query_params() ) ); return new WP_REST_Response( array( 'products' => $products, 'page' => $page, 'perPage' => $per_page, 'total' => (int) $results->total, 'totalPages' => (int) $results->max_num_pages, ), 200 ); } /** * Format a WC_Product for the products API response. * * @param WC_Product $product Product. * @return array */ private function format_product( WC_Product $product ) { return array( 'id' => $product->get_id(), 'sku' => $product->get_sku(), 'name' => $product->get_name(), 'status' => $product->get_status(), 'type' => $product->get_type(), 'price' => $product->get_price(), 'regularPrice' => $product->get_regular_price(), 'salePrice' => $product->get_sale_price(), 'stockQuantity' => $product->get_stock_quantity(), 'stockStatus' => $product->get_stock_status(), 'weight' => $product->get_weight(), 'permalink' => $product->get_permalink(), 'dateModified' => $product->get_date_modified() ? $product->get_date_modified()->date( 'c' ) : null, ); } /** * Strip "-BOX"/"-SPLIT" child suffixes to resolve the parent order, * matching getOrderNumberFromOrder() in the original. * * @param string $order_number Order number. * @return string */ private function strip_child_suffix( $order_number ) { foreach ( array( '-box', '-split' ) as $suffix ) { $pos = stripos( $order_number, $suffix ); if ( false !== $pos ) { return substr( $order_number, 0, $pos ); } } return $order_number; } /** * Find a WooCommerce order by its order number. * * @param string $order_number Order number. * @return WC_Order|false */ private function find_order( $order_number ) { // Direct ID first (default WooCommerce order numbers are IDs). $order = wc_get_order( absint( $order_number ) ); if ( $order instanceof WC_Order ) { return $order; } /** * Filter to resolve custom order numbers (e.g. from sequential * order number plugins) to a WC_Order. * * @param WC_Order|false $order Resolved order. * @param string $order_number Order number. */ return apply_filters( 'weship_acs_sync_find_order', false, $order_number ); } }