cURL request Spotify API Unexpected status: 415 - php

Here is my script for an auth request to Spotify but it returns an error. I tried changing the Content-Type, but that doesn't seem to cut it. Here is my code:
$spot_api_client = 'client';
$spot_api_secret = 'secret';
$spot_api_redirect = 'myurl';
if(isset($_GET['state']) && isset($_COOKIE['stateKey']) && $_COOKIE['stateKey'] == $_GET['state']){
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "https://accounts.spotify.com/api/token",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'grant_type' => 'authorization_code',
'code' => $_GET['code'],
'redirect_uri' => urlencode($spot_api_redirect),
),
CURLOPT_HTTPHEADER => array(
'Accept' => '*/*',
'User-Agent' => 'runscope/0.1',
'Authorization' => 'Basic '. base64_encode($spot_api_client.':'.$spot_api_secret),
'Content-Type'=>'application/json'
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
}

Well, seems I found the answer based on this question :
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';
$spot_api_redirect = 'myurl';
$credentials = "client:secret";
$headers = array(
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
"User-Agent: runscope/0.1",
"Authorization: Basic " . base64_encode($credentials));
$data = 'grant_type=authorization_code&code='.$_GET['code'].'&redirect_uri='.urlencode($spot_api_redirect);
if(isset($_GET['state']) && isset($_COOKIE['stateKey']) && $_COOKIE['stateKey'] == $_GET['state']){
unset($_COOKIE['stateKey']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($response);
}

Just in case of node.js / request use, point out "WTF" tag :)
request(
{
method : "POST",
url : "https://accounts.spotify.com/api/token",
json : true,
headers :
{
"Content-Type" : "application/x-www-form-urlencoded", // WTF!
"Authorization" : "Basic " + new Buffer(client_id+":"+client_secret).toString('base64')
},
body : "grant_type=client_credentials"
},
function (err, response, body)
{
if (err)
{
cb(err);
}
else
{
if (body.hasOwnProperty("access_token"))
{
access_token = body.access_token;
cb(null);
}
else
{
cb(body);
}
}
}
);

Related

POST Request in PHP is not returning anything

I am trying to use Thycotic PAM API. According to their documentation, The following is a sample HTTP POST request. The placeholders shown need to be replaced with actual values.
POST /SecretServer/webservices/SSWebservice.asmx/GetUser HTTP/1.1
Host: 192.168.3.242
Content-Type: application/x-www-form-urlencoded
Content-Length: length
token=string&userId=string
I can get token string and user ID from the app. With this data, following is the PHP code I am trying
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser';
$data = array(
'token' => 'token_string',
'userId' => 8
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = json_decode(file_get_contents($url, false, $context));
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
I also tried this way:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser?token=token_string&userId=8 HTTP/1.1';
$json = json_decode(curl_get_contents($url));
var_dump($json);
Both of them are returning nothing. Any suggestion is much appreciated.
curl_setopt($ch ,CURLOPT_POST, 1);
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch ,CURLOPT_POSTFIELDS, "token=string&userId=string");
you must use this parameters

PHP curl file transfer

