I am getting a response as an array in the following format:
Array
(
[refresh_token_expires_in": "0] =>
[api_product_list": "[ops-prod]] =>
[api_product_list_json": [
"ops-prod"
]] =>
[organization_name": "epo] =>
[developer.email": "sudham#gmail.com] =>
[token_type": "BearerToken] =>
[issued_at": "1568870621501] =>
[client_id": "F4GzALmoCfWXh] =>
[access_token": "MYjtqSlOI] =>
[application_name": "8ec0-872fa20cdc59] =>
[scope": "core] =>
[expires_in": "1199] =>
[refresh_count": "0] =>
[status": "approved] =>
[error] =>
)
when i run print_r($token); i am getting the proper response.
Now i need to grab the value of only "access_token". I am not sure how to do that. I tried with $token['access_token']; but its returning null value. Can anyone help me on the same.
The following is the json response:
{"refresh_token_expires_in\": \"0":"","api_product_list\": \"[ops-prod]":"","api_product_list_json\": [\n \"ops-prod\"\n ]":"","organization_name\": \"epo":"","developer.email\": \"sudham#gmail.com":"","token_type\": \"BearerToken":"","issued_at\": \"1568871637352":"","client_id\": \"fxhYBIrh7BZHtcQeUIGF4GzALmoCfWXh":"","access_token\": \"HgARGtASwbcG":"","application_name\": \"2df9fbac-8ec0-872fa20cdc59":"","scope\": \"core":"","expires_in\": \"1199":"","refresh_count\": \"0":"","status\": \"approved":"","error":""}
Response
a:14:{s:29:"refresh_token_expires_in": "0";s:0:"";s:30:"api_product_list": "[ops-prod]";s:0:"";s:44:"api_product_list_json": [
"ops-prod"
]";s:0:"";s:24:"organization_name": "epo";s:0:"";s:39:"developer.email": "sudham#gmail.com";s:0:"";s:25:"token_type": "BearerToken";s:0:"";s:26:"issued_at": "1568871637352";s:0:"";s:45:"client_id": "4GzALmoCfWXh";s:0:"";s:44:"access_token": "ARGtASwbcG";s:0:"";s:56:"application_name": "46e2-8ec0-872fa20cdc59";s:0:"";s:13:"scope": "core";s:0:"";s:18:"expires_in": "1199";s:0:"";s:18:"refresh_count": "0";s:0:"";s:18:"status": "approved";s:0:"";}
oauth1.php
<?php
function read_token ($tokenname) {
// read token file and return token variables array
// if token not present or outdated create a new token and return new token variables array
$tokenfile="$tokenname.dat";
$error='';
if (file_exists($tokenfile)) {
$token=unserialize(file_get_contents($tokenfile));
// convert token issued time from windows (milliseconds) format to unix (seconds) format
$tokentime=substr($token['issued_at'],0,-3);
$tokenduration=$tokentime + $token['expires_in'] - 120;
if ($tokenduration < time()) {
$error.="token '$tokenname' expired.<br>\n";
} else {
$token['error']=$error;
}
} else {
$error.="tokenfile '$tokenname' not found.<br>\n";
}
if ($error) {$token=create_token($tokenname);}
return($token);
}
function create_token ($tokenname) {
// set variables
$tokenfile="$tokenname.dat";
$error='';
switch ($tokenname) {
case 'OPSincidental':
$ops_key='*******';
$ops_secret='*******';
break;
default:
$ops_key='*******';
$ops_secret='*******';
break;
}
$tokenUrl='https://ops.epo.org/3.2/auth/accesstoken';
$tokenHeaders=array(
'Authorization: Basic '.base64_encode($ops_key.':'.$ops_secret),
'Content-Type: application/x-www-form-urlencoded'
);
$tokenPostFields='grant_type=client_credentials';
$curlOpts=array(
CURLOPT_URL => $tokenUrl,
CURLOPT_HTTPHEADER => $tokenHeaders,
CURLOPT_POSTFIELDS => $tokenPostFields,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1
);
// obtain token
$token_request= curl_init();
curl_setopt_array($token_request, $curlOpts);
if (!$ops_token_response=curl_exec($token_request)) {$error.=curl_error($token_request)."<br>\n";}
curl_close($token_request);
// process token
$ops_token_split=explode(',', trim($ops_token_response,'{}'));
foreach ($ops_token_split as $tokenval) {
$tokenpair=explode(' : ', trim($tokenval));
$token[trim($tokenpair[0],'"')]=trim($tokenpair[1],'"');
}
// write token data to file
file_put_contents($tokenfile, serialize($token));
// add error information to token array and return result
$token['error']=$error;
return($token);
}
?>
oauthmain.php
<?php
// obtain token
include_once('oauth1.php');
$token=read_token('OPSincidental');
//print json_encode($token);
if (!$token['error']) {
echo "Token:<br>\n<PRE>"; print_r($token); echo "</PRE>";
// prepare for sending data request
$error='';
$requestUrl='http://ops.epo.org/3.2/rest-services/published-data/publication/epodoc/EP1000000/biblio';
//$requestUrl='https://ops.epo.org/3.2/rest-services/published-data/publication/epodoc/EP100000';
$requestHeaders=array(
'Authorization: Bearer '.$token['access_token'],
'Host: ops.epo.org',
'X-Target-URI: http://ops.epo.org',
'Accept: application/xml',
'Connection: Keep-Alive'
);
$curlOpts=array(
CURLOPT_URL => $requestUrl,
CURLOPT_HTTPHEADER => $requestHeaders,
// CURLOPT_SSL_VERIFYPEER => FALSE,
// CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1
);
// send request and collect data
$ops_request= curl_init();
curl_setopt_array($ops_request, $curlOpts);
if (!$ops_response=curl_exec($ops_request)) { $error.=curl_error($ops_request)."<br>\n";}
echo "curl options:<br>\n";
echo "<PRE>";print_r($requestHeaders);echo "</PRE>";
curl_close($ops_request);
if ($error) {echo "Error:<br>\n$error";} else {echo "Result:<br>\n".htmlspecialchars($ops_response);}
} else {
echo $token['error'];
}
?>
Use the unserialize() function to parse that response.
$ops_token_response = file_get_contents("filename.dat");
$token = unserialize($ops_token_response);
echo $token['access_token'];
TBH I would recommend changing the way you store the token file - I would store the return value from the API directly to the file (you would be storing the JSON string). At the moment you are trying to do your own json_decode() on the response - which is not correctly extracting the data anyway...
// Do not use this bit
// process token
// $ops_token_split=explode(',', trim($ops_token_response,'{}'));
// foreach ($ops_token_split as $tokenval) {
// $tokenpair=explode(' : ', trim($tokenval));
// $token[trim($tokenpair[0],'"')]=trim($tokenpair[1],'"');
// }
// Decode the values to $token
$token = json_decode($ops_token_split, true);
// Write JSON to token file
// write token data to file
file_put_contents($tokenfile, $ops_token_response);
Then to read the file, just json_decode() the contents of the file...
if (file_exists($tokenfile)) {
$token=json_decode(file_get_contents($tokenfile), true);
Related
I tried my first API call but something is still wrong. I added my API-Key, choose the symbol and tried to echo the price. But it is still not valid. But my echo is still 0. Maybe someone show me what i did wrong. Thank you!
<?php
$coinfeed_coingecko_json = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?symbol=ETH');
$parameters = [
'start' => '1',
'limit' => '2000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: XXX'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
$coinfeed_json = json_decode($coinfeed_coingecko_json, false);
$coinfeedprice_current_price = $coinfeed_json->data->{'1'}->quote->USD->price;
?>
<?php echo $coinfeedde = number_format($coinfeedprice_current_price, 2, '.', ''); ?>
API Doc: https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest
There is a lot going on in your code.
First of all $url was not defined
Second of all you made two requests, one of which I have removed
Third; you can access the json object by $json->data[0]->quote->USD->price
Fourth; I removed the invalid request params
I have changed a few things to make it work:
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
var_dump($json->data[0]->quote->USD->price);
var_dump($json->data[1]->quote->USD->price);
I am trying to pull data from API for active collab, but in the body to the task exist tags HTML, causing a mess in the coding, anybody know what I can do?
My code to push API:
try {
function listTasks() {
$ch = curl_init();
$token = 'token';
curl_setopt_array($ch, [
CURLOPT_URL => 'https://collab.cadastra.com.br/api/v1/projects/projectnumber/tasks/',
CURLOPT_HTTPHEADER => [
'X-Angie-AuthApiToken: ' . $token,
'Content-Type: application/json',
'x-li-format: json'
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS
]);
$result = curl_exec($ch);
// $tasks = json_decode($result, true);
// for ($i = 0; $i < count($tasks); $i++) {
// if ($tasks[$i]["task_list_id"] == 55979) {
// $tasks_name[$i] = $tasks[$i]["name"];
// }
// }
print_r(filter_var($result, FILTER_SANITIZE_MAGIC_QUOTES));
curl_close($ch);
// return $resultado;
}
listTasks();
} catch (Error $e) {
print_r($e->getMessage());
}
// print_r($_POST['email']));
This return:
you can use one of PHP function for clean view:
strip_tags (https://www.php.net/manual/en/function.strip-tags)
htmlentities (https://www.php.net/manual/en/function.htmlentities)
for view the tasks, otherways you must look at the source of request, cause browser is rendering html. if you will have any errors for this, you can the function use for task body.
I hope it help to you. :)
i need to transform a return JSON in Array, to manipulate the datas, but when trying this array is set as null, i need to use htmlentities why this return in navigator was messed up by the html tags in json.
this is my code:
<?php
try {
function listTasks() {
$ch = curl_init();
$token = 'token';
curl_setopt_array($ch, [
CURLOPT_URL => 'https://collab.cadastra.com.br/api/v1/projects/idproject/tasks/',
CURLOPT_HTTPHEADER => [
'X-Angie-AuthApiToken: ' . $token,
'Content-Type: application/json',
'x-li-format: json'
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS
]);
$result = curl_exec($ch);
$convert = htmlentities($result, ENT_QUOTES, "UTF-8"); // I did this because the return had html tags that gave problems with browser display.
$tasks = json_decode($convert, true); //this is where I convert to array.
// for ($i = 0; $i < count($tasks); $i++) {
// if ($tasks[$i]["task_list_id"] == 55979) {
// $tasks_name[$i] = $tasks[$i]["name"];
// }
// }
var_dump($tasks); // here it returns null, if I put print_r returns nothing.
curl_close($ch);
// return $result;
}
listTasks();
} catch (Error $e) {
print_r($e->getMessage());
}
// print_r($_POST['email']));
Someone can help me ?
If the cURL request is responding with JSON format, you should first decode it with
json_decode
and then only use
htmlentities
for specify array index'es to clear the text. Then you use your way, you make json string invalid, so it can't decode it. anyway you should not use mixed json with html to display it into browser.
I am working with an API at the moment that will only return 200 results at a time, so I am trying to run some code that works out if there is more data to fetch based on whether or not the results have a offsetCursor param in them as this tells me that that there are more results to get, this offsetCursor is then sent a param in the next request, the next set of results come back and if there is an offsetCursor param then we make another request.
What I am wanting to do is push the results of each request into a an array, here is my attempt,
function get_cars($url, $token)
{
$cars = [];
$curl = curl_init();
curl_setopt_array($curl, 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 => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err) {
return false;
} else {
$results = json_decode($response, TRUE);
//die(print_r($results));
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
//array_push($cars, $results['_embedded']['results']);
}
}
die(print_r($cars));
}
I assume I am doing the polling of the api correct in so mush as that if there is a cursor offet then I just call the function from within itself? But I am struggling to create an array from the results that isnt just an array within and array like this,
[
[result from call],
[resul from call 2]
]
what I really want is result from call1 right through to call n be all within the same sequential array.
using a do+while loop, you'll have only 1 instance of cars variable, that would work.
Since you're using recursion, when you call get_cars inside get_cars, you have 2 instances of cars variable, one per get_cars call.
IMHO, using a loop is better in your case.
But if you still want to use recursion, you should use the result of get_cars call, something like this:
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
$newcars = get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
$cars = array_merge($cars, $newcars);
//array_push($cars, $results['_embedded']['results']);
}
(and get_cars should return $cars, instead of printing it with print_r)
Edit: here is an example of, untested, code with a while loop (no need for do+while here)
<?php
function get_cars($baseUrl, $token)
{
$cars = [];
// set default url to call (1st call)
$url = $baseUrl;
while (!empty($url))
$curl = curl_init();
curl_setopt_array($curl, 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 => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err)
{
// it was "return false" in your code
// what if it's the 3rd call that fails ?
// - "return $cars" will return cars from call 1 and 2 (which are OK)
// - "return false" will return no car (but call 1 and 2 were OK !!)
return $cars;
}
$results = json_decode($response, TRUE);
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
// next call will be using this url
$url = $baseUrl . '&cursor_offset='.$results['cursorOffset'];
// DONT DO THE FOLLOWING (concatenating with $url, $url = $url . 'xxx')
// you will end up with url like 'http://example.com/path/to/service?cursor_offset=xxx&cursor_offset==yyy&cursor_offset==zzz'
// $url = $url . '&cursor_offset='.$results['cursorOffset'];
}
else
{
$url = null;
}
}
return $cars;
}
i have a chriskacerguis Rest Server ,that listen for a client request as usually an API Server do.
base on client request i want to send/response some data to client in header only.
my questions are:
how do i access Client header first? then
how do i set Header in Rest Server?
This is how i send a request to REST SERVER:
function request_curl($url = NULL) {
$utc = time();
$post = "id=1&CustomerId=1&amount=2450&operatorName=Jondoe&operator=12";
$header_data = array(
"Content-Type: application/json",
"Accept: application/json",
"X-API-KEY:3ecbcb4e62a00d2bc58080218a4376f24a8079e1",
"X-UTC:" . $utc,
);
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => 'http://domain.com/customapi/api/clientRequest',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $header_data,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HEADER => 1,
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) {
die(curl_error($ch));
}
curl_close($ch);
echo '<pre>';
print_r($answer);
echo '</pre>';
}
Below is my REST SERVER function that listen request and will response a header:
public function clientRequest_post() {
// Getting Post Data
$entityBody = file_get_contents('php://input', 'r');
$this->response($entityBody,200);
//getting header data ,no idea
}
May be try php function getallheaders() which will fetch all the header data for you. If you want to convert it into array, use foreach.
So this will get you the header data and will convert it into array
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
Now if you want to get body and convert it into array as well
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
The final function will look something like this...
public function clientRequest_post() {
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
$this->response($entityBody, 200);
}
Btw, I assume $this->response($entityBody,200); will generate the response for you. Best of luck with it