2

I am trying to echo a portion of my JSON response from the Plaid API.

Here is the code:

$data = array(
            "client_id"=>"test_id",
            "secret"=>"test_secret",
            "public_token"=>"test,fidelity,connected");
        $string = http_build_query($data);

    //initialize session
    $ch=curl_init("https://tartan.plaid.com/exchange_token");

    //set options
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //execute session
    $exchangeToken = curl_exec($ch);
    echo $exchangeToken;
    $exchangeT = json_decode($exchangeToken);
    echo $exchangeT['access_token'];
    //close session
    curl_close($ch);

Here is the response:

{ "sandbox": true, "access_token": "test_fidelity" }

I also get a 500 Internal Server Error, which results from the echo $exchangeT line. I want to take the access_token portion of the JSON response, echo it to verify, and eventually save it to a database.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Jepf
  • 87
  • 2
  • 10
  • 1
    A 500 error is the webservers way of saying "I have a major problem, but I don't want to talk about it in public". Look at the error log of the server, there will be a clear message saying what's wrong. – Gerald Schneider Jul 21 '16 at 12:31

3 Answers3

3

If you pass true as second parameter in your json_decode then you will get an array instead of object so change this

     $exchangeT = json_decode($exchangeToken, true);
// it wii output as $exchangeT = array('sandbox'=>true,'access_token'=>'test_fidelity');
        echo $exchangeT['access_token'];

for more info read http://php.net/manual/en/function.json-decode.php

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
2

And the function signature:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

From the function definition, you can see that the second argument $assoc is by default false. What this argument does (and it's name suggests), is that when TRUE, returned objects will be converted into associative arrays.

So, in your case,

$exchangeToken = json_decode($exchangeToken, true);

should do what you need.

1

just pass true as second parameter, json_decode() returns in array format instead of object if second parameter is true.

 $exchangeT = json_decode($exchangeToken, true);
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42