Catalog Image can't be exported using Api in PHP

Hi,
I am exporting products from php site to square using Batch upsert catalog objects in Catalog Api. But product image is not exported. Tried to export using Create a catalog image function. But that is not available in PHP. Can you pls let me know how can i create catalog image from php

Hi @athiraarun welcome to the forums!

Unfortunately CreateCatalogImage endpoint is not supported by our SDKs. You can take a look at our Code Cookbook to see how to implement it yourself, though.

In PHP I would highly recommend using something like Guzzle rather than cURL (I’ve never had success with creating an image just using cURL in PHP). Let me know if you run into any issues.

$client = new \GuzzleHttp\Client();
$response = $client->request(‘POST’, ‘https://connect.squareupsandbox.com/v2/catalog/images’,[
‘headers’ => [
‘Accept’ => ‘application/json’,
‘Content-type’ => ‘multipart/form-data’,
‘Square-Version’ => ‘2019-05-08’,
‘Authorization’ => 'Bearer ’ . ‘{ACCESS_TOKEN}’,
],
‘multipart’ => [
[
‘name’ => ‘idempotency_key’,
‘contents’ => ‘GhTjBsOe1tvB0LSd’,
‘headers’ => [ ‘Content-Type’ => ‘application/json’]
],
[
‘name’ => ‘image_file’,
‘contents’ => fopen( ‘https://www.jimiamy.com/wp-content/uploads/2019/09/77f4c4b32d8dae16dbacaa0e8d440cad.jpg’, ‘r’ ),
]
],

                                                             ]);
                                
                                
                                echo $response->getBody();

Replaced with sandbox access token. But it is showing Error 400 Bad Request. Could you pls help me to fix this issue

The issue here appears to be that in your multipart section, you’re encoding the idempotency key instead of the full JSON “request”. I’m kind of rusty on my PHP, but I believe you should follow something that looks more like this:

$client = new \GuzzleHttp\Client([
  // Use https://connect.squareupsandbox.com for sandbox
  'base_uri' => 'http://connect.squareup.com'
]);

$request_data = json_encode([
  'idempotency_key' => 'some unique key',
  'object_id' => "CatalogItem ID",
  'image' => [
      'id' => '#TEMP_ID',
      'type' => 'IMAGE',
      'image_data' => [
        'name' => 'My picture'
        'caption' => 'A picture of a cup of coffee'
      ]
  ]
]);

$response = $client->request('POST', '/v2/catalog/images', [
  'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer ACCESS_TOKEN',
    'Square-Version' => '2020-04-22'
  ],
  'multipart' => [
    [
      'name' => 'request',
      'contents' => $request_data
    ],
    [
      'name' => 'file',
      'contents' => fopen('/path/to/file', 'r')
    ]
  ]
]);

echo $response->getBody();

It worked.Appreciate your help.Thanks a lot!!!

1 Like