I'm building an app that would need to add metafields to an Order when it is being created.
Is the above possible? If not, could you recommend a way in which this can be achieved using the current API?
Unless you create the orders yourself via API (and add the metafields then), I see no opportunity to have the metafields added between the order creation and order/create webhook triggering.
For future users - yes, you can add metadata to an existing order that was created through the normal order flow and not the API. You'd be forgiven for thinking you couldn't as the docs only mention Product meta and Shop meta.
This Stackoverflow answer pointed me in the right direction. My example is in PHP but you get the idea. Works perfectly;
$orderMetaJson = array( "metafield" => array( "namespace" => "custom_fields", "key" => "my_meta_key", "value" => "my_meta_value", "value_type" => "string" ) ); $json = json_encode($orderMetaJson); $requestUrl = 'https://firstname.lastname@example.org/admin/orders/' . $order->id . '/metafields.json'; $ch = curl_init($requestUrl); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($json)) ); $curlResult = curl_exec($ch); curl_close($ch);
It's probably worth clarifying the statement about not using the url with the API key in it.
If (as in the example above written in PHP), you are using it in a method on a server side script ... then there is no problem using urls with API keys in them. That's what they were designed for.