[SalesForce] How to request rest api after getting access token. php & curl

I am able to authenticate with salesforce and receive a token using php & curl, below. However my next step is to use the token id to query salesforce (e.g objects) and i am not getting anything back. I am new to salesforce, php and rest api's. I have tried several ways, the code below is the last change i made and i get http 400 error.
When i run curl on my terminal (MacOS) with the access token, i get back the json i expect. Any help would be appreciated.

Here is my code:

<?php

$cookie_file = tempnam('./temp', 'cookie');

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, "https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=VRi0wrACym0LPy2siVyKXzCLUzC7mz8TLtMapjl&client_secret=2800232856&username=kathy&password=nottoselfzvrGTNeFWTg7WEWfC1MP&format=json");
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
curl_close($ch);

$json   = json_decode($result);
$atoken = $json->access_token;
echo $atoken;

$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, "https://login.my.salesforce.com/services/data/v26.0/');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization', 'OAuth '+$atoken));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);

$curl_response = curl_exec($ch);
print_r($curl_response);
curl_close($ch);
?>

Best Answer

A few things:

  • You need to use instance_url in the second call
  • String concatenation in PHP uses '.', not '+'
  • As Lex mentioned, the cookie jar is not needed with OAuth or the REST API

So your code for the second call should look like:

curl_setopt($ch, CURLOPT_URL, $json->instance_url . "/services/data/v26.0/');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization', 'OAuth ' . $atoken));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

And I hope that isn't your real client secret. If it is, go reset it, right now!