Retrieve a JSON from postman on PHP - php

I am trying to retrieve a json from an api (and store as a variable), but I am unable to retrieve.
I am trying in all ways that postman and the web give to me.
I Am using laravel/homestead (ubuntu)
I am using laravel framework.
This way give me a HTTP Status 415 - Unsupported Media Type
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "443",
CURLOPT_URL => "https://iescities.com:443/IESCities/api/data/query/268/sql?origin=original",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "select * from wifi",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 1471daf9-329d-e9b4-b144-0383850f4769"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I also try another way but I haven't http\Client class and I haven't idea of how install and/or link it.
$client = new http\Client;
$request = new http\Client\Request;
$body = new http\Message\Body;
$body->append('select * from wifi');
$request->setRequestUrl('https://iescities.com:443/IESCities/api/data/query/268/sql');
$request->setRequestMethod('POST');
$request->setBody($body);
$request->setQuery(new http\QueryString(array(
'origin' => 'original'
)));
$request->setHeaders(array(
'postman-token' => 'e854f317-fdcc-1888-0043-758a3d5e32ba',
'cache-control' => 'no-cache'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
Lot of thanks and sorry for my ignorance.

From the IESCities manual:
Query must be sent in text/plain format.
So in the line you set the headers:
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 1471daf9-329d-e9b4-b144-0383850f4769"
),
You should put another key:
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 1471daf9-329d-e9b4-b144-0383850f4769",
"Content-Type: text/plain"
),
After doing this you should be able to query the API.

Have you tried decoding the JSON?
$response = curl_exec($curl);
$responseJSON = json_decode($response, true);
print_r($responseJSON);
If you JSON looks like:
{
"name": Susy,
"age": 22
}
You can pull the age by using echo $responseJSON["age"];

Related

How to upload video using put.re api (using CURL)

