Add metafield to Order right when it is placed and view metafield in webhook.

Highlighted
New Member
1 0 0

Hi,

I'm building an app that would need to add metafields to an Order when it is being created.

For Example:

  1. Customer adds products to cart
  2. Customer completes checkout
  3. Order is placed
  4. Can metafields be added at this point before the webhook is triggered?
  5. My app gets the Order webhook and I would like to access the metafields I added

Is the above possible? If not, could you recommend a way in which this can be achieved using the current API?

Thanks!

0 Likes
Highlighted
Shopify Partner
110 3 20

Hi, 

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.

Bogdan | WebShopAssist
User friendly apps with top-rated support
- SKUGen the SKU generator
- DPD Integration
1 Like
Highlighted
Shopify Partner
4 0 2

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://api_key@yoursite.myshopify.com/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);
1 Like
Highlighted
Shopify Expert
5 0 0

API keys should not be part of the request URL, which is why an authenticated app using the API is the preferred method.

0 Likes
Highlighted
Shopify Partner
4 0 2

It's probably worth clarifying the statement about not using the url with the API key in it.

 

Don't expose API keys on the frontend peeps.  So you wouldn't use these urls in Javascript.

 

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. 

0 Likes