How can we customer metafields via rest api

JayPRajput
Shopify Partner
3 1 0

Hello Guy's
I am facing issue with  customer metafield  and I want to update value from api but i am getting error If someone can help me Thanks

if(isset($_POST['Login_tag']) && isset($_POST['customer_id'])){
$Login_tag = $_POST['Login_tag'];
$customerId = $_POST['customer_id'];

$url = "https://mystore.myshopify.com/admin/api/2023-01/customers/5479815282785.json";

$data = '{"customer":{"id":5479815282785,"metafields":[{"key":"customer_login_tag","value":"login_11","type":"string","namespace":"login_tag_update"}]}]}}';

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"content-type: application/json",
"X-Shopify-Access-Token: {token}"
]);
$response = curl_exec($curl);
curl_close($curl);
echo json_encode($response);
die;
}


Login_Api.png

Reply 1 (1)

garyrgilbert
Shopify Partner
397 40 163

Hi there, 

 

do your self a favor and get friendly with graphQL  once you get the hang of it its way more powerful. See below for example.. Oh and BTW "string" is no longer a valid type for metafields you probably want "single_line_text_field" And you should really be hitting the the metafields.json endpoint not the customer endpoint.

 

e.g. https://mystore.myshopify.com/admin/api/2023-01/customers/5479815282785/metafields.json

and use POST instead of put.

https://shopify.dev/docs/api/admin-rest/2023-01/resources/metafield#post-blogs-blog-id-metafields-ex...

 

mutation metafieldsSet($metafields: [MetafieldsSetInput!]!) {
  metafieldsSet(metafields: $metafields) {
    userErrors {
      field
      message
    }
  }
}

 

 

and then in your case the data would look like this:

 

{
  "metafields": [
    {
      "key": "customer_login_tag",
      "namespace": "login_tag_update",
      "ownerId": "gid://shopify/Customer/[customerid]",
      "type": "single_line_text_field",
      "value": "login_11"
    }
  ]
}

 

Cheers,

 

Gary

- Was my reply helpful? Click Like to let me know!
- Was your question answered? Mark it as an Accepted Solution