Square Connect API-图片上传-Node.js

时间:2018-07-11 15:23:36

标签: node.js multipartform-data square node-request

我花了数天时间尝试使用Square Connect v1 API使用image_upload端点成功上传图像。 API docs are here

当前,我在进行POST后收到以下响应。

{"type":"bad_request","message":"Could not create image"}

我正在这样使用节点请求库:

const formData = {
      image_data: {
        value: BASE64IMAGE,
        options: {
          'Content-Disposition': 'form-data',
          filename: 'hat.jpg',
          'Content-Type': 'image/jpeg',
        },
      },
    };
    request.post(
      {
        method: 'POST',
        url: `https://connect.squareup.com/v1/${location}/items/${item_id}/image`,
        headers: {
          Authorization: `Bearer ${access_token}`,
          'Content-Type': 'multipart/form-data; boundary=BOUNDARY',
          Accept: 'application/json',
        },
        formData,
      },
      (err, httpResponse, body) => {
        if (err) {
          return console.error('upload failed:', err);
        }
        console.log('Upload successful!  Server responded with:', body);
      },

有没有人能够通过node.js成功使用此端点?

2 个答案:

答案 0 :(得分:0)

出现错误的原因是需要提供二进制图像数据,但是要提供base64编码数据。您可以看到有关如何进行此操作的示例here

答案 1 :(得分:0)

经过几天的玩耍,我终于开始工作了。尽管最后,如果没有先将图像保存到磁盘,然后将其发布到Square,我将无法使其工作。这是我的工作片段:

let mimeOptions = {
 'Content-Disposition': 'form-data',
 filename: 'photo.jpg',
 'Content-Type': 'image/jpeg',
};
if (type === 'png') {
 mimeOptions = {
  'Content-Disposition': 'form-data',
  filename: 'photo.png',
  'Content-Type': 'image/png',
 };
}

const options = {
 url: shopifyImage.src,
 dest: `${__dirname}/temp/${uuid()}.${type}`,
};

download
 .image(options)
 .then(({ filename, image }) => {
  const formData = {
    image_data: {
      value: fs.createReadStream(filename),
      options: mimeOptions,
    },
  };
  request.post(
    {
      method: 'POST',
      url: `https://connect.squareup.com/v1/${squareCredentials.location_id}/items/${
        squareProduct.catalog_object.id
      }/image`,
      headers: {
        Authorization: `Bearer ${squareCredentials.access_token}`,
        'Content-Type': 'multipart/form-data; boundary=BOUNDARY',
        Accept: 'application/json',
      },
      formData,
    },
    (err, httpResponse, body) => {
      fs.unlink(filename, () => {});
      if (err) {
        return console.error('upload failed:', err);
      }
    },
  );
})
.catch((err) => {
  console.error(err);
});