问题
How to save the order id from delivery service in metadata?
add_action('woocommerce_thankyou', 'send_order_to_delivery');
function send_order_to_delivery( $order_id ){
// Send data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://app.axample.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);
$json = '$result';
$delivery_order_id = json_decode($json)->order_id;
if ( ! empty( $_POST['delivery_order_id'] ) ) {
update_post_meta( $order_id, 'delivery_order_id', sanitize_text_field( $_POST['delivery_order_id'] ) );
}
}
When I send the order to an external delivery service, I get the answer echo $result;
-
{"result":"success","order_id":100888,"order_number":10}
Need save "order_id":100888
for this new order.
回答1:
Try the following instead
add_action('woocommerce_thankyou', 'send_order_to_delivery');
function send_order_to_delivery( $order_id ){
// Send data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://app.axample.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);
// Test 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'] ) );
}
}
Code goes in function.php file of your active child theme (or active theme). It should works.
来源:https://stackoverflow.com/questions/51061953/save-received-data-to-the-order-from-an-external-delivery-service-in-woocommerce