简体   繁体   中英

PHP cURL JSON API

My API documentation says I need to enter the following cURL.

curl

 -H "Accept: application/json"
 -F grant_type=consumer_credentials 
 -F consumer_key=ABCDEFGHIJKLMN
 -F consumer_secret=123456789
 https://sandbox.apps.****.com/api/AccessToken 

I've no idea what to do with the -F bits (nor what -F stands for!) So I put them in as JSON post data.

I assume -H is header?

As a starting point I had this:

$data = array(
  "grant_type" => "consumer_credentials",
  "consumer_key" => "ABCDEFGHIJKLMN",
  "consumer_secret" => "123456789"
);

$str_data = json_encode($data);

$url_send ="https://sandbox.apps.****.com/api/AccessToken";

function sendPostData($url, $post){
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));  
  $result = curl_exec($ch);
  curl_close($ch); 
  return $result;
}

echo " " . sendPostData($url_send, $str_data);

But all I get is a page that says error occurred. It should return JSON with login data.

As Marc said, I was sending through json instead of normal field data.

I put in

foreach($data as $key=>$value) { $str_data .= $key.'='.$value.'&'; }
rtrim($str_data, '&');

instead of

$str_data = json_encode($data);

and it seems to be working now.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM