2
votes

After creating about 1000 inventory items with code, Square suddenly started returning an error.

The error returned was:

{"type":"bad_request","message":"'name' is required"}

Example code:

$postData = array(
  'id' => 'test_1433281486',
  'name' => 'test',
  'description' => 'test',
  'variations' => array(
    'id' => 'test_v1433281486',
    'name' => 'Regular',
    'price_money' => array(
      'currency_code' => 'USD',
      'amount' => '19800',
    ),
  ),
);
$json = json_encode($postData);

$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $access_token, 'Content-Type: application/json', 'Accept: application/json'));
curl_setopt($curl, CURLOPT_URL, "https://connect.squareup.com/v1/me/items");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
$json = curl_exec($curl);
curl_close($curl);

Here is the json_encoded string:

{
  "id":"test_1433281486",
  "name":"test",
  "description":"test",
  "variations": {
    "id":"test_v1433281486",
    "name":"Regular",
    "price_money": {
      "currency_code":"USD",
      "amount":"19800"
    }
  }
}

I have tried everything I know to do a simple Create Item with code now, but it no longer works. Always returns the message "name" is required. My code to update images, fees, categories etc still works perfectly - just can't create.

I still have 100's of new inventory items to add, so getting this to work is imperative to business.

2

2 Answers

1
votes

Variations needs to be passed in as an array. Here is how the JSON should look:

{
  "id":"test_1433281486",
  "name":"test",
  "description":"test",
  "variations": [{
    "id":"test_v1433281486",
    "name":"Regular",
    "price_money": {
      "currency_code":"USD",
      "amount":"19800"
    }
  }]
}

Thanks for the report! We will update our error messaging to send the proper message if variations is not passed in as an array.

1
votes

This is for all the PHP developers. Here is an updated Create Item PHP array that is compatible with Square. Notice the nested "variations" arrays.

Square now (6/15) requires brackets in JSON arrays - PHP json_encode() does not produce them unless you add nested arrays.

$postData = array(
  'id' => 'test_1433281487',
  'name' => 'test2',
  'description' => 'test2',
  'variations' => array(array(
    'id' => 'test_v1433281487',
    'name' => 'Regular',
    'price_money' => array(
      'currency_code' => 'USD',
      'amount' => '19800',
    ),
  )),
);
$json = json_encode($postData);

Here's another example of JSON brackets in PHP.

Here is the PHP json_encode() documentation.