Calling Watson API from PHP code - php

I am trying to call Natural Language Understanding Watson API from my PHP code using curl. I have successfully tried curl from terminal. It gives some result on executing this command:
curl -u "my_username":"my_password" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream.&features=sentiment,keywords"
However when I try to use curl in php using this code:
<?php
$url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream%2C%20a%20dream%20deeply%20rooted%20in%20the%20American%20dream%20%E2%80%93%20one%20day%20this%20nation%20will%20rise%20up%20and%20live%20up%20to%20its%20creed%2C%20%22We%20hold%20these%20truths%20to%20be%20self%20evident%3A%20that%20all%20men%20are%20created%20equal.&features=sentiment,keywords";
$post_args = array(
'version' => '2017-02-27',
'url' => 'https://davidwalsh.name/curl-post',
'features' => 'sentiment,keywords'
);
$headers = array(
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "my_username:my_password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
?>
I get this result:
{
"error": "unsupported media type",
"code": 415
}
What should be done?

I can't believe I was stuck here due to a blank space.
Replacing this:
$headers = array(
'Content-Type:application/json'
);
with
$headers = array(
'Content-Type: application/json'
);
worked. Note the blank space between : and application/json.

Related

Having troubles for using CURL and API using PHP

Good day family !
Please help me using this API.
This API is user to get a token see the normal answer :
{'status': True, 'message': 'Success', 'code': 50, 'data': {'token': '773b718a53341b57zd511dazd4588fdf2', 'amount': 45.0}}
When i use Python it's working fine ! here is the python working code :
import requests
import json
headers = {"Authorization": "Token 12345678900987654321234567890", "Content-Type":"application/json"}
data = {"vendor": 1265,
"amount": 45,
"note" : "Commande #1324"
}
r = requests.post("https://sandbox.paymee.tn/api/v1/payments/create", data=json.dumps(data), headers=headers)
response = r.json()
# Now you can use
print(response)
But when i use PHP i have as output : NULL
Here is the code
<?php
$headers = array("Authorization: Token 12345678900987654321234567890");
$curl_post_data = array(
'vendor' => 1265,
'amount' => 45,
'note' => "Commande #1324"
);
$curl_handle=curl_init('https://sandbox.paymee.tn/api/v1/payments/create');
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_POST, true);
curl_se
topt($curl_handle, CURLOPT_POSTFIELDS, $curl_post_data);
$query = json_decode(curl_exec($curl_handle),true);
var_dump($query);
curl_close($curl_handle);
?>
Do you have any solution please ? i spent one week stuking there ! and my exam is close... :(
Thanks in advance
$result = curl_exec($curl_handle);
$query = json_decode($result,true);
<?php
$headers = array(
"Authorization: Token 12345678900987654321234567890",
"Content-Type: application/json"
);
$data = array(
"vendor" => 1265,
"amount" => 45,
"note" => "Commande #1324"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://sandbox.paymee.tn/api/v1/payments/create");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
print_r($response);
?>
This gives me the response that I'm using a invalid token which seems about right since you gave a sample token.

could not send the notification using topic messaging

could not send the notification using topic messaging. Here i am attached the code. Please check it. it runs fine on the postman. But could not get the notification.
$topic = $_POST['topic'];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
if($_POST['send_to']=='topic'){
$fcmNotification = array(
'to' => '/topics/'.$topic,
'notification' => $dataToSentNotification,
);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$results = curl_exec($ch);
curl_close($ch);
Use the curl_errno function to get the specific error, code as follow:
$error_msg = NULL;
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch);
if ($error_msg !== NULL) {
print_r($error_msg);
}
As aynber says, add the whole curl sentences inside if or what do you expect if $fcmNotification is empty or null?

Shutter Stock API PHP Post Object formatting

I am talking to the Shutter Stock API. I am certain the problem is not SS but more the formatting of my PHP Curl post as if I send this request via terminal I get a proper response.
The Terminal curl comand is as follows:
curl "https://api.shutterstock.com/v2/images/licenses?subscription_id=$SUBSCRIPTION_ID" \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header "Content-Type: application/json" \
-X POST \
--data '{
"images": [
{ "image_id": "137111171" }
]
}
so I am playing with sending this as a PHP curl instead and here is what I have:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = new Object();
$params = {
'images' : {'image_id' : '137111171'}
};
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_decode($params));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
/*$json = json_decode($response, true);
if (json_last_error()) {
echo '<span style="font-weight:bold;color:red;">Error: ' . $response . '</span>';
} else {*/
return $response;
The response form Shutter Stock is "Decode body failure" which is a custom error response. I think the problem is in the $params variable and how it is formatted. Problem is that this is a post, I suspect that on the other side SS is decoding this in a specific way. The proper curl parameter is in the bash curl above as:
--data '{
"images": [
{ "image_id": "137111171" }
]
Does anyone have any suggestions about how to properly format this particular --data value so that I can send it as a POST?
Thanks
your PHP code contains invalid syntax, also PHP has no class named Object, but you're probably looking for StdObject, but even that doesn't make much sense here.. also you're not urlencoding $SUBSCRIPTION_ID . remove the invalid syntax parts, and use json_encode, not json_decode..
curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode ( array (
'images' => array (
array (
'image_id' => '137111171'
)
)
), JSON_OBJECT_AS_ARRAY ) );
(edit, going by the comments, the api requires applicable data to be an array instead of an object, thus i added the JSON_OBJECT_AS_ARRAY flag.)
I think you pass wrong CURLOPT_POSTFIELDS data. Try:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = [
'images' => ['image_id' => '137111171']
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;

Why does Google Firebase Cloud Messaging Server return Moved Temporarily?

This is what I wrote to get it and attempt to send a push notification:
<?php
//send FCM notification
$fcmToken = "My device token";
$fcmKey = "My Firebase Cloud Messaging Server Key";
//I tried curl like this but I barely understand it and it wouldn't work
//curl -X POST --header "Authorization: key=$fcmKey" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"$fcmToken\",\"notification\":{\"body\":\"Yellow\"},\"priority\":10}"
echo "starting curl <hr>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: key=$fcmKey","Content-Type: application/json","to: $fcmToken","notification:{\"body\":\"Yellow\"}","priority: 10" )); //setting custom header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
echo "curlResult: " . $result;
curl_close($curl);
echo "<hr>curl end";
?>
The output I got was like this, why?:
starting curl <hr>curlResult: <HTML>
<HEAD>
<TITLE>Moved Temporarily</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Moved Temporarily</H1>
The document has moved here.
</BODY>
</HTML>
<hr>curl end
Thanks in advance for any help!
I'm not sure what exactly made the difference but I ended up following the answer on this post to get it to work:
Firebase Cloud Messaging, issues in receiving notification
For preservation this is what it said:
<?php
function send_notification ($tokens)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$priority="high";
$notification= array('title' => 'Some title','body' => 'hi' );
$fields = array(
'registration_ids' => $tokens,
'notification' => $notification
);
$headers = array(
'Authorization:key=xxxxxxxxxxxxx',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// echo json_encode($fields);
$result = curl_exec($ch);
echo curl_error($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$tokens = array('RECEIVER-TOKEN-1'
,'RECEIVER_TOKEN-2');
$message_status = send_notification($tokens);
echo $message_status;

PHP cURL: how to set body to binary data?

I'm using an API that wants me to send a POST with the binary data from a file as the body of the request. How can I accomplish this using PHP cURL?
The command line equivalent of what I'm trying to achieve is:
curl --request POST --data-binary "#myimage.jpg" https://myapiurl
You can just set your body in CURLOPT_POSTFIELDS.
Example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Taken from here
Of course, set your own header type, and just do file_get_contents('/path/to/file') for body.
This can be done through CURLFile instance:
$uploadFilePath = __DIR__ . '/resource/file.txt';
if (!file_exists($uploadFilePath)) {
throw new Exception('File not found: ' . $uploadFilePath);
}
$uploadFileMimeType = mime_content_type($uploadFilePath);
$uploadFilePostKey = 'file';
$uploadFile = new CURLFile(
$uploadFilePath,
$uploadFileMimeType,
$uploadFilePostKey
);
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify array of form fields
*/
CURLOPT_POSTFIELDS => [
$uploadFilePostKey => $uploadFile,
],
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
See - https://github.com/andriichuk/php-curl-cookbook#upload-file
to set body to binary data and upload without multipart/form-data, the key is to cheat curl, first we tell him to PUT, then to POST:
<?php
$file_local_full = '/tmp/foobar.png';
$content_type = mime_content_type($file_local_full);
$headers = array(
"Content-Type: $content_type", // or whatever you want
);
$filesize = filesize($file_local_full);
$stream = fopen($file_local_full, 'r');
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PUT => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_INFILE => $stream,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
fclose($stream);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
credits: How to POST a large amount of data within PHP curl without memory overhead?
Try this:
$postfields = array(
'upload_file' => '#'.$tmpFile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'/instances');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
}
curl_close($ch);
Below solution worked fine for me.
$ch = curl_init();
$post_url = "https://api_url/"
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$post = array(
'file' => '#' .realpath('PATH_TO_DOWNLOADED_ZIP_FILE')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$headers[] = 'Authorization: Bearer YOUR_ACCESS_TOKEN';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
refered: curl to php-curl
You need to provide appropriate header to send a POST with the binary data.
$header = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_POSTFIELDS, $arr_containing_file);
Your $arr_containing_file can for example contain file as expected (I mean, you need to provide appropriate expected field by the API service).
$arr_containing_file = array('datafile' => '#inputfile.ext');

Categories