Uploading Etsy listing images in PHP with Oauth

After figuring out how to upload Etsy listing images in Python for one project, I needed to do the same thing in PHP for another. Despite Etsy itself being implemented in PHP (as far as I know), and the examples in their documentation being in PHP, this turned out to be tricky.

First up, the example for uploading listing images in Etsy’s documentation is plain wrong. It doesn’t work. Don’t waste any more time trying to get that example to work.

I was trying all sorts of different approaches with the PHP Oauth client (which I had working for all other Etsy API requests), but nothing worked. I kept getting a 400 status from the Etsy API with one of these error messages:

  • “The request body is too large”
  • “Image file or image_id string must be included”

In the end I gave up trying to do this directly with the PHP Oauth client, and instead got it working using the old-fashioned PHP curl functions.

This solution does still use the PHP Oauth client to generate the Authorization header, and then the request is made using curl commands.

<?php

$oAuth = new Oauth(
	'{ETSY KEY STRING}',
	'{ETSY SHARED SECRET}',
	OAUTH_SIG_METHOD_HMACSHA1,
    OAUTH_AUTH_TYPE_URI
);
$oAuth->setToken(
    '{OAUTH TOKEN}',
    '{OAUTH TOKEN SECRET}'
);

$authorization = $oAuth()->getRequestHeader('POST', $url);
$headers = ["Authorization: $authorization"];

$listingId = '{LISTING ID}';
$url = "https://openapi.etsy.com/v2/listings/$listingId/images";

$filePath = '{FILE PATH}';
$file = new CURLFile($filePath, 'image/jpeg', basename($filePath));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $file]);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
curl_close($ch);
return $response;

I hope that helps you get your Etsy API integration working!

By the way, if you need help on your project, you can hire me as a freelance Etsy API developer.


View post: Uploading Etsy listing images in PHP with Oauth