Access web api using access token in MS Dynamics using php - php

For Previous question about Azure account, I can create an app using azure account.
Now I can get auth code from below url:
Auth_code
From Auth_code we can get the access token by:
$auth_code = $_GET['code'];
$result = access($auth_code);
function access($auth_code){
$redirectUri = 'https://XXXX /authorize.php';
$token_request_data = array (
"grant_type" => "authorization_code",
"code" => $auth_code,
"redirect_uri" => $redirectUri,
"client_id" => "client_id",
"client_secret" => "client_secret",
"resource" =>"resource" (From manifest in azure)
);
$token_request_body = http_build_query ( $token_request_data );
$curl = curl_init ( 'https://login.windows.net/common/oauth2/token' );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $curl, CURLOPT_POST, true );
curl_setopt ( $curl, CURLOPT_POSTFIELDS, $token_request_body );
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER,false);
$response = curl_exec ( $curl );
$res = json_decode($response);
curl_close ( $curl );
Now I'm trying to access the web api using that access_token,I couldn't get the result.
For example:
$authHeader = 'Authorization:Bearer access_toke';
$ch = curl_init();
$url = 'https://domain/api/data/v8.0/contacts';
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($authHeader, 'Content- Type:application/json'));
$result = curl_exec($curl);
echo "<pre>";print_r($result);exit;
curl_close($curl);
I'm getting empty response. Now I have to know how to access the web API using access token.
When I try to run manually https://domain/api/data/v8.0/contacts, I can get all contacts in my crm.But when I try to access it by access_token using php,it returns empty.
Web api reference url : reference for web api url

Refer to the guide Compose HTTP requests and handle errors, as the requirements shown at HTTP headers section:
Every request should include the Accept header value of application/json, even when no response body is expected.
And there are supernumerary blank in your PHP script at curl_setopt($curl, CURLOPT_HTTPHEADER, array($authHeader, 'Content- Type:application/json'));
You can remove the blanks in Content-Type and try again.
By the way, you can leverage Fiddler to capture the requests from your PHP client. We you get the response body content and request status code via the tool. We can match the status code with the list at https://msdn.microsoft.com/en-us/library/gg334391.aspx#bkmk_statusCodes. If the code is always 200 without response body, you may check your code in web api.

Related

Connecting to OpenID using PHP cURL Showing Error

I am using the following code to request a token from a IdentityServer, which uses OpenID protocol:
$curl = curl_init( 'https://remoteserver.com/connect/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$code = $_GET['code']; // The code from the previous request
$redirect_uri = 'http://mycalldomain.com/test.php';
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_USERPWD,
"MYCLIENTID" . ":" .
"MYCLIENTSECRET");
$auth = curl_exec( $curl );
print '$auth = ';print_r($auth); // to see the error
$secret = json_decode($auth);
$access_key = $secret->access_token;
Is outputing the following error:
$auth = {"ErrorMessage":"Unsupported Mediatype"}
Can someone guide on this please?
You should provide a Content-Type HTTP header that the resource you're POSTing things accepts, by adding something like this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
That will make it JSON (as an example!), and your output data (CURLOPT_POSTFIELDS) must correspond to the Content-Type you choose.
Currently, the Content-Type is "multipart/form-data", as per the PHP documentation:
If value is an array, the Content-Type header will be set to multipart/form-data.
If you want to use the Content-Type "application/x-www-form-urlencoded", then in addition to setting that as the Content-Type, you have to give CURLOPT_POSTFIELDS in that format too. Being a web development language, PHP has a built-in function http_build_query for encoding arrays in that format:
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
)));

linkedin oauth cant exchange auth code for access token

I am trying to use linkedin to get profile data of users, I get the authorization code from a button on login form that redirects to another page where I want to have some fields that fill with their name and such to create a user or login. I can't exchange the the auth token for an access one with my post. I get bad request or unauthorized responses. it says I am missing the required parameter "client_id", but it is obviously there ... Please take a look, thanks.
$code = $_GET['code'];
$data =array(
"grant_type" =>"authorization_code",
"code"=> $code,
"redirect_uri" => "http:\\localhost\index.php?doctor=linkedin",
"client_id" => "shh",
"client_secret" => "secret"
);
$str_data = json_encode($data);
//echo $str_data;
//function sendPostData($url, $post){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.linkedin.com/oauth/v2/accessToken');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$str_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$token = json_decode($result);
var_dump($token);
curl_close($ch); // Seems like good practice
function HandleHeaderLine( $curl, $header_line ) {
echo "<br>".$header_line; // or do whatever
return strlen($header_line);
}
LinkedIn expects ones POSTed field, as a query string. Try changing:
$str_data = json_encode($data);
to:
$str_data = http_build_query($data);
An Example from their documentation :
POST /oauth/v2/accessToken HTTP/1.1
Host: www.linkedin.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=987654321&redirect_uri=https%3A%2F%2Fwww.myapp.com%2Fauth%2Flinkedin&client_id=123456789&client_secret=shhdonottell
Hope that helps.

