Search code examples
phpphp-curl

PHP CURL Showing Post Fields Array Error While Other Code Works Fine


I have two php pages running curl code for an API on them.

Page1.php

$fields = array(
        'item' => array(
            'name' => 'Extra Chair',
            'amount' => 2300,
            'currency' => 'USD'
        ),
        'quantity' => '1'
    );

$fields_string = http_build_query($fields);

And then I use this string in CURL shown below. And it works fine and I get a response.

CURLOPT_POSTFIELDS => $fields_string,

Page2.php

$fields = array(
        'plan_id' => 'plan_DiUORv81uf2uyu',
        'total_count' => 120,
        'customer_notify' => true,
        'addons' => array(
            'item' => array(
                'name' => 'Extra',
                'amount' => 2300,
                'currency' => 'USD'
            )
        ),
        'notes' => array(
            'notes_key' => 'Beam me up Scotty'
        )
    );

    $fields_string = http_build_query($fields);

After using it as CURLOPT_POSTFIELDS => $fields_string,, gives error

[description] => addons must be an array

I am doing it as it says in API document example shown HERE.

Document Example:

curl -u <YOUR_KEY_ID>:<YOUR_KEY_SECRET> \
-X POST https://api.razorpay.com/v1/subscriptions \
-H "Content-Type: application/json" \
-d '{
  "plan_id": "plan_00000000000001",
  "total_count": 6,
  "start_at": 1561852800,
  "addons": [
    {
      "item": {
      "name": "Delivery charges",
      "amount": 30000,
      "currency": "INR"
      }
    }
  ],
  "notes": {
    "notes_key": "Beam me up Scotty"
  },
  "customer_notify": 1,
  "expire_by":"1561939199"
}'

Solution

  • As per document you need to enclose one more array before item

    $fields = array(
      'plan_id' => 'plan_DiUORv81uf2uyu',
      'total_count' => 120,
      'customer_notify' => true,
      'addons' => [
        [
          'item' => array(
            'name' => 'Extra',
            'amount' => 2300,
            'currency' => 'USD'
          )
        ]
      ],
      'notes' => array(
        'notes_key' => 'Beam me up Scotty'
      )
    );