2017-10-11 200 views
0

我已附加如下功能:在woocommerce_checkout_order_processed钩:woocommerce_checkout_order_processed钩执行功能两次

//check if woocommerce is acive 
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) { 
    add_action('woocommerce_checkout_order_processed', 'wc_on_place_order'); 
} 

wc_on_place_order的功能是在用户点击PLACE ORDER按钮之后执行。但是,这个函数执行两次很奇怪。

wc_on_place_order函数调用C#编写的外部API:

function wc_on_place_order($order_id) { 
    global $wpdb; 

    // get order object and order details 
    $order = new WC_Order($order_id); 

    // get product details 
    $items = $order->get_items(); 
    //return $items; 

    $products = array(); 
    foreach ($items as $item) { 
     array_push($products, 
      array('userid' => $order->user_id, 'descr' => $item['name'], 'amt' => (float)$item['line_total']) 
     ); 
    } 

    //passing $products to external api using `curl_exec` 
    . . . . 

    //on successful call, the page should be showing an `alert`, however, it does not 
    // the handle response  
    if (strpos($response,'ERROR') !== false) { 
      print_r($response); 
    } else { 
     echo "<script type='text/javascript'>alert($response)</script>"; 
    } 
} 

在C#API调试后,我注意到它的服务被称为两次,因此,结账时被保存两次到API数据库。

点击PLACE ORDER时是不是有什么毛病wc_on_place_order功能或者是woocommerce_checkout_order_processed叫了两声?

有趣的是,加入$items = $order->get_items()莫名其妙后return $items,C#的API只调用一次:

// get product details 
$items = $order->get_items(); 
return $items; //this line 

为什么会这样呢?

还有一个问题我想问一下,是woocommerce_checkout_order_processed我应该用右钩子吗?我一直在网上搜索正确的钩子,看起来woocommerce_checkout_order_processed被用在大多数帖子中。我不能使用woocommerce_thankyou挂钩,因为如果我刷新页面,它也会调用api。

任何想法将非常感激。

回答

1

我总是使用挂钩woocommerce_payment_complete这将在顾客支付订单后按顾名思义激发。

function order_payment_complete($order_id){ 
    $order = wc_get_order($order_id); 
    /* Insert your code */ 
} 

add_action('woocommerce_payment_complete', 'order_payment_complete'); 
+0

这有效,但生病会寻找更好的钩子。似乎我不能阻止woocommerce从此钩子重定向到“谢谢”页面 –

+0

您可以在结账后将用户重定向到不同的页面,是否可以解决您的问题? –

+0

我想留在当前页面。请参阅我正在调用外部API以检查当前用户是否在该端点上有余额,然后如果用户没有余额,我想显示错误消息或其他内容。 –