I want to upload videos to put.re, a file hosting provider using php curl
I tried this code:
foreach ($_FILES['uploadvid']['tmp_name'] as $index => $fileTmpName) {
$fileName = $_FILES['uploadvid']['name'];
$size = $_FILES['uploadvid']['size'];
$handle = fopen($fileTmpName, "r");
$data = fread($handle, filesize($fileTmpName));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_URL => "https://api.put.re/upload",
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array( 'file' => # $data),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$pms = json_decode($response, true);
$vidurl = $pms['data']['link'];
if ($vidurl!="") {
echo 'Success';
} else {
echo 'Problem';
echo $err;
echo $response;
}
}
But this echo Problem.
If you check the api docs, you will see there is no output for error.
You can check The Api Docs here . There is no example shown in it's site.
The $err returns nothing,
the $reponse returns a message: NO files(s) found.
I think there is a mistake in the API call...
Please Help me to get through this.
Please NOTE that, I want to upload videos, not images. put.re allows any kind of file to be uploaded. I tried to upload files less than 100mb (which is a limit)
Can you share more detail about the error you getting ? For example i tried the api with code at below and get response which says upload disabled.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.put.re/upload",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Length: 20895",
"Content-Type: application/x-www-form-urlencoded",
"Host: api.put.re",
"User-Agent: PostmanRuntime/7.20.1",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

How do I find out how to translate a Postman query in cURL via PHP

I use postman for the first time.
My goal is to download a JSON file.
I managed to look at the code for cURL in postman:
But if I test the code in the command line, I can not log in.
Actually, I want to call the JSON file via PHP. I have tested initial approaches. In addition to the problem that I can not authenticate myself here, I think that I need more values. For example POSTFIELDS. Is that correct and if so, how do I find what I have to enter in Postman? Here is my initial Code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.divessi.com/divessi/index.php",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "..",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic BASE64",
"Cache-Control: no-cache",
"Postman-Token: TOKEN",
"content-type: ??"
),
));
$response = curl_exec($curl);
$obj = json_decode($response);
$events = array();
if ($obj)
{
$events = $obj[0]->DATA;
}
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
} else {
foreach ($events as $event) {
...
}

https://oauth2.googleapis.com/tokeninfo won't return email

I used this code before and I could receive the email but it doesn't work now .... why?
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "https://oauth2.googleapis.com/tokeninfo?id_token=".$id,
));
$resp = curl_exec($curl);
curl_close($curl);
try{
$resp = json_decode($resp,true);
if(empty($resp['error']))
return $resp;
else return null;
}catch (\Exception $e)
{
return null;
}
$id is access_token/
i get name,picture,... but no email in array
The simple answer is from the docs:
These fields are only included when the user has granted the "email" OAuth scopes to the application.
About 2 months ago google shutdown google+ api, if you wish to add your code where you acquire the token maybe we could help you a bit more.
We have two ways to solve this problem:
You should use this https://www.googleapis.com/oauth2/v3/userinfo to receive email and you should have access_token
Most programmers do not know the difference between access_token and id_token, and use access_token instead of id_token by mistake. the access_token is a string shorter than id_token and you should run this code for getting email:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.googleapis.com/oauth2/v3/userinfo",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Authorization: Bearer ya29.GlsJBxmiZkSmgMEUlhrtytyJEEI45uQTR8xmmrsZulz7kEOtyrtyytrycyPxCtg_TZ_hz3x5zI5fRlqgJ9ARCnQIEFZaO5o75ZbwicwFGFf_y7PZ8T",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Host: www.googleapis.com",
"Postman-Token: 55ft6892-d0hc-43b0-af22-5eeced9155b5,58b4bd70-355c-4293-933c-30b1c0982b67",
"User-Agent: PostmanRuntime/7.11.0",
"accept-encoding: gzip, deflate",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {echo "cURL Error #:" . $err;} else {echo $response;}
The mobile programmer receives an email retrieval value and the programmer does not need to call the above web service to get the email.
Finally I got some samples of access_token and id_token
access_token:
ya29.GlsJB84Op0099CWZzGrazU449yFBRX1IwA7kjQvUbISnzaP1tGrqzcH7Pdo-vynDF9GZ7L9El_cvMrX2UBedIcq00Ml4Id5wb1459qpxfB3IzHv7dFwTKyV28E5Y
id_token:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjJjM2ZhYzE2YjczZmM4NDhkNDI2ZDVhMjI1YWM4MmJjMWMwMmFlZmQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLm67b2dsZS5jb20iLCJhenAiOiI3MjI1NDU1MjAwODItdGNycTRhZzZpZjJwZmVsbXEwN2xoM2xlMm5uamljdHIuYXB67uy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI3MjI1NDU1MjAwODI456NycTRhZzZpZjJwZmVsbX67N2xoM2xlMm5uamljdHIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDg0MDMxNzUyMzc0NDg5OTI2OTQiLCJlbWFpbCI6Im5pZ2h0LmV4dGVybkBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZ567dHJ1ZSwiYXRfaGFzaCI6IkIyVi1GenM5WjVHRm4wQjNEa0FUMXciLCJpYXQiOjE1NTc4Mjc3MTgsImV4cCI6MTU1NzgzMTgh7H0.S6VNWWcSzOqpNdOBBAY-tDmFJQu0ZTU5RSalYnsC0P4KuW6ts8f61PQT5X2a1DXjgV6vj3iu9T1Apj8RzvYezakruLt7doB9CI9vEr1hpOwCcQ3W_o8MkZWZUtU1i4heXM7k3uW9LQy5fa3mdY4pWX0YEa6x--eAnwvUHuJzrRIfn-boV4Rl1LkkCS7AKKMYpOC-_Gej5P9eu5xc7d-xtFr_Cv8ne5pnQKk-5Un9f3IV5SW9mi9AOJI_MdmKg1n-P495TAk5wrLUME5UOJTHgleh__TmfVZwpvvc-UVKtRObJhANubqqiTA_E5O1-TSdrj9yNNhldyxsL6Xb5MfsJQ`

REST API request in PHP - query error

I am making a request to an API using its post.rest web service. I have constructed the request using Postman. I get the error message, "Parameter 'query' is required, and it must have a value." I have been trying to work this out for several days, and I'm at my wits' end. I thought I could resolve it myself, but have not been successful. It seems like I've tried at least a hundred different permutations of the code.
Here is my PHP code for the request:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://SDMDataAccess.sc.egov.usda.gov/Tabular/post.rest",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>
$data = array("query" => "SELECT l.areasymbol, l.areaname, l.lkey,
musym, muname, museq, mu.mukey
FROM sacatalog sac
INNER JOIN legend l ON l.areasymbol = sac.areasymbol
AND l.areatypename = 'Non-MLRA Soil Survey Area'
INNER JOIN mapunit mu ON mu.lkey = l.lkey
AND mu.mukey IN (455997)
", "FORMAT" => "JSON"),
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/json",
"Postman-Token: 520636bc-a062-4ab8-99e7-7edaae5118b4"
),
));
file_put_contents('soil_request.txt', $data);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I am unable to find any examples of code for submitting rest requests to this API service in their documentation or elsewhere on the internet, even though their documentation is vast.
Thank you in advance for your consideration on this. I really appreciate it.
From https://en.1answer.info/676973-7a313939383734 it looks like you may need to change your data array into a json string before sending it
Also, your line that is
CURLOPT_POSTFIELDS=>$data=array("select ....
is wrong.
Instead, define your data array, then build a http query string out of it. Also, the parameter names are case sensitive, so you want to use query instead of QUERY and format instead of FORMAT.
Working code -
<?php
$data["query"]="SELECT l.areasymbol, l.areaname, l.lkey,
musym, muname, museq, mu.mukey
FROM sacatalog sac
INNER JOIN legend l ON l.areasymbol = sac.areasymbol
AND l.areatypename = 'Non-MLRA Soil Survey Area'
INNER JOIN mapunit mu ON mu.lkey = l.lkey
AND mu.mukey IN (455997)";
$data["format"] = "JSON";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://SDMDataAccess.sc.egov.usda.gov/Tabular/post.rest",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/json",
"Postman-Token: 520636bc-a062-4ab8-99e7-7edaae5118b4"
),
));
file_put_contents('soil_request.txt', $data);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Send android notification via firebase from heroku php server

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;
}

Categories