Office365 OAuth - Token via CURL - php

I'm trying to connect to the Azure platform to grab a response, mainly to get the token for use when accessing an office365 mailbox
The following is what i'm using, but I always get a NULL response
What other CURLOPT_POSTFIELDS need to be included, or what else needs to be changed.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://login.microsoftonline.com/".$tennantid."/oauth2/v2.0/authorize",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'client_id='.$appid.'&response_type=token&scope=https://graph.microsoft.com/User.Read&redirect_uri='.$uri,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded'
),
));
$response = curl_exec($curl);
$response_decode = json_decode($response);
var_dump($response_decode);
curl_close($curl);
I currently get the token back ok when I use the following method
$params = array ('client_id' =>$appid,
'redirect_uri' =>$uri,
'response_type' =>'token',
'response_mode' =>'form_post',
'scope' =>'https://graph.microsoft.com/User.Read',
'state' =>$_SESSION['state']);
header ('Location: '.$login_url.'?'.http_build_query ($params));
Which works fine.
But I need to do CURL method as I need this running background cron job task
What do I seem to be missing?
Thanks in advance

A link to the API documentation may have helped. Without that I cannot help much. Just one obvious thing.
You are using Content-Type: application/x-www-form-urlencoded
You are not encoding the data. From MDN:
application/x-www-form-urlencoded: the keys and values are encoded in
key-value tuples separated by '&', with a '=' between the key and the
value. Non-alphanumeric characters in both keys and values are percent
encoded: this is the reason why this type is not suitable to use with
binary data (use multipart/form-data instead)
Source: MDN Post data
This would mean your request data should look like this:
client_id%3D1234%26response_type%3Dtoken%26scope%3Dhttps%3A%2F%2Fgraph.microsoft.com%2FUser.Read%26redirect_uri%3Dhttp%3Aexample.com
Try this:
$post = urlencode('client_id='.$appid.'&response_type=token&scope=https://graph.microsoft.com/User.Read&redirect_uri=http:example.com');
CURLOPT_POSTFIELDS => $ post,

Related

Unable to POST data TO REST API Using PHP CURL but it work fine with Postman

