REST call to Microsoft Graph - rest

I have got my access token but I am struggling to see how you then send the request for the data required. In the example Call Microsoft Graph they have:
GET
https://graph.microsoft.com/v1.0/me/messages?$select=subject,from,receivedDateTime&$top=25&$orderby=receivedDateTime%20DESC
Accept: application/json Authorization: Bearer token
But what is the method for parsing the Accept: and the Authorization: to Microsoft Graph?
I have tried as a POST but it says bearer token empty.
$token=$_SESSION['$token'];
$url = 'https://graph.microsoft.com/v1.0/me/calendarview?startdatetime=2018-02-08T18:29:54.171Z&enddatetime=2018-02-15T18:29:54.171Z';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
Authorization => 'Bearer ' . $token,
Content-Type => 'application/json'
)
)
);
$resp = curl_exec($curl);
curl_close($curl);

Use the provided graphServiceClient
// Create Microsoft Graph client.
try
{
graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await GetTokenForUserAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
return graphClient;
}
Use that to authenticate your request.
$request = 'https://graph.microsoft.com/v1.0/me/calendarview?startdatetime=2018-02-08T18:29:54.171Z&enddatetime=2018-02-15T18:29:54.171Z';
hrm = new HttpRequestMessage(HttpMethod.Get, request);
// Authenticate (add access token) our HttpRequestMessage
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);
// Send the request and get the response.
response = await graphClient.HttpProvider.SendAsync(hrm);
jsonString = await response.Content.ReadAsStringAsync();

Related

Symfony HttpClient, fail to authenticate external API witch Bearer

I have a problem, I try to use a external API, but the response of that APi is a 401.
1º- I send a request to get the auth token, works fine.
$auth = $this->client->request(
'POST',
'https://api.namebright.com/auth/token',
[
'body' => [
'grant_type' => 'client_credentials',
'client_id' => $clientID,
'client_secret' => $clientSecret,
],
]
);
2º- handler token, i dump the token is loocks fine
$token = sprintf('Bearer %s', $auth->toArray()['access_token']);
3º- I make other request to get the API response, i got a 401.
$response = $this->client->request(
'GET',
'http://api.namebright.com/rest/purchase/availability/google.pt',
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => $token,
],
]
);
I don't know what i'm doing wrong. :(
I checked, for responses on the internet and i don't see the problem.
I Tried to change Authorization to authorization.
I tried to check the token in the postmen, works fine.

guzzle3 add token Post Request

I am working on a project using an old version of Guzzle (version 3), I'd like to add a token to the post request, can't find how to do it, I have looked on the doc there is no example for that , here is what I tried so far :
<?php
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => ['Bearer', $token]
));
$req = $client->post($url);
$client->send($req)->getBody(true);
?>
$client->setDefaultOption('auth', array(null, 'Bearer'.$token ))
I keep getting :
Guzzle\Http\Exception\ClientErrorResponseException: Client error response [status code] 400 [reason phrase] Bad Request [url]
I found the solution :
`$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
));`
So instead of array in Authorization I sent a string that contains the token

Guzzle getBody() after request return posted body

