'WooCommerce how to update order meta data key value with woo rest api 3

I've been searching around but can't get it to work.

Using the api v3 I'm able to get all orders and everything is ok, but now I need to be able to update a metadata, when I use insomnia I manage to update the metadata, but now I need to do it from a php script but it just won't work.

with insomnia using put.

{ "meta_data": [ { "key": "_mensajero", "value": "juan carlos" } ]}

and it works and update order meta, but with php no matter what I try I cannot get it to update

<?php
 if (isset($_POST['btn-update'])) {
 $oid = $_POST['cId']; /////the order id
 $data =  [
  'meta_data' => [
    '_mensajero' => '_mensajero'
    
    ]
   ];

   $woocommerce->put('orders/' . $oid,  $data);
  header('Location: #');
   }

?>  


Solution 1:[1]

There are multiple ways to update the meta data. One common way would be to use the order object and one of its methods called update_meta_data. Like this:

if (isset($_POST['btn-update'])) 
{

    $oid = absint($_POST['cId']); // the order id

    if($oid)
    {
        $order = wc_get_order($oid);

        if($order)
        {

            $order->update_meta_data('_mensajero', '_mensajero');

            $order->save();

            // Do what ever you want here

        }else{

            die('NO ORDER WITH THE PROVIDED ID FOUND!');
            
           // OR send back a custom error message using 'wp_send_json_error' function
            
        }

    }else{

        die('NO ORDER ID RECIEVED!');

        // OR send back a custom error message using 'wp_send_json_error' function

    }
    
}

Another way of updating meta data using update_post_meta function:

if (isset($_POST['btn-update'])) 
{

    $oid = absint($_POST['cId']); // the order id

    if($oid)
    {
        $order = wc_get_order($oid);

        if ($order) {

            update_post_meta($oid, '_mensajero', '_mensajero');

            // Do what ever you want here

        } else {

            die('NO ORDER WITH THE PROVIDED ID FOUND!');

            // OR send back a custom error message using 'wp_send_json_error' function
        }

    }else{

        die('NO ORDER ID RECIEVED!');

        // OR send back a custom error message using 'wp_send_json_error' function
    }
    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1