Curl php avec authentification Bearer au besoin
function callAPI($method, $url, $data ,$sessionIdToPut ){ $curl = curl_init(); switch ($method){ case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); } $data_header = array('Content-Type: application/json'); if ($sessionIdToPut != NULL){ array_push($data_header,"Authorization: Bearer ".$sessionIdToPut); } // OPTIONS: curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_HTTPHEADER, $data_header); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_PROXY, ''); // EXECUTE: $result = curl_exec($curl); //DEBUG -_> echo 'Erreur Curl : ' . curl_error($curl); if(!$result){die("Connection Failure");} curl_close($curl); return $result; }
Exemple GET :
$make_call = callAPI('GET','https://monurl.com:9043/api/v1/events/',NULL,NULL); $response = json_decode($make_call, true);
Exemple POST
$data_array = array("donnée1" => "valeur1","donnée2" => "valeur2."); $make_call = callAPI('POST','https://monurl.com:9043/api/v1/sessions',json_encode($data_array) ,NULL);
Exemple GET avec Authentification Bearer :
$sessionId=ejejehfrfvhivuihvitrvt-nieucnutnirtnitnct-etnctrjncticn $make_call = callAPI('GET','https://monurl.com:9043/api/v1/events/',NULL,$sessionId); $response = json_decode($make_call, true);