I hope someone can help me here:
I have an application which should use the Spotify API. But after request the authorization itself, I am stuck at requesting a token. Related code follows:
function post($content, $url,$clientId,$clientSecret)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic '.base64_encode($clientId).':'.base64_encode($clientSecret)));
return curl_exec($ch);
}
$clientId="4df42e27a76d41f9961b0952102fexxx";
$clientSecret="3088a8b6132b40dc980540880cf5bxxx";
$content=array(
'grant_type' => 'authorization_code',
'code' => $_GET["code"],
'redirect_uri' => 'http%3A%2F%2Fhome.xxx.de%2Ftoken.php',
);
echo post($content,"https://accounts.spotify.com/api/token",$clientId,$clientSecret);
Unfortunatly, the result is {"error":"invalid_client"} and i have no idea why...
Authorization
Required.
Base 64 encoded string that contains the client ID and client secret key. The field must have the format:
Authorization: Basic <base64 encoded client_id:client_secret>
I read this as base64_encode($clientId.':'.$clientSecret)
Related
I made the change suggested and am still receiving a similar error:
{"error":"invalid_request","error_description":"invalid grant type"}
This error is likely to happen if the url-encoding is not set properly. The updated code is below
Any help would be greatly appreciated!
<?php
$client_id = '...';
$redirect_uri = 'http://website.com/foursquare2.php';
$client_secret = '...';
$code = $_REQUEST['code'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, "https://id.shoeboxed.com/oauth/token");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
));
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
your code is sending the data in multipart/form-data format. when you give CURLOPT_POST an array, curl will automatically encode the data in that array in the multipart/form-data format. then you tell the server, with your header, that this data is in application/x-www-form-urlencoded format, and the server will try to parse it as such, and fail, thus your received error.
first off, get rid of curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); altogether. if you're using application/x-www-form-urlencoded, php/curl will automatically add that header for you, and unlike you, php/curl won't make any typos (the devs got automated test suits to make sure this stuff is correct before every release), likewise, if you're using multipart/form-data format, php/curl will add that header for you, so don't add those 2 specific headers manually.
if you want to use the multipart/form-data format, just get rid of the header saying otherwise. but if you want to use application/x-www-form-urlencoded format, PHP has a built-in function to encode to this format, called http_build_query, so do
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
)));
(and also get rid of the content-type header, it will be added automatically.)
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.
I'm trying to use php and cURL to make requests to the Fitbit oauth 2.0 api. I can get my authorisation code but cannot manage to exchange the code for a token. The Fitbit api docs say (https://dev.fitbit.com/docs/oauth2/#access-token-request) that I need to post code, client id, redirect uri and grant type set to 'authorization_code'.
Howver, I keep getting an error when I print the response.
"errorType":"unsupported_grant_type","message":"The authorization grant_type is not supported. Visit https://dev.fitbit.com/docs/oauth2 for more information on the Fitbit Web API authorization process."}],"success":false}
For the life of me I cannot work out what I am doing wrong with the below code. Any suggestions?
$code = $_GET['code'];
$url = 'https://api.fitbit.com/oauth2/token';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'code=' . $code . '&' .
'client_id=' . $oauth2_client_id . '&' .
'redirect_uri=' . $oauth2_redirect . '&' .
'grant_type=authorization_code'
)
);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Basic '. base64_encode($oauth2_client_id.':'.$oauth2_secret),
'Content-Type: application/x-www-form-urlencoded'
));
$response = curl_exec($curl);
print_r($response);
You're concatenating the POST arguments in to a single string and then include it in an array but they should be individually presented; that can be done in as follows:
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
'code' => $code,
'client_id' => $oauth2_client_id,
'redirect_uri' => $oauth2_redirect,
'grant_type' => 'authorization_code'
)));
See: curl POST format for CURLOPT_POSTFIELDS
I am trying to integrate my application with a payment gateway.
Their API is based on REST API and uses JSON to transport data. They have this sample code
$ curl -X POST -H "Content-Type: application/json" \
-u APIKEYEXAMPLEAPIKEYEXAMPLE:APIKEYEXAMPLEAPIKEYEXAMPLE \
https://api.netbanx.com/hosted/v1/orders \
-d '{
"merchantRefNum" : "ABCDE12345",
"currencyCode" : "USD",
"totalAmount" : 1234
}'
And I am trying to use this to develop a php code for the same. So far my code is like this, I took in the answer provided below and modified a bit and here is my code.
<?php
//API Url
$url = 'https://api.netbanx.com/hosted/v1/orders';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'merchantRefNum' => '89983483',
'currencyCode' => 'USD',
'totalAmount' => '1234'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Set the header authorization
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'Authorization: Basic ZGV2Y2VudHJlNDYxNzpCLXFhMi0wLTU0OGEwM2RkLTMwMmQwMjE1MDA4M2VhZTUwYjQxYzQ0ZDIwMTE4OGM3ZmY4Yjc0ZDIxMzUwY2NiMjdiMDIxNDYwMDc4MGFlMTRkM2E2MTEzY2RmMmJkODc5MjJmZjU3MWQwMGY0ZWU=');
//Execute the request
$result = curl_exec($ch);
?>
My testing API Key devcentre4617:B-qa2-0-548a03dd-302d02150083eae50b41c44d201188c7ff8b74d21350ccb27b0214600780ae14d3a6113cdf2bd87922ff571d00f4ee
As told in their docs, I converted the API Key to base64 added the word Basic gave a whitespace and got the HTTP Authorizatoin code as Basic ZGV2Y2VudHJlNDYxNzpCLXFhMi0wLTU0OGEwM2RkLTMwMmQwMjE1MDA4M2VhZTUwYjQxYzQ0ZDIwMTE4OGM3ZmY4Yjc0ZDIxMzUwY2NiMjdiMDIxNDYwMDc4MGFlMTRkM2E2MTEzY2RmMmJkODc5MjJmZjU3MWQwMGY0ZWU=
On execution I keep getting
{"error":{"code":401,"message":"Not authorised"}}
Is something wrong with my code? Or is the issues elsewhere?
UPDATE!!!
This is the working code, the issue was with the API DOCs the testing api is https://api.test.netbanx.com/hosted/v1/orders
<?php
//API Url
$url = 'https://api.test.netbanx.com/hosted/v1/orders';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'merchantRefNum' => '89983483',
'currencyCode' => 'USD',
'totalAmount' => '1234'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json and HTTP Authorization code
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("devcentre4617:B-qa2-0-548a03dd-302d02150083eae50b41c44d201188c7ff8b74d21350ccb27b0214600780ae14d3a6113cdf2bd87922ff571d00f4ee") //Base 64 encoding and appending Authorization: Basic
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Execute the request
$result = curl_exec($ch);
?>
You need to add your username and password like this:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, 'APIKEYEXAMPLEAPIKEYEXAMPLE:APIKEYEXAMPLEAPIKEYEXAMPLE');
Good luck :)
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);