Woocommerce钩在下订单后,处理订单之前检查库存/取消订单

时间:2018-12-27 20:20:26

标签: php wordpress woocommerce hook-woocommerce

我正在使用另一个插件扩展WooCommerce。单击下订单后,我正在检查购物车中的物品库存。然后,我根据从第三方API调用返回的数量更新库存。当库存数量少于订购数量时,订单仍在完成。

我正在使用woocommerce_checkout_order_processed钩子,并且还尝试过使用woocommerce_create_order。在这两种方法中,我都能使用第三方API返回的数量成功更新产品的数量。即使产品缺货,两个钩子仍导致订单仍在处理中的不良行为。我想知道是否应该改用woocommerce_after_checkout_validation,但是我不确定如何实现它。

add_action( 'woocommerce_checkout_order_processed', $plugin_extension, 'woo_integrator_check_stock_before_processing_order', 1, 1 );    

public function woo_integrator_check_stock_before_processing_order ( $order_id ) {
$order = wc_get_order ( $order_id );
$items = $order->get_items();
$item_qty_sku = array();

foreach( $items as $key => $item){
    $product = wc_get_product($item['product_id']);
    $item_qty_sku[] =  array(
        'SKU' => $product->get_sku(),
        'Name' => $product->get_name(),
        'Quantity' => $item['qty']
    );
}

// to test out the API, set $api_mode as ‘sandbox’
$api_mode = 'sandbox';
if($api_mode == 'sandbox'){
    // sandbox URL example
    $endpoint = "sandbox.com/endpoint"; 
}
else{
    // production URL example
    $endpoint = "production.com/endpoint"; 
}

// setup the data which has to be sent
$data = new stdClass();
$data = json_encode($item_qty_sku);

// send API request via cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('content-type: application/json',));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec ($ch);

curl_close ($ch);
$json = json_decode($response);

// the handle response    
if (strpos($response,'ERROR') !== false) {
    print_r($json);
} 
else {
    // success
   foreach($json as $key => $json_product){
        foreach( $items as $key => $item ){
            $product = wc_get_product($item['product_id']);
            if( $product->get_sku() == $json_product->SKU ){
                if( $item['qty'] != $json_product->Quantity){
                    $product->set_stock_quantity($json_product->Quantity);
                    $product->save();
                    }
                }
            }           
        }
    }
}

预期:如果从API返回的产品库存数量少于尝试订购的数量,则订购失败。

实际:即使从API返回的产品数量少于尝试订购的数量,订单也会完成。产品库存数量为负值。

实际示例:某些产品的订单5。 API返回的库存只有3个。订单完成。现在,WooCommerce中该产品的库存数量为-2。

预期示例:某些产品的订单5。 API返回的库存只有3个。订单失败。现在,WooCommerce中该产品的库存数量为3。

0 个答案:

没有答案
相关问题