Square Connect API - image upload - Node.js

2019-08-23 16:38发布

I've spent days trying to successfully upload images with the image_upload endpoint using the Square Connect v1 API. The API docs are here

Currently, I'm getting the following response after making the POST.

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

I'm using the node-request library as such:

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);
      },

Has anybody out there been able to use this endpoint successful using node.js?

2条回答
我只想做你的唯一
2楼-- · 2019-08-23 16:43

The reason you're getting an error is you need to provide binary image data, but you're providing base64 encoded data. You can see an example of how to do it here.

查看更多
别忘想泡老子
3楼-- · 2019-08-23 17:04

After many days of playing around, I finally got it working. Although, in the end, I was not able to make it work without first saving the image to disk, and then posting it to Square. Here is my working snippet:

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);
});
查看更多
登录 后发表回答