Google OAuth2 error - Required parameter is missing: grant_type on refresh

I have built a prototype calendar synching system using the Google calendar API and it works well, except refreshing access tokens. These are the steps I have gone through:
1) Authorised my API and received an authorisation code.
2) Exchanged the authorisation code for Access Token and a RefreshToken.
3) Used the Calendar API until the Access Token expires.
At this point I try to use the Refresh Token to gain another Access Token, so my users don't have to keep granting access because the diary sync happens when they are offline.
Here's the PHP code, I'm using curl requests throughout the system.
$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = array("grant_type" => "refresh_token",
"client_id" => $clientID,
"client_secret" => $clientSecret,
"refresh_token" => $refreshToken);
$headers[0] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);
The response i'm getting is:
[error] => invalid_request
[error_description] => Required parameter is missing: grant_type
No curl errors are reported.
I've tried header content-type: application/x-www-form-urlencoded, and many other things, with the same result.
I suspect it's something obvious in my curl settings or headers as every parameter mentioned in the Google documentation for this request is set. However, I'm going around in circles so would appreciate any help, including pointing out any obvious errors I've overlooked.
your request should not post JSON data but rather query form encoded data, as in:
$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = "grant_type=refresh_token&client_id=$clientID&client_secret=$clientSecret&refresh_token=$refreshToken";
$headers[0] = 'Content-Type: application/x-www-form-urlencoded';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);

Eventbrite API simple access token request doesn't work

My code, which actually perfectly works with Linkedin and Meetup APIs, doesn't work with Eventbrite API and I definitely don't understand why :
$params = array(
'grant_type' => 'authorization_code',
'client_id' => EVENTBRITE_CONSUMER_KEY,
'client_secret' => EVENTBRITE_CONSUMER_SECRET,
);
// Eventbrite API access token request
$url = 'https://www.eventbrite.com/oauth/token?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(array('http' => array('method' => 'POST')));
// Retrieve access token information
$response = file_get_contents($url, false, $context);
I precise that the API login part to get the authorization code seems to work perfectly well.
Here is the PHP error :
Warning: file_get_contents(https://www.eventbrite.com/oauth/token?grant_type=authorization_code&client_id=ZZ6PPQOMTKSXIHEKLR&client_secret=QQDDIS4RBZXI6ONO7QEYEUZ4JB2ABQQG6K3H7CBD6M5QWK5GSK&code=O63YZASRAYMOUHRMH5AH): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD REQUEST in /var/www/include/actions.php on line 102
Thanks by advance if anybody has a clue :)
UPDATE :
I finally found where is the problem (even if I don't understand why) :
file_get_contents doesn't seem to be a good method to access the oauth page, I used curl instead :
$request_url = 'https://www.eventbrite.com/oauth/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
I hope it will help anybody encountering the same issue ;)
Just so that this question doesn't continue to show up as unanswered in an auto-email, I'm going to add your answer from your update here -- hope that's alight!
file_get_contents doesn't seem to be a good method to access the oauth page, I used curl instead:
$request_url = 'https://www.eventbrite.com/oauth/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
Thanks for making it easy by answering your own question! ;)

Send and Receive JSON using an https curl_exec call in PHP

I'm trying to make a curl call using PHP. My project has a flow like this
I redirect user to the server.
User uses the services and the server redirects him to a page on my application.
I would like to make a server to server call at this point to verify certain details.
Point to be noted - I post JSON data as well as receive JSON data as response.
I have tried this. I am able to send data but don't get any response.
Is this correct?
Please help!
$data = array("One" => "Onedata", "Two" => "Twodata");
$JsonData = json_encode($data);
$ch = curl_init('https://exampleurl');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $JsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($JsonData))
);
$result = curl_exec($ch);
As you mention in the comment:
The problem is with SSL verification of the host. It takes some effort (see http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/) to setup SSL correctly, so a workaround is to add the following two options:
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
Try to use the below code which works for me. and make sure the json_url is correct. When you run it on the browser you should get an output. Before try it using CURL, run in on the browser and see whether you get the output you want.
$json_url ='https://exampleurl';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json')
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$results = curl_exec($ch); // Getting jSON result string
$json_decoded = json_decode($results);

Categories