In the API response when some product prices came as zero, all the item’s prices were set as zero. I could not find the reason for that.
Also, the order has been created although I have added a checkpoint to prevent that order from being placed.
I have used the below code to calculate real-time for both add and update.
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );
function before_calculate_totals( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
$logger = wc_get_logger();
$context = array( 'source' => 'B2BeCONNECT' );
if( is_cart() || is_checkout() ) {
$user_id = get_current_user_id();
$company_id = get_user_meta( $user_id, 'parent', true );
$company_sap_soldto = get_user_meta( $company_id, 'sap_soldto', true );
$current_url = get_option( 'realtime_price_api_url' );
$current_url_update = get_option( 'realtime_price_update_api_url' );
//making array of multiple products
$sku_a = array();
$qty_a = array();
$cart_c = COUNT( $cart_obj->get_cart() );
$quote_nm = WC()->session->get( 'quote_nm_sap' ) ? WC()->session->get( 'quote_nm_sap' ) : "0";
$quote_url = ($quote_nm && $quote_nm != "0") ? $current_url_update : $current_url;
$logger->info('Quote ID'. $quote_nm, $context );
if ($cart_c < 2) {
$skuStructure = '';
foreach ($cart_obj->get_cart() as $key => $value) {
$sku = $value['data']->get_sku();
$qty = $value['quantity'];
$skuStructure .= '{
"discount": "",
"id": 1,
"sku":"' . $sku . '",
"qty": ' . $qty . ',
"plant": ""
}';
$sample_with_quote = '{
"productPriceUpdateCollection": {
"product_skus": {
"item": [' . $skuStructure . ' ]
},
"customer": {
"item": [
{
"role": "AG",
"number": "' . $company_sap_soldto . '"
},
{
"role": "WE",
"number": "' . $company_sap_soldto . '"
},
{
"role": "RE",
"number": "' . $company_sap_soldto . '"
}
]
},
"quote_id": "' . $quote_nm . '",
"discounts": {
"item": {
"type": "",
"value": "",
"cause": ""
}
}
}
}';
// $logger->info('Request Body Structure1: '. $sample_with_quote, $context );
$response = wp_remote_post( $quote_url, array(
'method' => 'POST',
'timeout' => 240,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => $sample_with_quote,
'cookies' => array()
)
);
if (is_wp_error( $response )) {
$logger->info($response->get_error_message(),$context);
wc_print_notice( 'Order cannot be processed. Please refresh the page and try again.','error' );
} else { // Start:If response success
$xml = simplexml_load_string( $response['body'], "SimpleXMLElement", LIBXML_NOCDATA );
$json = json_encode( $xml );
$array = json_decode( $json, TRUE );
if ($quote_nm && $quote_nm != 0) {
WC()->session->set( 'quote_nm_sap', $array['Envelopes']['ZSD_SDOC_CHANGE']['ORDER_NUMBER'] );
$price_arr = $array['Envelopes']['ZSD_SDOC_CHANGE']['ITEM_OUT'];
} else {
WC()->session->set( 'quote_nm_sap', $array['Envelopes']['ZSD_SDOC_CREATE']['ORDER_NUMBER'] );
$price_arr = $array['Envelopes']['ZSD_SDOC_CREATE']['ITEM_OUT'];
}
// $logger->info(wc_print_r( $price_arr), $context );
if ($array && !empty( $price_arr )) {
$price = $price_arr['ROW']['TOTAL'];
$qty = $price_arr['ROW']['QUANTITY'];
if ($qty && $price) {
$value['data']->set_price( ((float)$price / $qty) );
}
} else {
$value['data']->set_price(0);
$logger->info('zero price set', $context );
}
} // End: If response success
}
} else {
foreach ($cart_obj->get_cart() as $key => $value) {
array_push( $sku_a, $value['data']->get_sku() );
array_push( $qty_a, $value['quantity'] );
}
$n = COUNT( $sku_a );
$i = 1;
$l = 0;
$skuStructure = '';
foreach ($sku_a as $sku) {
$q = $qty_a[$l] ? $qty_a[$l] : 1;
if ($i < $n) {
$skuStructure .= '{ "discount": " ", "id": 1, "sku":"' . $sku . '", "qty": ' . $q . ', "plant": "" },';
} else {
$skuStructure .= '{ "discount": "", "id": 1, "sku":"' . $sku . '", "qty": ' . $q . ', "plant": "" }';
}
$i++;
$l++;
}
$sample_with_quote = '{
"productPriceUpdateCollection": {
"product_skus": {
"item": [' . $skuStructure . ']
},
"customer": {
"item": [
{
"role": "AG",
"number": "' . $company_sap_soldto . '"
},
{
"role": "WE",
"number": "' . $company_sap_soldto . '"
},
{
"role": "RE",
"number": "' . $company_sap_soldto . '"
}
]
},
"quote_id": "' . $quote_nm . '",
"discounts": {
"item": {
"type": "",
"value": "",
"cause": ""
}
}
}
}';
// $logger->info('Request Body Structure2: '. $sample_with_quote, $context );
$response = wp_remote_post( $quote_url, array(
'method' => 'POST',
'timeout' => 240,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => $sample_with_quote,
'cookies' => array()
)
);
if (is_wp_error( $response )) {
$logger->info($response->get_error_message(),$context);
wc_print_notice( 'Order cannot be processed. Please refresh the page and try again.','error');
} else { // Start:If response success
$xml = simplexml_load_string( $response['body'], "SimpleXMLElement", LIBXML_NOCDATA );
$json = json_encode( $xml );
$array = json_decode( $json, TRUE );
if ($quote_nm && $quote_nm != 0) {
WC()->session->set( 'quote_nm_sap', $array['Envelopes']['ZSD_SDOC_CHANGE']['ORDER_NUMBER'] );
$price_arr = $array['Envelopes']['ZSD_SDOC_CHANGE']['ITEM_OUT'];
} else {
WC()->session->set( 'quote_nm_sap', $array['Envelopes']['ZSD_SDOC_CREATE']['ORDER_NUMBER'] );
$price_arr = $array['Envelopes']['ZSD_SDOC_CREATE']['ITEM_OUT'];
}
// $logger->info( wc_print_r( $price_arr, true ), $context );
$j = 0;
foreach ($cart_obj->get_cart() as $key => $value) {
//$logger->info('SKU: '.$value['data']->get_sku(), $context );
if ($array && !empty( $price_arr['ROW'] )) {
$price = $price_arr['ROW'][$j]['TOTAL'];
$qty = $price_arr['ROW'][$j]['QUANTITY'];
if ($qty && $price) {
$value['data']->set_price( ((float)$price / $qty) );
}
} else {
$value['data']->set_price(0);
$logger->info('zero price set', $context );
}
$j++;
}
} // End: If response success
}
}
}
To restrict an order being placed used the below code
add_action('woocommerce_checkout_create_order', 'cancel_order_if_zero_total', 10, 2);
function cancel_order_if_zero_total($order, $data) {
$cart = WC()->cart;
$cart_total =round($cart->get_total( 'edit' ) );
$logger = wc_get_logger();
$context = array( 'source' => 'B2BeCONNECT' );
$logger->info( 'Cart total '.$cart->get_total( 'edit' ), $context );
$customer_id=$cart->get_customer()->id;
$company = get_user_meta($customer_id,'parent', true);
foreach ($cart->get_cart() as $cart_item_key=>$cart_item){
$product_price = $cart_item['data']->get_price();
if( empty($product_price) || $product_price == 0) {
$product_id = $cart_item['product_id'];
$logger->info( 'For Company Id ('.$company.'), Product Id (' . $product_id . ') Price not found. ' . $product_price, $context );
$error_text = __( "Order cannot be processed. Please refresh the page and try again.", "wocommerce" );
throw new Exception( $error_text );
}
}
if($cart_total == 0) { // Throw an error notice
$logger->info( 'For Company Id ('.$company.'), Order total is zero: '.$cart_total, $context );
$error_text = __("Order cannot be processed. Please refresh the page and try again.", "wocommerce" );
throw new Exception( $error_text );
} else {
return $order;
}
}