we're using GLPI API we need to create a ticket linked with documents .
The only curl part that i can't translate it's the document's upload .
With Curl (working) :
curl -i -X POST "http://glpitest/glpi/apirest.php/Document" -H "Content-Type: multipart/form-data" -H "Session-Token:sessiontoken"-H "App-Token:apptoken" -F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json" -F "filename[0]=#test.txt" "http://glpitest/glpi/apirest.php/Document"
But i can't translate this is in PHP CURL i tried something like this :
$headers = array(
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
'Http_Accept: application/json',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
echo $url = $_SESSION['api_url'] . "/Document";
$cfile = new CURLFile('testpj.txt', 'text/plain', 'test_name');
//$manifest = 'uploadManifest={"input": {"name": "test", "_filename" : "testpj.txt"}};type=application/json filename[0]=#'+$cfile;
$post = ["{\"input\": {\"name\": \"test\", \"_filename\" : \"testpj.txt\"}};type=application/json}", #"C:\\xampp\htdocs\glpi"];
print_r($post);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
the example in the api:
$ curl -X POST \
-H 'Content-Type: multipart/form-data' \
-H "Session-Token: 83af7e620c83a50a18d3eac2f6ed05a3ca0bea62" \
-H "App-Token: f7g3csp8mgatg5ebc5elnazakw20i9fyev1qopya7" \
-F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}};type=application/json' \
-F 'filename[0]=#file.txt' \
'http://path/to/glpi/apirest.php/Document/'
< 201 OK
< Location: http://path/to/glpi/api/Document/1
< {"id": 1, "message": "Document move succeeded.", "upload_result": {...}}
update : I tried #hanshenrik but i have an error .
["ERROR_JSON_PAYLOAD_INVALID","JSON payload seems not valid"]
in the api.class.php :
if (strpos($content_type, "application/json") !== false) {
if ($body_params = json_decode($body)) {
foreach ($body_params as $param_name => $param_value) {
$parameters[$param_name] = $param_value;
}
} else if (strlen($body) > 0) {
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
$this->format = "json";
} else if (strpos($content_type, "multipart/form-data") !== false) {
if (count($_FILES) <= 0) {
// likely uploaded files is too big so $_REQUEST will be empty also.
// see http://us.php.net/manual/en/ini.core.php#ini.post-max-size
$this->returnError("The file seems too big!".print_r($_FILES), 400,
"ERROR_UPLOAD_FILE_TOO_BIG_POST_MAX_SIZE", false);
}
// with this content_type, php://input is empty... (see http://php.net/manual/en/wrappers.php.php)
if (!$uploadManifest = json_decode(stripcslashes($_REQUEST['uploadManifest']))) {
//print_r($_FILES);
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
I have no uploadManifest in $_REQUEST and if i put the the filename[0]file i have the curl error 26 (can't read file) .
Thank you
translating
-F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json"
is tricky because php doesn't really have native support for adding Content-Type headers (or any headers really) to members of a multipart request, with the only *exception* (known to me) being CURLFile's "Content-Type" and Content-Disposition's "filename" header... with that in mind, you can work around this by putting your data in a file and creating a CURLFile() around that dummy file, but it's.. tricky and stupid-looking (because PHP's curl api wrappers lacks proper support for it)
with the CURLFile workaround, it would look something like:
<?php
declare(strict_types = 1);
$ch = curl_init();
$stupid_workaround_file1h = tmpfile();
$stupid_workaround_file1f = stream_get_meta_data($stupid_workaround_file1h)['uri'];
fwrite($stupid_workaround_file1h, json_encode(array(
'input' => array(
'name' => 'Uploaded document',
'_filename' => 'test.txt'
)
)));
curl_setopt_array($ch, array(
CURLOPT_URL => "http://glpitest/glpi/apirest.php/Document",
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
"Session-Token:sessiontoken",
"App-Token:apptoken"
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => new CURLFile($stupid_workaround_file1f, 'application/json', ' '), // https://bugs.php.net/bug.php?id=79004
'filename[0]' => new CURLFile('test.txt', 'text/plain')
)
));
curl_exec($ch);
curl_close($ch);
fclose($stupid_workaround_file1h);
Thanks for the Help .
$document can be a $_FILES['whatever'] post .
Works on GLPI api .
<?php
declare (strict_types = 1);
session_start();
$document = array('name' => 'document', 'path' => 'C:\xampp\htdocs\glpi\document.pdf', 'type' => 'txt', 'name_ext' => 'document.pdf');
$url = $_SESSION['api_url'] . "/Document";
$uploadManifest = json_encode(array(
'input' => array(
'name' => $document['name'],
'_filename' => $document['name_ext'],
),
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data',
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => $uploadManifest,
'filename[0]' => new CURLFile($document['path'], $document['type'], $document['name_ext']),
),
));
print_r($_REQUEST);
echo $result = curl_exec($ch);
echo "erreur n° " . curl_errno($ch);
$header_info = curl_getinfo($ch, CURLINFO_HEADER_OUT) . "/";
print_r($header_info);
if ($result === false) {
$result = curl_error($ch);
echo stripslashes($result);
}
curl_close($ch);

How to re-write this cURL request in Guzzle 6?

Example Code (provided by Channel Advisor):
https://developer.channeladvisor.com/authorization/updating-access-token/php-updating-access-token
<?php
$endpoint = "https://api.channeladvisor.com/oauth2/token";
$refresh_token="{{REFRESH_TOKEN}}";
$application_id= "{{APPLICATION_ID}}";
$shared_secret="{{SHARED_SECRET}}";
$url = $endpoint;
$client_id = base64_encode("$application_id:$shared_secret");
$body = "grant_type=refresh_token&refresh_token=$refresh_token";
$length = strlen($body);
$headers = array(
"Authorization: Basic $client_id",
"Content-Type: text/plain",
"Cache-Control: no-cache",
"Content-Length: $length"
);
echo "URL:".$url."\n";
echo "Body:$body\n";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
print_r($httpcode);
echo"\n";
$json = json_decode($result, true);
var_dump($json);
?>
Attempting to rewrite as Guzzle HTTP request:
My question is am I setting the Basic authentication correctly?
$accessToken = {{ACCESS_TOKEN}};
$refresh_token = {{ACCESS_TOKEN}};
$application_id = {{APPLICATION_ID}};
$shared_secret = {{SHARED_SECRET}};
$base_uri = "https://api.channeladvisor.com/oauth2/token";
$client_id = 'Basic ' . base64_encode("$application_id:$shared_secret");
$client = new Client(
['headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => $client_id
]
]
);
$result = $client->request('POST', $base_uri, [
'query' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
],
]);
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
You're sending POST request, then I guess you should send FORM data, not QUERY data.
$response = $client->request('POST', $base_uri, [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
],
]);

