13

I need to integrate an API so I write function:

public function test() {

    $client = new GuzzleHttp\Client();

try {
    $res = $client->post('http://example.co.uk/auth/token', [

    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
            ],

    'json' => [
        'cliend_id' => 'SOMEID',
        'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
        'grant_type' => 'client_credentials'
]
            ]);

$res = json_decode($res->getBody()->getContents(), true);
dd($res);

}
catch (GuzzleHttp\Exception\ClientException $e) {
        $response = $e->getResponse();
        $result =  json_decode($response->getBody()->getContents());

    return response()->json(['data' => $result]);

    }

}

as a responde I got message:

{"data":{"error":"invalid_clientId","error_description":"ClientId should be sent."}}

Now when I try to run the same url with same data in POSTMAN app then I get correct results:

enter image description here

What is bad in my code? I send correct form_params also I try to change form_params to json but again I got the same error...

How to solve my problem?

Aleks Per
  • 1,181
  • 4
  • 22
  • 53

1 Answers1

30

The problem is that in Postman you're sending the data as a form, but in Guzzle you're passing the data in the 'json' key of the options array.

I bet that if you would switch the 'json' to 'form_params' you would get the result you're looking for.

$res = $client->post('http://example.co.uk/auth/token', [
    'form_params' => [
        'client_id' => 'SOMEID',
        'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
        'grant_type' => 'client_credentials'
    ]
]);

Here's a link to the docs in question: http://docs.guzzlephp.org/en/stable/quickstart.html#sending-form-fields

Also, I noticed a typo - you have cliend_id instead of client_id.

Dylan Pierce
  • 3,147
  • 1
  • 26
  • 35