Experimenting with webapp with Spotify API. Satisfied that all data settings on Spotify Developer site OK (client_id, client_secret etc).
When I run the following in the console...
curl -H "Authorization: Bearer <the actual access token>" https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V
... it works perfectly. Even running the following url directly in the browser works:
https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V?access_token=<the actual access token>
I've tried tagging on the access token to the url in the method below, but no luck. If I try to use the access token in the header and the url, I get an error telling me to use one or the other.
<?php
session_start();
class SpotifyClientCredentials
{
public $url = 'https://accounts.spotify.com/api/token';
public $client_id = '<the client id>';
public $client_secret = '<the client secret>';
public $token = false;
public function __construct()
{
if(isset($_SESSION['token'])) $this->token = $_SESSION['token'];
}
public function connect()
{
$enc = base64_encode($this->client_id. ':' . $this->client_secret);
$header = "Authorization: Basic $enc";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $this->url,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header],
CURLOPT_POSTFIELDS => 'grant_type=client_credentials'
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result,true);
$this->token = $data['access_token'];
$_SESSION['token'] = $this->token;
}
curl_close($ch);
}
public function request($requestUrl)
{
if(!$this->token) $this->connect();
$header = "Authorization: Bearer {$this->token}";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $requestUrl,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header]
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result, true);
print_r($data);
}
curl_close($ch);
}
}
$spfy = new SpotifyClientCredentials;
$spfy->request('https://api.spotify.com/v1/albums/4aawyAB9vmqN3uQ7FjRGTy');
Getting rid of CURLOPT_POST => true, gives an 502 Bad Gateway.
I get no response / output whatsoever with the code, as is, above.
As mentioned, tagging on the access token to the requestUrl:
CURLOPT_URL => $requestUrl . '?access_token=' . $this->token,
gives the following curl response:
Array ( [error] => Array ( [status] => 400 [message] => Must not use more than one method for including an access token ) )
If I then comment out the CURLOPT_HTTPHEADER, I once again get no response.
The access token seeems valid, as when I don't include it, I get an error message. Truly at a loss - any help gratefully appreciated.
Related
I want to get an access token to call to Google Directory API. I have seen several posts with PHP Curl code, but everytime there has to be a human action to permit access before you get the access token. Is there a way to make a CURL request and get the access token directly?
This is my code so far:
define("CALLBACK_URL", "http://localhost/los/index");
define("AUTH_URL", "https://accounts.google.com/o/oauth2/auth");
define("ACCESS_TOKEN_URL", "https://oauth2.googleapis.com/token");
define("CLIENT_ID", "**.apps.googleusercontent.com");
define("CLIENT_SECRET", "**");
define("SCOPE", "https://www.googleapis.com/auth/admin.directory.device.chromeos");
function getToken(){
$curl = curl_init();
$params = array(
CURLOPT_URL =>
ACCESS_TOKEN_URL."?"."&grant_type=authorization_code"."&client_id=".
CLIENT_ID."&client_secret=". CLIENT_SECRET."&redirect_uri=". CALLBACK_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_ENCODING => '',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_NOBODY => false,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Content-Length: 0",
"content-type: application/x-www-form-urlencoded",
"accept: *",
"accept-encoding: gzip, deflate",
),
);
curl_setopt_array($curl, $params);
$response = curl_exec($curl);
$err = curl_error($curl);
echo $response;
curl_close($curl);
if ($err) {
echo "cURL Error #01: " . $err;
} else {
$response = json_decode($response, true);
if(array_key_exists("access_token", $response)) return $response;
if(array_key_exists("error", $response)) echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
}
}
When I run it I get this error message:
{ "error": "invalid_request", "error_description": "Missing required parameter: code" }Missing required parameter: codec
I've just been through a similar problem with using PHP cURL to get an access token from the http code returned by the Google API after the user authorizes the consent screen. Here's my long-winded answer:
From least to most important: you should start by fixing the brackets after your if conditions:
if (array_key_exists("access_token", $response)) {
return $response
} elseif (array_key_exists("error", $response)) {
echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
}
The error message "Missing required parameter: code" appears because you need to post the code that was returned in the url after the client authorizes your app. You'd do that by doing something like:
CURLOPT_URL => ACCESS_TOKEN_URL."?"."&code=".$_GET['code']."&grant_type=authorization_code"."&client_id=".CLIENT_ID."&client_secret=". CLIENT_SECRET."&redirect_uri=".CALLBACK_URL,
To make it more semantic you'd define the $authorization code variable before that:
$authorizationCode = $_GET['code'];
Lastly, the most important part is that to get an Access Token from Google you need to used the cURL post method as shown in the documentation:
https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code
You can do that with PHP cURL with this command:
curl_setopt( $ch, CURLOPT_POST, 1);
But then you need to break your URL into two parts: the host and the fields to be posted. To make it easier to read, you can setup your endpoint and the fields into variables:
$endpoint = 'https://oauth2.googleapis.com/token';
$fieldsToPost = array(
// params for the endpoint
'code' => $authorizationCode, //being that $authorizationCode = $_GET['code'];
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'redirect_uri' => CALLBACK_URL,
'grant_type' => 'authorization_code',
);
Then you can use the $enpoint to set the url and http_build_query() to set up your fields. In the end, adapting your code to the code that worked for me would look something like this:
function getToken() {
$endpoint = 'https://oauth2.googleapis.com/token';
$fieldsToPost = array(
// params for the endpoint
'code' => $authorizationCode, //being that $authorizationCode = $_GET['code'];
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'redirect_uri' => CALLBACK_URL,
'grant_type' => 'authorization_code',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $endpoint);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fieldsToPost));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
// get curl response, json decode it, and close curl
$googleResponse = curl_exec($curl);
$curl_error = curl_errno($curl);
$googleResponse = json_decode( $googleResponse, TRUE );
curl_close( $curl );
return array( // return response data
'url' => $endpoint . '?' . http_build_query( $params ),
'endpoint' => $endpoint,
'params' => $params,
'has_errors' => isset( $googleResponse['error'] ) ? TRUE : FALSE, // b oolean for if an error occured
'error_message' => isset( $googleResponse['error'] ) ? $googleResponse['error']['message'] : '', // error message
'curl_error' => $curl_error, //curl_errno result
'google_response' => $googleResponse // actual response from the call
);
}
To check the response you can use the following print function to see the response:
if (isset($_GET['code'])) {
$response = getToken();
echo '<pre>';
print_r($response);
die();
}
I know it's been a long time and you've probably found a workaround but I hope this is still useful for future projects. Cheers!
I'm trying to obtain my "long lived access token" using CURL/PHP but I'm receiving the error "Missing parameters for client_id, client_secret, code, grant_type, redirect_uri".
The URL I'm calling is where you can clearly see the parameters I'm trying to pass in!
https://api.surveymonkey.net/oauth/token?client_secret='.urlencode($client_secret).'&code='.urlencode($short_token).'&redirect_uri='.urlencode($redirect_url).'&client_id='.urlencode($client_id).'&grant_type=authorization_code
I'm also using the content-type of "application/x-www-form-urlencoded" as per the docs (see below).
My CURL request:
function survey_monkey_curl_request($url, $params=[], $request_type = 'get', $access_token) {
print_r($url);
$ch = curl_init();
$headers = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: bearer " .$access_token
];
$opts = [
CURLOPT_URL => $url,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => 0,
];
if ($request_type == 'post') {
$opts[CURLOPT_POST] = 1;
//$opts[CURLOPT_POSTFIELDS] = json_encode($params);
}
if ($request_type == 'patch') {
$opts[CURLOPT_CUSTOMREQUEST] = "PATCH";
$opts[CURLOPT_POSTFIELDS] = json_encode($params);
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
curl_close($ch);
throw new Exception(curl_error($ch));
}
curl_close($ch);
return $result;
}
Where am I going wrong?
Straight from the documentation it looks like to get the long-lived token you need to post your fields:
//Exchange for long-lived token
curl -i -X POST https://api.surveymonkey.net/oauth/token -d \
"client_secret=YOUR_CLIENT_SECRET \
&code=AUTH_CODE \
&redirect_uri=YOUR_REDIRECT_URI \
&client_id=YOUR_CLIENT_ID \
&grant_type=authorization_code"
https://developer.surveymonkey.com/api/v3/?shell#new-authentication
When you append your parameters onto your url you are sending then as GET request paramters
You need to put your data string into CURL POSTFIELDS and do not json encode
The PHP Answer
<?php
$ch = curl_init();
$data = [
'client_secret' => $YOUR_CLIENT_SECRET,
'code' => $AUTH_CODE,
'redirect_url' => $YOUR_REDIRECT_URI,
'client_id' => $YOUR_CLIENT_ID,
'grant_type' => 'authorization_code'
];//set your data as an array
$headers = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: bearer " . $access_token
];
$opts = [
CURLOPT_URL => $url,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => 0,
];
if ($request_type == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = http_build_query($data);// this will build your data string from the array
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
curl_close($ch);
return $result;
Here is my controller
<?php
class Linkedin extends CI_Controller
{
public function __construct ()
{
parent::__construct();
}
public function login ()
{
redirect('https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=client_id&redirect_uri=domain');
}
public function index ()
{
$state = $_GET['state'];
if($state == '987654321')
{
$authorization_code = $_GET['code'];
// Initiating curl
$curl = curl_init();
// Here we exchanging 'authorization code' to access token
// Access token is used to get userdetails
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code='.$authorization_code.'&client_id=client_id&client_secret=app_secret&redirect_uri=domain',
CURLOPT_USERAGENT => 'To get access token',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array()
));
// Send the request & save response to $resp
$response = curl_exec($curl);
$response = json_decode($response);
curl_close($curl);
}
$curl_req = curl_init();
curl_setopt_array($curl_req, array(
CURLOPT_HTTPHEADER => array('Connection : Keep-Alive','Authorization: Bearer '.$response->access_token.''),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://api.linkedin.com/v1/people/~',
CURLOPT_USERAGENT => 'user details',
));
$resp = curl_exec($curl_req);
echo $resp;
curl_close($curl_req);
}
}
I did this from source linkedin docs . Well all seems working fine except the get_details function.I cannot get the user profile details,it returns error whenever I try after login
{
"errorCode": 0,
"message": "ssl required",
"requestId": "HLDS2BCBW4",
"status": 401,
"timestamp": 1479715273015
}
Just changed the line CURLOPT_URL => 'http://api.linkedin.com/v1/people/~' to CURLOPT_URL => 'https://api.linkedin.com/v1/people/~?format=json' and it works
I have trying to get posts from user with instagram
https://api.instagram.com/v1/users/1481746871/media/recent/?access_token=censored&count=6
I already tried using url above on my browser and it has responded what I wanted, but when i tried it on laravel, it returs
APINotAllowedError 400 you cannot view this resource
this is my code :
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$url = 'https://api.instagram.com/v1/users/317657774/media/recent/?access_token=*censored*&count=6';
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
return $results;
I wonder why ? is it because I am testing from localhost and it is not https ?
please note that I am using my own account(non private) and access_token is generated from my own account
thanks !
I am new in Tinypass api integration.
I try to integrate Tinypass API using PHP. Code below:
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://sandbox.tinypass.com/r2/access?rid=portfolio_id&user_ref=badashah26',
// CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_HTTPHEADER => array(
'AID: xxxxxxxx', // PUT your AID
'signature: xxxxxxxxxxxxxxxxxx', // PUT your signature
'sandbox: true'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
print_r($resp); exit();
Response get but error display.
"error":{"message":"Access denied: invalid AID or signature","code":401}}
Any one can find solutions.
Thanks
Our REST API documentation has been updated to provide a few steps on how to generate your own API header. Check out the documentation at http://developer.tinypass.com/main/restapi.
Best,
Tinypass Support
Something like this..? (untested)
$aid = 'YOUR AID';
$action = '/r2/access?rid='.$rid.'&user_ref='.$userref;
$request = 'GET '.$action;
$url = 'http://sandbox.tinypass.com'.$action;
$signature = hash_hmac('sha256',$request,$aid);
$auth = $aid.':'.$signature;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Authorization: '.$auth);
));
$resp = curl_exec($curl);
curl_close($curl);
print_r($resp); exit();