autoship_qpilot_orders_update (function)
(src/api.php) Creates a WooCommerce Order (when a QPilot Scheduled Order processes) if one does not exist. Takes the $request as a parameter and returns the $response (or error).
Function
/** * Creates an WC Order if it doesn't already exist, * * @param WP_REST_Request $request Request data. * @return WP_Error|WP_REST_Response */ function autoship_qpilot_orders_update( $request ) { // Confirm WC Rest is available if ( class_exists( 'WC_REST_Orders_Controller' ) ){ $json = $request->get_json_params(); $metas = isset( $json['meta_data'] ) && !empty( $json['meta_data'] ) ? $json['meta_data'] : array(); $scheduled_order_processing_id = ''; foreach ($metas as $meta ) { if ( '_qpilot_scheduled_order_processing_id' == $meta['key'] ){ $scheduled_order_processing_id = $meta['value']; break; } } // If there is a Processing ID Check for Existing Orders if ( !empty( $scheduled_order_processing_id ) ) { // Get the orders from WC_orders. $orders = wc_get_orders( array( '_qpilot_scheduled_order_processing_id' => $scheduled_order_processing_id ) ); //the order exists, it's a duplicate if ( !empty( $orders ) ){ // Get and Update the QPilot Site Meta $sitemeta = $orders[0]->get_meta( '_qpilot_site_meta' ); // Update the Site Meta $sitemeta = autoship_qpilot_get_sitemeta( $sitemeta ); // Add QPilot Autoship Version to Order Meta as well as any additional tracking. $orders[0]->add_meta_data( '_qpilot_site_meta', $sitemeta , true ); return new WP_Error( 'duplicate_order', __( 'Order has already been created from scheduled order processing.', 'autoship' ), array( 'status' => 400, 'order' => json_encode( array_values( $orders )[0]->get_data() ) ) ); } } // Allow others to hook in and modify QPilot data for new orders being created via the rest api. $request = apply_filters('autoship_qpilot_orders_via_rest', $request, $request ); // Since this order doesn't exist create it using the WC Rest Controller. $controller = new WC_REST_Orders_Controller; $response = $controller -> create_item( $request ); return $response; } else { return new WP_Error( 'woocommerce_rest_unavailable', __( 'The WooCommerce REST API is either unavailable or not found.', 'autoship' ), array( 'status' => 500 ) ); } }