gpt4 book ai didi

php - 防止在 Woocommerce 谢谢钩子(Hook)中多次处理数据

转载 作者:行者123 更新时间:2023-12-02 03:33:35 25 4
gpt4 key购买 nike

我有代码将订单数据发送到外部送货服务,并在那里创建新订单。我注意到,如果您重新加载“谢谢”页面,代码将再次工作并发送相同的信息。结果:在支持服务中创建了多个相同的订单。我应该在代码中添加什么才能避免这种情况发生?

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'] ) );
}
}

最佳答案

尝试以下操作,我们检查 '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 文件中。它应该能彻底解决您的问题。

关于php - 防止在 Woocommerce 谢谢钩子(Hook)中多次处理数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com