Square Connect API - image upload - Node.js

与世无争的帅哥 提交于 2020-01-06 07:15:44

问题


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


来源:https://stackoverflow.com/questions/51289166/square-connect-api-image-upload-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!