Invisible recaptcha siteverify - error codes

I'm trying to verify my $_POST['g-recaptcha-response'] on https://www.google.com/recaptcha/api/siteverify but i keep getting the following result:
"success": false,
"error-codes": [
"missing-input-response",
"missing-input-secret"
]
My code:
if($has_errors == false) {
$result = file_get_contents( 'https://www.google.com/recaptcha/api/siteverify', false, stream_context_create( array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query( array(
'response' => $_POST['g-recaptcha-response'],
'secret' => variable_get('google_recaptcha_secret', '')
) ),
),
) ) );
var_dump($result);
$result = json_decode($result);
if($result->success == false) {
form_set_error('name', t('Submission blocked by Google Invisible Captcha.'));
}
}
I checked my variable google_recaptcha_secret, it is correct.
I've never seen file_get_contents used to post data like that, I'm not saying it's not possible but I would recommend trying with cURL:
if ($has_errors == false) {
$data = [
'response' => $_POST['g-recaptcha-response'],
'secret' => variable_get('google_recaptcha_secret', ''),
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);
$error = !$result ? curl_error($curl) : null;
curl_close($curl);
var_dump($result);
$result = json_decode($result);
if ($error || $result->success == false) {
form_set_error('name', t('Submission blocked by Google Invisible Captcha.'));
}
}

I want to call call the mifinity api using php

I am using the following api:http://apidocs.mifinity.com/#/doc/2 but its not working??
My API key
$data = array(
'key' => "1234567777"
);
$url = 'https://demo.mifinitypay.com/';
$ch = curl_init($url);
$postString = http_build_query($data, '', '&');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$request = new HttpRequest();
$request->setUrl('https://demo.mifinitypay.com/api/oauth/token');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'postman-token' => '6396dfb7-540b-0e7d-7333-5d0eeff4d606',
'cache-control' => 'no-cache',
'authorization' => 'Basic username:password encoded using Base64',
'x-api-version' => '1',
'accept' => 'application/json',
'content-type' => 'application/x-www-form-urlencoded'
));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array(
'grant_type' => 'client_credentials'
));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}

Categories