I am writing a script that does foreign exchange using an API to do it in realtime.
I presume that the problem is in my implementation of curl, as I get no output from this :
$currencyBase = "USD";
$currencyForeign = "EUR";
$url = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=' . $currencyBase . '&to_currency=' . $currencyForeign . '&apikey=KCUGBA9AP3Z1E2P8';
echo $currencyBase;
// create curl resource
$c = curl_init($url); //Initialize a cURL session
curl_setopt($c, CURLOPT_HEADER, 0); //Set an option for a cURL transfer
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); //Set an option for a cURL transfer
$this->fxRate = doubleval(curl_exec($c));
curl_close($c); //Close a cURL session
I have hardcoded
$currencyBase = "USD";
$currencyForeign = "EUR";
for debugging and I have also tried print_r($c) to see if I'm passing anything but I still get no output.
I know that my API call works because I have tried the link with entered USD and EUR and I get a response when I enter it in the browser as follows:
https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=EUR&apikey=KCUGBA9AP3Z1E2P8
But I always get an empty response when I print the output from the script.
Your problem is this part of the code: $this->fxRate = doubleval(curl_exec($c));
curl_exec returns a string (which happens to be json), which you are casting to doubleval and that results in 0. Try it like this instead:
$this->fxRate = json_decode(curl_exec($c))->{"Realtime Currency Exchange Rate"}->{"5. Exchange Rate"};
Related
I'm trying to pass a $url to curl using a function.
the URL is built with a variable in it in the following method:
a.php // main page, include (a.php, b.php)
b.php // dynamic string function
c.php // curl function
I build a dynamic string successfully using sessions data // $_SESSION["input"]
myDynamicstringfunction set a string by multiple sessions input values.
$dval = myDynamicstringfunction();
echo $dval;
// render correctly to: "-e5 -g6 -g7"
the $dval value is a string that resolve as expected. the $url is:
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 $dval";
The $url is render correctly with the
echo $url;
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
I pass the $url to the curl function using:
$r = mycUrlfunction($url);
The curl function I use:
function singleRequest($url){
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$curly = curl_exec($ch);
if ($curly == FALSE){
die("cURL Error: " . curl_error($ch));
}
$result = json_decode($curly, true);
// close cURL resource, and free up system resources
curl_close($ch);
echo '<pre>';
return ($result);
}
The above get me an error (curl 1) - CURLE_UNSUPPORTED_PROTOCOL (1)
I have tried many things to get the $url to work with no success.
if I set the $url value manually without the $dval variable like this:
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
The code works just fine and I get the correct results from the API call.
I tried using different quotes, {}, [], encoding to ASCII, vprintf(), and other solutions with no success.
the problem was with constructing the dynamic variable $dynamicstring of the URL
initially used
$dynamicstring= "-a" . $_SESSION["a"]." -b".$_SESSION['b']." -c".$_SESSION['c']." -d".$_SESSION['d']."<br>";
this have a few problems
when using echo it render the expected output correctly
it have a "<br>" at the end
it have the wrong structure
the correct way to construct the $dynamicstring is to use {}
$dynamicstring= "-a{$_SESSION["a"]} -b{$_SESSION['b']} -c{$_SESSION['c']} -d{$_SESSION['d']}";
<?php error_reporting(0);
$currency_code = $_GET['currency_code'];
$currency_opt = strtoupper($currency_code)."INR";
$jsn_response = file_get_contents('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22' .$currency_opt. '%22%29&format=json&env=store://datatables.org/alltableswithkeys&callback=');
$currencyrate_arr = json_decode($jsn_response, true);
$currency_rate = $currencyrate_arr['query']['results']['rate']['Rate'];
//var_dump($currency_rate);
if($currency_rate > 0){
echo $currency_text = $currency_rate;
}
else{
echo $currency_text = "SORRY! ERROR..";
}
?>
It was working fine but now I am getting error while using this piece of code for currency conversion.
The script is working for me, and produces correct results.
If you are receiving an error, it's either because of a server configuration, or an API limit.
You can check https://developer.yahoo.com/yql/faq/
Rate limits in YQL are based on your authentication. If you use IP-based authentication, then you are limited to 2,000 calls/hour/IP to the public YQL Web service URL (/v1/public/*)
If you need to exceed the 2000 calls per hour limit, read the above link for more information.
PS: If you want to debug, set:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Edit: Since allow_url_fopen is disabled, you can't use file_get_contents on outside URLs, but you can still use CURL.
So just replace the file_get_contents with:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22' .$currency_opt. '%22%29&format=json&env=store://datatables.org/alltableswithkeys&callback=');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$jsn_response = curl_exec($ch);
curl_close($ch);
I want to convert given postcode to latitude and longitude to integrate in my cart project.
But when I try to grab latitude and longitude with google api they are showing some error like,
"We're sorry... ... but your computer or network may be sending
automated queries. To protect our users, we can't process your request
right now."
What is wrong with my code? My code is shown below.
function getLatLong($code){
$mapsApiKey = 'AIzaSyC1Ky_5LFNl2zq_Ot2Qgf1VJJTgybluYKo';
$query = "http://maps.google.co.uk/maps/geo?q=".urlencode($code)."&output=json&key=".$mapsApiKey;
//---------
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $query);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$data = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//-----------
//$data = file_get_contents($query);
// if data returned
if($data){
// convert into readable format
$data = json_decode($data);
$long = $data->Placemark[0]->Point->coordinates[0];
$lat = $data->Placemark[0]->Point->coordinates[1];
return array('Latitude'=>$lat,'Longitude'=>$long);
}else{
return false;
}
}
print_r(getLatLong('SW1W 9TQ'));
Use useragent
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0');
Also check whether you missed or not to send any HTTP Request header. Also check whether you are using required parameters(GET or POST) with your request.
By the way, If you are using too many requests then you have nothing to do with this error. Just stop sending requests, or limit your requests so that it doesn't upset the server.
NOTE: When the user accepts my permissions to use my app. I ask them to accept manage_notifications
I am so confused. I research this on the web and it seems I get a mix of deprecated and wrong information and I am trying to send a notification to the user using my facebook canvas app using facebook graph. the following is how I do it and its not working.
public function getAccessToken() {
$app_id = $this->settings['app_id'];
$app_secrete = $this->settings['app_secrete'];
$url = "https://graph.facebook.com/oauth/access_token?".
"client_id={$app_id}".
"&client_secret={$app_secrete}".
"&grant_type=client_credentials";
$c = curl_init($url);
// necessary so CURL doesn't dump the results on your page
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($c);
$result = explode("=", $result);
curl_close ($c);
return $result[1];
}
The result passes something like this access_token=523216317ewwer235|K4A1XugBpajwrweu1K2k12jzckdU . so that is why i explode the = sign within the code. I call this function every time the user enters my app. I take the access code and pass it as $token in the following code.
public function alertUser($userid,$token,$message="You have a notification") {
$inviteMessage = $message;
$inviteMessage = urlencode($inviteMessage);
$url = "https://graph.facebook.com/{$userid}/notifications?access_token={$token}&".
"template={$inviteMessage}&ref=notify";
$c = curl_init($url);
// necessary so CURL doesn't dump the results on your page
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($c);
curl_close ($c);
$r = json_decode($result);
}
and I get the following response
object(stdClass) {
error => object(stdClass) {
message => 'A user access token is required to request this resource.'
type => 'OAuthException'
code => (int) 102
}
}
You must use POST requests in order to make notifications work :
curl_setopt ($c, CURLOPT_POST, true);
Apparently you are making GET requests, trying to request a resource.
API integration description
The API needs a form to be posted to the API URL with some input fields and a customer token. The API processes and then posts response to a callback.php file on my server. I can access the posted vals using $_POST in that file. That's all about the existing method and it works fine.
Requirement
To hide the customer token value from being seen from client side. So I started with sending server side post request.
Problem
I tried with many options but the callback is not happening -
1) CURL method
$ch = curl_init(API_URL);
$encoded = '';
$_postArray['customer_token'] = API_CUSTOMER_TOKEN;
foreach($_postArray as $name => $value)
{
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
$resp echoes 1 if the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); is removed but the callback does not happen. I am setting a session variable in the callback script to verify.Is it needed that the API be synchronous in order to use curl method, so that curl_exec returns the response?
2) without CURL as given in Posting parameters to a url using the POST method without using a form
But the callback is not happening.
I tried with the following code too, but looks like my pecl is not installed properly because the HttpRequest() is not defined.
$req = new HttpRequest($apiUrl, HttpRequest::METH_POST);
$req->addQueryData($params);
try
{
$r->send();
if ($r->getResponseCode() == 200)
{
echo "success";
// success!
}
else
{
echo "failure";
// got to the API, the API returned perhaps a RESTful response code like 404
}
}
catch (HttpException $ex)
{
// couldn't get to the API (probably)
}
Please help me out! I just need to easily send a server side post request and get the response in the callback file.
Try to debug your request using the curl_get_info() function:
$header = curl_getinfo($ch);
print_r($header);
Your request might be OK but it my result in an error 404.
EDIT: If you want to perform a post request, add this to your code:
curl_setopt($ch, CURLOPT_POST, true);
EDIT: Something else I mentioned at your code: You used a '1' at the 'CURLOPT_RETURNTRANSFER' but is should be 'true':
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
At least this is how I usually do it, and you never know if the function will also understand a '1' as 'true';
EDIT: The real problem: I copy-pasted your source and used it on one of my pages getting this error:
Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\phptests\test.php on line 8
The error is in this line:
foreach($_postArray as $name => $value)
$_postArray is an array with one value holding the other values and you need either another foreach or you simple use this:
foreach($_postArray['customer_token'] as $name => $value)
As discussed in the previous question, the callback is an entirely separate thing from your request. The callback also will not have your session variables, because the remote API is acting as the client to the callback script and has its own session.
You should really show some API documentation here. Maybe we're misunderstanding each other but as far as I can see, what you are trying to do (get the callback value in the initial CURL request) is futile, and doesn't become any less futile by asking twice.