Square Connect API - image upload - Node.js

2019-08-23 16:53发布

问题:

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?

回答1:

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.



回答2:

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