I'm using Guzzle 6.3. I'm trying to post a data with a header.
This is my code:
$headers = [
'content-type' => 'application/json',
'Accept' => 'application/json'
];
$request = new Psr7\Request('post', 'product', $headers, json_encode($data));
$res = $this->http->send($request);
$resData = json_decode($res->getBody(), true);
The response body ($resData) is always equal to the posted one ($data).
Thank you.
Try
$resData = json_decode($res->getBody()->getContents(), true);
Otherwise (if it doesn't help) check what your API endpoint returns.

JWT: Why am I always getting token_not_provided?

I am sending a PUT request to an API endpoint I have created. Using jwt, I am able to successfully register and get a token back.
Using Postman, my request(s) work perfectly.
I am using Guzzle within my application to send the PUT request. This is what it looks like:
$client = new \Guzzle\Http\Client('http://foo.mysite.dev/api/');
$uri = 'user/123';
$post_data = array(
'token' => eyJ0eXAiOiJKV1QiLCJhbGc..., // whole token
'name' => 'Name',
'email' => name#email.com,
'suspended' => 1,
);
$data = json_encode($post_data);
$request = $client->put($uri, array(
'content-type' => 'application/json'
));
$request->setBody($data);
$response = $request->send();
$json = $response->json();
} catch (\Exception $e) {
error_log('Error: Could not update user:');
error_log($e->getResponse()->getBody());
}
When I log the $data variable to see what it looks like, this is what is returned.
error_log(print_r($data, true));
{"token":"eyJ0eXAiOiJKV1QiL...","name":"Name","email":"name#email.com","suspended":1}
Error: Could not suspend user:
{"error":"token_not_provided"}
It seems like all data is getting populated correctly, I am not sure why the system is not finding the token. Running the "same" query through Postman (as a PUT) along with the same params works great.
Any suggestions are greatly appreciated!
The token should be set in the authorization header, not as a post data parameter
$request->addHeader('Authorization', 'Basic eyJ0eXAiOiJKV1QiL...');

Getting token works, but making payment not

I'm making a class to make a payment with paypal.
Getting a token via the function getToken() works and it spits out a good response (according to the documentation).
However, when I'm using that token to build up a payment with the same sendAPICall() used for the token; it only returns a empty string (according to var_dump() ).
If I copy the exact curl command from the api-information and paste the beare-token; it works. So something is wrong with my API call....
Clearly I'm missing something. Could anyone point me to the error?
The function which gets the Bearer-token:
public function getToken(){
$headers = array(
"Accept-Language" => 'en_US',
"Accept" => "application/json"
);
$t = json_decode($this->sendAPICall('grant_type=client_credentials', '/oauth2/token', $headers, true));
if($t->error){
$this->error = $t->error_description;
$this->token = NULL;
return false;
}else{
$this->token = $t;
return true;
}
}
The function which should make the payment after checking there is a token available.
public function makePayment(){
$this->getToken();
if($this->error){
return false;
}else{
$d = '{"intent":"sale",
"redirect_urls":{
"return_url":"'.$this->config['returnURL'].'",
"cancel_url":"'.$this->config['cancelURL'].'"
},
"payer":{
"payment_method":"paypal"
},
"transactions":[
{
"amount":{
"total":"'.$this->amount.'",
"currency":"'.$this->config['currency'].'"
},
"description":"'.$this->description.'"
}
]
}';
$headers = array( "Authorization" => $this->token->token_type . ' ' . $this->token->access_token,
"Content-type" => "application/json"
);
return $this->sendAPICall(urlencode($d), '/payments/payment', $headers, false);
}
}
And off course the connection with the paypal API, where I'm using the $auth boolean to make the difference between sending the userpwd or using the token:
private function sendAPICall($data, $url, $headers, $auth=true){
$ch = curl_init();
$options = array( CURLOPT_URL => $this->config['endpoint'].$url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true
);
if($auth){
$options[CURLOPT_USERPWD] = $this->config['client_id'].':'.$this->config['client_secret'];
};
curl_setopt_array($ch, $options);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
return curl_exec($ch);
}
It does not look like this code snippet is passing HTTP headers correctly. CURLOPT_HTTPHEADER takes a unideimensional array with values of the form "headername: value". You need
$headers = array(
"Authorization: " . $this->token->token_type . ' ' . $this->token->access_token,
"Content-type: application/json"
);
Also consider
Checking for curl_errno($ch) / curl_error($ch) and the HTTP response code (curl_getinfo($ch, CURLINFO_HTTP_CODE)) to see if the call was successful.
Creating the request data as an associative array and using json_encode($data) when calling sendAPICall(). This is far easier than manipulating JSON strings manually.