I try to make a cURL request to Dropbox API, but I get this error:
Error in call to API function "files/search_v2": options: expected array, got string
I don't understand why, I'm sending an array!?
My code is below. Documentation here: https://www.dropbox.com/developers/documentation/http/documentation#files-search
$token = "....";
$options = array("path" => "/", "max_results" => 10);
$options["file_categories"] = "folder";
$parameters = array("query" => "searchPhrase", "options" => $options);
$headers = array(
"Authorization: Bearer $token",
'Content-Type: application/json'
);
$curlOptions = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($parameters),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
);
try {
$ch = curl_init('https://api.dropboxapi.com/2/files/search_v2');
curl_setopt_array($ch, $curlOptions);
$response = curl_exec($ch);
//var_dump($response);
curl_close($ch);
} catch (Exception $e) {
trigger_error(
sprintf(
'Curl failed with error #%d: %s',
$e->getCode(),
$e->getMessage()
),
E_USER_ERROR
);
}
Related
It doesn't work and responds with
{"message": "Cannot send an empty message", "code": 50006}
I've tried entering the message into CURLOPT_POSTFIELDS
<?php
$url = 'https://discordapp.com/api/channels/638164827180630046/messages';
$ch = curl_init();
$payload = json_encode( array( "content"=> "a", "nonce"=> "638201106664521728", "tts"=> false ) );
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Authorization: Bot <token>'),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POSTFIELDS => "a"
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);
echo $response;
?>
I want it to send a message
I am using PHP OAuth2.0 Adobesign API for sending pdf to user for e-signature purpose.
I successfully generate auth token and refresh token by following basic OAuth2 steps.
Now I am facing issue while trying to send pdf transientDocuments using curl code. Below is my sample code:
define("CALLBACK_URL", "https://www.getdadstrong.com/vipin/test.php");
define("AUTH_URL", "https://api.in1.echosign.com/api/rest/v6/transientDocuments");
define("ACCESS_TOKEN_URL", "http://api.in1.echosign.com/oauth/token");
define("CLIENT_ID", "MY_CLIENT_ID");
define("CLIENT_SECRET", "MY_CLIENT_SECRET");
define("SCOPE", "agreement_send:account"); // optional
function getToken(){
$curlFILE = curl_init();
$params = array(
CURLOPT_URL => AUTH_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_NOBODY => false,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer MY_SECURE_TOKEN",
"cache-control: no-cache",
"content-type: multipart/form-data",
"Content-Disposition: form-data; name='file'; filename='MyPDF.pdf'",
),
CURLOPT_POSTFIELDS => array (
// 'filename' => new CURLFile('./MyPDF.pdf')
'filename' => new CURLFile('./MyPDF.pdf','application/pdf','MyFile')
),
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_SSL_VERIFYHOST => FALSE
);
curl_setopt_array($curlFILE, $params);
$response = curl_exec($curlFILE);
curl_close($curlFILE);
$err = curl_error($curlFILE);
if ($err) {
echo "<br/> cURL Error #01: " . $err;
}
echo '<pre>';
var_dump($err);
var_dump($response);
echo '<pre>';
}
getToken();
Output:
{
"code": "NO_FILE_CONTENT",
"message": "Must provide file body"
}
Finally I come to know Adobe Esign with V6 having some issue with this method. So I switch to V5 and make some little modification in my code. It is working for me.
<?php
define("AUTH_URL", "https://api.na2.echosign.com/api/rest/v5/transientDocuments");
$url = AUTH_URL;
$header =array(
"Authorization: Bearer 3AAAB6hBTt666543359kgBzroaNxqyezwBRdsdsdssssssssss6767gGy7CNdERHxqz1r5lOzmyxI7hfQ22zsyCDvnG_HRc8m9B7UBRJuGy",
"cache-control: no-cache",
"content-type: multipart/form-data",
"Content-Disposition: form-data; name='File'; filename='MyPDF.pdf'",
);
$filePath= '#'.file_get_contents('MyPDF.pdf');
$fields = array('File' => $filePath,'Mime-Type' => 'application/pdf', 'File-Name' => 'MyPDF.pdf');
$resource = curl_init();
curl_setopt_array($resource, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $fields,
CURLOPT_HTTPHEADER => $header
));
$res = curl_exec($resource);
$result = json_decode($res,true);
echo "<pre>";
print_r($result);
echo "</pre>";
curl_close($resource);
?>
Output:
Array
(
[transientDocumentId] => 3AA777777777777gwxctQX8kTYj2e3Esgc5_HbvKgKK_oaIccNqr2JwWJK8bUXn779OMvyFMJG2VONbbbMqO-bo_GoKJP-wfYszcQtg7tbJ8sc8YxTwQPm3kV77777ThgQy5ZoeHb_km-zmitgdSkf7sLYp0vCO8CAbvYQVzd3OpU6zJ-Mv54VoVKvsYUFsfhfhgK]epKpCHnvKWvn37fghfg777876rV2QYyh9bkApotXvSzxndXNQbUTmAcpP1Jq-WlXsVdGleKjHoEMoDgfhfghIOYQFxy5eeOtctqwtxC9MUWjioGV6FW6ZtoGm0ijqGU*
)
I had a little play in some free time and the following seemed to work on my test system. The function targets a very simple php endpoint rather than a remote url/api endpoint.
$file=sprintf('%s%slamb_vindaloo.pdf', __DIR__, DIRECTORY_SEPARATOR );
define( 'BEARER_TOKEN', '74e793ea86b6e06d5d971454a955c48012a422d7694d3463c23f69ef758f62db' );
define( 'AUTH_URL', 'https://sentinel/demo/stack/pdf-receiver.php' );
define( 'CA_CERTIFICATE', 'c:/wwwroot/cacert.pem' );
function getToken( $file=false ){
if( !$file )return;
$curl = curl_init();
$params = array(
CURLOPT_URL => AUTH_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POST => true,
CURLOPT_NOBODY => false,
CURLOPT_HTTPHEADER => array(
sprintf( "Authorization: Bearer %s", BEARER_TOKEN ),
"Cache-Control: no-cache",
"Content-Type: application/octet-stream", # <----- set the content-type
sprintf("Content-Disposition: form-data; name='file'; filename='%s'", $file ),
),
CURLOPT_POSTFIELDS => array (
'filename' => new CURLFile( $file, mime_content_type( $file ), pathinfo( $file, PATHINFO_FILENAME ) )
),
CURLOPT_CAINFO => CA_CERTIFICATE, # <------ if the endpoint is SSL it is advisable to use a valid cacert.pem file!!
CURLOPT_SSL_VERIFYPEER => false, # <------ if possible set this to true
CURLOPT_SSL_VERIFYHOST => 2 # <------ true/false are not options for this
);
curl_setopt_array( $curl, $params );
/*
Return an object with the various return values
rather than doing any printing from within the
function
*/
$res=(object)array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
curl_close( $curl );
return $res;
}
/* call the function */
$results=getToken( $file );
/* process the response accordingly */
if( $results->info->http_code==200 ){
printf('<pre>%s</pre>', $results->response );
}
The simple PHP endpoint is:
<?php
#
# PDF File Receiver for curlFile Tests....
#
$data=file_get_contents( 'php://input' );
echo base64_encode( $data );
?>
The response, to highlight success was as follows:
LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS02NGQ5ZGYyYTE3ZmE1MGNkDQpDb250ZW50LURpc3Bvc...etc etc
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;
I'm attempting to push a notification to a specific Android device using a heroku PHP server. I'm not having any luck in doing so, however.
I can push a notification through the firebase console just fine (i.e. the problem is not with my Android app).
Here is my code (which I got from How do I send a POST request with PHP?):
$url = 'https://fcm.googleapis.com/fcm/send';
$data = array('score' => '5x1', 'time' => '15:10');
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n" .
"Authorization: key=MY_SERVER_KEY\r\n",
'method' => 'POST',
'data' => http_build_query($data),
'to' => 'MY_FCM'
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
I feel like I'm doing something terribly basic wrong (like my JSON is not formatted correctly or something).
The firebase apis can be found here: https://firebase.google.com/docs/cloud-messaging/send-message
I've been working on this for a couple days now, and any assistance will be much appreciated. Thanks guys!
Update
A quick note that Heroku doesn't support the HttpRequest() class from what I've experienced, however, cURL works great. Also, I didn't mention it, but I was actually wanting a notification message to be sent, not just a data message. So, my final code looked like the following:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\n
\"notification\" : {\n
\"body\" : \"Goku\",\n
\"title\" : \"Over 9000\",\n
},\n
\"to\" : \"MY_FCM_TOKEN\"\n
\"priority\" :
\"high\"\n
}",
CURLOPT_HTTPHEADER => array(
"authorization: key=MY_SERVER_KEY",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
In your code
'http' => array(
'header' => "Content-type: application/json\r\n" .
"Authorization: key=MY_SERVER_KEY\r\n",
'method' => 'POST',
'data' => http_build_query($data),
'to' => 'MY_FCM'
)
you have to send data and to inside the key 'content'.
/* $mydata contains 'data' and 'to' */
'http' => array(
'header' => "Content-type: application/json\r\n" .
"Authorization: key=MY_SERVER_KEY\r\n",
'method' => 'POST',
'content' => http_build_query($mydata)
)
These are few recommended ways to send fcm notification using php
HttpRequest
$request = new HttpRequest();
$request->setUrl('https://fcm.googleapis.com/fcm/send');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'cache-control' => 'no-cache',
'content-type' => 'application/json',
'authorization' => 'key=YOUR_FCM_API_KEY'
));
$request->setBody('{
"data" : {
"name" : "Goku",
"power_level" : "Over 9000",
"fighting_skill" : "excellent"
},
"to" : "FCM_ID_OF_RECIEVER"
}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
pecl_http
<?php
$client = new http\Client;
$request = new http\Client\Request;
$body = new http\Message\Body;
$body->append('{
"data" : {
"name" : "Goku",
"power_level" : "Over 9000",
"fighting_skill" : "excellent"
},
"to" : "FCM_ID_OF_RECIEVER"
}');
$request->setRequestUrl('https://fcm.googleapis.com/fcm/send');
$request->setRequestMethod('POST');
$request->setBody($body);
$request->setHeaders(array(
'cache-control' => 'no-cache',
'content-type' => 'application/json',
'authorization' => 'key=YOUR_FCM_API_KEY'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
cURL
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\n \"data\" : {\n \"name\" : \"Goku\",\n \"power_level\" : \"Over 9000\",\n \"fighting_skill\" : \"excellent\"\n },\n \"to\" : \"FCM_ID_OF_RECIEVER\"\n}",
CURLOPT_HTTPHEADER => array(
"authorization: key=YOUR_FCM_API_KEY",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I am using the following code to update an issue in JIRA but unable to diagnose the error. The error I am getting is as follows:
HTTP Status 415 - Unsupported Media Type
type Status report
message Unsupported Media Type
The code I have written is as follows:
$resource_array['api_name'] = 'issue/SPC-60';
$resource_array['fields'] = array (
'summary' => 'CLONE - Testing label stuff',
'assignee' =>
array (
'emailAddress' => 'avinashk.dubey#gmail.com',
),
'customfield_10649' =>
array (
'id' => '10668',
),
'customfield_10616' => 'This is observation'
);
$data = putJiraAPI($resource_array);
print_r($data);
////////////////////////////////////////////
function putJiraAPI($resource_array)
{
$api_name = $resource_array['api_name'];
unset($resource_array['api_name']);
$result = put_to($api_name, $resource_array);
if(is_array($result))
{
return $result;
}
else
{
return "error while getting data using ".BASE_URL.API_URL.$resource_string;
}
}
function put_to($api_name, $resource_array)
{
$jdata = json_encode($resource_array);
print_r($jdata);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_URL => BASE_URL . API_URL . $api_name,
CURLOPT_USERPWD => USER_NAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHECURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_RETURNTRANSFER => true
));
echo BASE_URL . API_URL . $api_name;
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result,true);
}
Actually, I did wrong here:
CURLOPT_HTTPHECURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
it should be:
CURLOPT_HTTPHEADER => array('Content-type: application/json'),