Shopify获取客户Metafields

时间:2018-03-01 18:55:40

标签: shopify shopify-app

更新:我有此私有API请求,以获取向shopify管理员发送请求的客户元数据数据。

const {getAccessToken} = require('./auth')
    const request = require('request')
    const {shopFromPermanentDomain} = require('./helpers')

const getCustomerMetafields = ({accessToken, id, shop}) => new Promise((resolve, reject) => {
  request({
    url:`https://${shop}.myshopify.com/admin/customers/${id}/metafields.json',
    headers: {
      'X-Shopify-Access-Token': accessToken
    }
  }, (error, response, body) => {
    const {errors} = JSON.parse(body)

    if (response.statusCode === 200) {
      const { metafields } = JSON.parse(body)
      resolve(metafields)
    }

    reject({error: errors, status: 500})
  })
})

const getCustomerMetafieldsResponse = (req, res) => {
  const {id, permanentDomain} = req.body

  if (id && permanentDomain) {
    const shop = shopFromPermanentDomain(permanentDomain)

    getAccessToken({shop})
      .then(accessToken => getCustomerMetafields({accessToken, id, shop})
        .then(meta => res.json({
          meta,
          status: 200
        }))
      )
      .catch(({error, status}) => res.json({error, status}))
  } else {
    res.json({error: 'Missing params', status: 500})
  }
}

module.exports = getCustomerMetafieldsResponse

我通过以下请求从前端向我的API发出此请求。

const getCustomerMeta = ({
   id,
   permanentDomain
}) => new Promise((resolve, reject) => {
  post({
    params: { email, permanentDomain, task: 'get-customer-meta' },
    then: ({ error, id, state, status }) => {
      if (status === 200) {
        resolve({ id, state })
      }

      reject(error)
    },
    url: '/apps/spoke'
  })
})
    getCustomerMeta({
       id, // 98303739294 (Customer ID)
       permanentDomain // "store.myshopify.com"
    })

发出此请求时,我收到以下请求错误:

 500 (Internal Server Error)

VM706781:8 Uncaught SyntaxError: Unexpected token < in JSON at position 7
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.l.onload

然后,我想获取客户元数据数据,以便我可以使用收集的数据填充前端。

谢谢!

2 个答案:

答案 0 :(得分:0)

您无法在不使用应用代理的情况下从前端调用后端(即)/ admin。在前端,您编写的代码将使用客户ID对您的应用程序进行代理XHR调用。使用该ID,您可以根据您的示例获取客户资源的Metafields,而不是Shop。通过为客户提供Metafields资源,您可以查找您感兴趣的资源,并在前端绘制它们。

或者只使用Liquid渲染已登录客户的元数据,因为这样更简单。

答案 1 :(得分:0)

自从您在2018年问这个问题以来,api可能发生了巨大变化,但是现在您可以通过客户或metafields端点获取客户的metafields。

例如

/admin/api/{api-version-number}/customers/{shopify-customer-id}/metafields.json

直接指向元字段端点的地方是:

/admin/api/{api-version-number}/metafields.json?metafield[owner_id]={shopify-customer-id}&metafield[owner_resource]=customers
相关问题