我有一个代码,可以将订单数据发送到外部送货服务,在那里创建新订单。我注意到,如果重新加载“谢谢”页面,该代码将再次起作用并发送相同的信息。结果:在支持服务中创建了几个相同的订单。我应该在代码中添加些什么,以免发生这种情况?
add_action('woocommerce_thankyou', 'send_order_to_delivery');
function send_order_to_delivery( $order_id ){
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
$order_data = $order->get_data();
$order_id = $order_data['id'];
// Send data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://app.example.com/api/index.php?new_order");
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
$decoded = (array) json_decode($result);
// Output
if( isset($decoded['result']) && $decoded['result'] == 'success' && isset($decoded['order_id']) && !empty($decoded['order_id']) ){
update_post_meta( $order_id, 'delivery_order_id', esc_attr( $decoded['order_id'] ) );
}
}
答案 0 :(得分:1)
尝试以下操作,在此检查'delivery_order_id'
meta_key
的订单元数据中是否已经存在某些值,避免两次或多次执行此任务:
add_action('woocommerce_thankyou', 'send_order_to_delivery');
function send_order_to_delivery( $order_id ){
// Checking if this has already been done avoiding reload
if( get_post_meta( $order_id, 'delivery_order_id', true ) )
return; // Exit if already processed
// Get an instance of the WC_Order object
$order_data = $order->get_data();
$order_id = $order_data['id'];
// Send data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://app.example.com/api/index.php?new_order");
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
$decoded = (array) json_decode($result);
// Output
if( isset($decoded['result']) && $decoded['result'] == 'success' && isset($decoded['order_id']) && !empty($decoded['order_id']) ){
update_post_meta( $order_id, 'delivery_order_id', esc_attr( $decoded['order_id'] ) );
}
}
代码进入活动子主题(或活动主题)的function.php文件中。它应该可以彻底解决您的问题。