Failed to download images from Shopify store using API - Need help troubleshooting (PHP, Laravel)

Failed to download images from Shopify store using API - Need help troubleshooting (PHP, Laravel)

AndrewPomazkov
Visitor
3 0 0

Hi everyone,

 

I'm experiencing an issue when trying to download images from my Shopify store using the API. I have a valid access token for my store and I'm using GuzzleHttp\Client to send requests.

 

Specifically, I'm trying to download images from URLs like https://cdn.shopify.com/s/files/1/.../.../.../files/[IMAGE_NAME].jpg

 

The problem is that Shopify seems to be blocking automatic image downloads through the API. I've tried different approaches, including using GraphQL API and REST interface, but nothing seems to work.

 

Can anyone help me troubleshoot this issue? How can I download images from my Shopify store using the API? I need to keep them locally 

 

Any solution should be safe and reliable.

Code sample:
$this->apiUrl = config('services.shopify.api_url'); 
$this->client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'X-Shopify-Access-Token' => config('services.shopify.access_token'),
],
]);

Then I'm retrieving product data with images. Image urls stored as json in database
All links are correct and can be accessed in the browser
but then I need to download them to local storage:

private function download(array $imageUrls): void
{
foreach ($imageUrls as $url) {
if (! File::exists('./storage/store-images/'.auth()->id())) {
File::makeDirectory('./storage/store-images/'.auth()->id(), 0777, true);
}

$query = "query { image(url: \"$url\") }";
$response = $this->client->post($this->apiUrl , [
'headers' => ['Content-Type' => 'application/json'],
'json' => ['query' => $query],
]);

if ($response->getStatusCode() === 200) {
$responseData = json_decode((string)$response->getBody(), true);
if (isset($responseData['data']['image'])) {
File::put('./storage/store-images/'.basename($url), (string)$responseData['data']['image']);
} else {
logger()->info('Could not download image', (array)$response->getStatusCode());
}
} else {
logger()->info('Could not download image', (array)$response->getStatusCode());
}
}
}
the http code is always 200 if I'm using GraphQL and 403 if I try to download with file_get_contents or storage()->download()

Thanks in advance for your help!

Reply 1 (1)

AndrewPomazkov
Visitor
3 0 0

Solved