I am trying to post a data to REST API using PHP/CURL and seems it's not working, as i get 301 Moved Permanently error,But it works fine with Postman. Here is the snippet of PHP CURL which i generated form Postman
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'api url',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('text' => 'test'),
CURLOPT_HTTPHEADER => array(
'api_key: key',
'Content-Type:application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
And it always return 301 Moved permanently, Note if i change the API key i got Unauthorised error, which means it hits the server, but i am not sure what i am missing, I have tried with multiple headers combinations.
Any help on this regard would be highly appreciated.
Quoting the PHP manual :
CURLOPT_POSTFIELDS: This parameter can either be passed as a urlencoded
string like 'para1=val1&para2=val2&...' or as an array with the field
name as key and field data as value. If value is an array, the
Content-Type header will be set to multipart/form-data.
Since you use array you'll need to use multipart.
See this post : curl POST format for CURLOPT_POSTFIELDS

Issues creating a PHP webhook for Twilio

So I have the following CURL command in PHP, if I send it https://webhook.site I can extract all the required data in JSON format.
Instead of using webhook.site, I would like to create my own PHP webhook client.
The code below is the CURL command that works 100% when using webhook.site:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://webhook.site/832090f1-f54f-4847-8c0d-5ec9208541a1',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('SmsSid' => 'SMe8723661742d423fbf3fa9f7bbede050','SmsStatus' => 'sent','MessageStatus' => 'sent','ChannelToAddress' => '+1788123XXXX','To' => 'whatsapp:+15196978899','ChannelPrefix' => 'whatsapp','MessageSid' => 'SMe8723661742d423fbf3fa9f7bbede050','AccountSid' => 'AC306a09582e77715b0eb72df90de4c590','StructuredMessage' => 'false','From' => 'whatsapp:+154xxxxxx','MediaUrl0' => 'https://api.twilio.com/2010-04-01/Accounts/werwersdsdg72df90de4c590/Messages/wweugryuwyr7762b11ea/Media/wjeruwiy6243742
'),
CURLOPT_HTTPHEADER => array(
'user-agent: TwilioProxy/1.1',
'host: Postman'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I then tried to use PHP to create a basic webhook just to pull the data:
<?php
if($json = json_decode(file_get_contents("php://input"), true)){
$data = $json;
$fp = file_put_contents( 'request.log', $data );
}
print_r($data);
?>
But I keep coming with a blank request.log file - what am I doing wrong??? Thanks in advance
Twilio developer evangelist here.
By default, curl will make a POST request with the Content-Type header application/x-www-form-urlencoded. This is actually the same content type that Twilio uses when it sends a webhook request.
Your PHP to receive the request is trying to json_decode the data, which won't work with form encoded data. Instead, you can access $_POST to get an associative array of the parameters sent to your script. You can then write them to a log file however you like.

How to send the content of SSL-related files to the API call | PHP | cUrl

I have two files for SSL ssl_crt and ssl_key. I want to read the content of these files and send it to the APIs as a JSON field. But the file_get_contents actually convert the single slash to double so the API return the following error.
The private key format is invalid.
The certificate format is invalid.
I am actually using run cloud service where I want to send the content of these files to one of their API
https://runcloud.io/docs/api/web-application#ssl-basic-install-ssl
As you can see in the above URL, they need the content in the proper format.
So I tried the following.
$curl = curl_init();
$ssl_crt = file_get_contents(selectServer()->ssl_crt_path);
$ssl_key = file_get_contents(selectServer()->ssl_key_path);
$data = [
'provider' => 'custom',
'enableHttp' => true,
'enableHsts' => false,
'certificate' => $ssl_crt,
'privateKey' => $ssl_key,
];
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://manage.runcloud.io/api/v2/servers/{id}/webapps/{webapp_id}/ssl',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_SLASHES),
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: Basic {token}'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
If I manually write the content of the certificate(or key) to the data array then it works fine. i.e
$data = [
// ...
'certificate' => '-----BEGIN CERTIFICATE-----\nblah\nblah==\n-----END CERTIFICATE-----,
'privateKey' => '-----BEGIN PRIVATE KEY-----\nblah\nblah==\n-----END PRIVATE KEY-----,
];
The actual issue with the format. the "\n" becomes "\n" and the main content of the certificate or key can have "\n".
Can someone help me out with this?
the post-mortem here is that the on-disk file was corrupted, the on-disk file had all newlines converted to literal-slash-followed-by-n, which PHP's double-quote operator was fixing, thus it worked when you hardcoded the file (with php's double-quote operator. it would not have worked with php's single-quote operator), and didn't work when you got it from file_get_contents() - code used to fix the on-disk file was
<?php
$real_crt=file_get_contents("ssl_crt");
$fixed_crt = strtr($real_crt,array(
"\\n"=>"\n",
"\\r"=>"\r",
));
file_put_contents("ssl_crt_fixed",$fixed_crt);
i only figured this out after you sent me the ssl_cert file on facebook messenger, though, and i'm pretty sure the ssl_cert file was required to solve this mystery, so i have voted to close this question as requires the shortest code necessary to reproduce the problem. ie, it needs the ssl_cert file to be any kind of reproducible

Requesting a cURL GET Request in PHP outputs garbage

I'm trying to build a Connector to Dynamics 365 Business Central but I'm having problems getting the data. Please help me figure out why when I send a GET request using cURL and PHP, it produces the following output:
�S[O�0�+(��&��qB��i�t�F/���=�ا��Ďb�}N�"&�M�����������8�0% �;
Here is my code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.businesscentral.dynamics.com/{tenantID}/customers/?$filter=displayName%20eq%20'Shawn%20Test'",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: {Auth Code}"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
It seems like a character encoding issue, or maybe you are receiving binary data.
What is this endpoint supposed to return? Check the response headers, it might give you a clue.
This is an encoding problem, try to remove CURLOPT_ENCODING line from your request or try to choose different encoding from your browser

cURL doesn't return all levels of JSON with variable in URL

I'm trying to consume an API with PHP 7.1.6. When I send the request with the API key hard-coded into the URL, it returns all the JSON. But, when I put the API key into the URL through a variable. It only returns the first level of JSON. I have tried setting the URL as a variable, then making the variable $url a cURL option and I've tried having the string with double and single quotes. Is there something else I can try to get it to work?
Also, I know the problem is with the actually response itself, but with json_decode() because when I look at the raw response, not all the JSON that should be there is present. The API key is just letters and number and when I copy the concatenated URL into Postman from the debugger, it works as it should
Here is the request:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => '/collection?fields=collection_id,name,description,f_list,modified_at&api_key=' . $api_key,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_COOKIEFILE => $this->cookie,
CURLOPT_COOKIEJAR => $this->cookie,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

Categories