Thursday, February 1, 2018

Exchanging credentials for bearer token

Lufthansa API gives bearer token with expiration time. So you need to exchange client secret, client id and grant type for bearer token. Here's the PHP script. Don't forget to place you credentials.


<?php
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL,"https://api.lufthansa.com/v1/oauth/token/");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, 'client_id=****&client_secret=****&grant_type=client_credentials');
 $headers = [
        'Content-Type: application/x-www-form-urlencoded'
 ];
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $data = curl_exec($ch);
 curl_close($ch);

 // Handle response data
 $response = json_decode($data);
 // get bearer token
 $tok = $response->access_token;
 
 $ch = curl_init();
 // end-point
 curl_setopt($ch, CURLOPT_URL,"https://api.lufthansa.com/v1/references/countries/DK?limit=20&offset=0");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $headers = [
     'Accept: application/json',
     'Authorization: Bearer '.$tok,
     'X-Originating-Ip: '.$_SERVER['SERVER_ADDR']
 ];
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $server_output = curl_exec ($ch);
 curl_close ($ch);
 $response = json_decode($server_output,true);
 echo"<pre>"; 
 var_dump($response);

No comments:

Post a Comment