I'm sending some data with the fetch API to a translate.php file, here is my JS code:
const translation = {
word: 'Hello'
};
fetch('http://yandex.local/translate.php', {
method: 'POST',
body: JSON.stringify(translation),
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
return res.text();
}).then(text => {
console.log(text);
})
Here is how I try to get the data on the translate.php:
$postData = json_decode(file_get_contents("php://input"), true);
$word = $postData['word'];
Here is my cURL request:
$word = $postData['word'];
$curl = curl_init();
$request = '{
"texts": "Hello",
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
curl_setopt($curl, CURLOPT_URL, 'https://translate.api.cloud.yandex.net/translate/v2/translate');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Api-Key 123456",
"Content-Type: application/json"
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$err = curl_error($curl);
if($err) {
echo 'Curl Error: ' . $err;
} else {
$response = json_decode($result, true);
print_r($response['translations']['0']['text']);
}
curl_close($curl);
When I'm runing this code I get the translation of Hello in russian which is Привет. But if I replace "Hello" in the request object by $word I got the error: Trying to access array offset on value of type null
Here is the way I rewrite the request object:
$request = '{
"texts": $word,
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
When I check the XHR of my translate.php all seems ok, I have a status 200 and the request payload shows my data. Also the word "hello" displays correctly in the console of my index.php
Don't ever create JSON strings by hand (i.e. I mean by hard-coding the JSON text directly into a string variable). It can lead to all kinds of syntax issues accidentally.
Please replace
$request = '{
"texts": "Hello",
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
with
$requestObj = array(
"texts" => $word,
"targetLanguageCode" => "ru",
"sourceLanguageCode" => "en"
);
$request = json_encode($requestObj);
This will produce a more reliable output, and also include the $word variable correctly.
P.S. Your actual issue was that in PHP, variables are not interpolated inside a string unless that string is double-quoted (see the manual). Your $request string is single-quoted.
Therefore $word inside your $request string was not changed into "Hello" but left as the literal string "$word". And also since you removed the quotes around it, when the remote server tries to parse that it will not be valid JSON, because a text variable in JSON must have quotes around it. This is exactly the kind of slip-up which is easy to make, and why I say not to build your JSON by hand!
Your version would output
{"texts":$word,"targetLanguageCode":"ru","sourceLanguageCode":"en"}
whereas my version will (correctly) output:
{"texts":"Hello","targetLanguageCode":"ru","sourceLanguageCode":"en"}
(Of course I should add, given the comment thread above, that regardless of my changes, none of this will ever work unless you send a correct POST request to translate.php containing the relevant data to populate $word in the first place.)
Related
I recently work with kraken.io API and I'm trying to integrate this API wuth my PHP CodeIgniter framework. So I followed the documentation but I got stuck when I used curl
This is my source code below ..
require_once(APPPATH.'libraries/kraken-php-master/Kraken.php');
$kraken = new Kraken("SOME_KEY", "SOME_SECRET");
$params = array(
"file" => base_url()."include/".$dataIn['logo'],
"wait" => true
);
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":'.base_url()."include/".$dataIn['logo'].',wait":true}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.kraken.io/v1/upload");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataj);
$response = curl_exec($ch);
curl_close($ch);
$data = $kraken->upload($params);
print_r($response);exit();
And I got this result
"{"success":false,"message":"Incoming request body does not contain a valid JSON object"}1"
So can anyone please help me,
And thanks in advance,
DONT POST YOUR API_KEY AND API_SECRET
The error message is quite clear, your json object is not valid. For instance this would be a valid JSON object for your request:
{
"auth": {
"api_key": "SOME",
"api_secret": "SECRET"
},
"file": "somefile.txt",
"wait": true
}
In your php code you are setting up a $params array but then you don't use it. Try this:
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":"' . $params["file"]. '", "wait":true}';
You can validate your JSON HERE
You should use json_encode function to generate your JSON data
$dataj = json_encode([
"auth" => [
"api_key" => "API_KEY",
"api_secret" => "API_SECRET"
],
"file" => base_url() . "include/" . $dataIn['logo'],
"wait" => true
]);
EDIT:
Here is an example from https://kraken.io/docs/upload-url so you don't need to use curl
require_once("Kraken.php");
$kraken = new Kraken("your-api-key", "your-api-secret");
$params = array(
"file" => "/path/to/image/file.jpg",
"wait" => true
);
$data = $kraken->upload($params);
if ($data["success"]) {
echo "Success. Optimized image URL: " . $data["kraked_url"];
} else {
echo "Fail. Error message: " . $data["message"];
}
I'm trying to write a PHP script based on the instructions here:
https://developers.facebook.com/ads/blog/post/2016/12/18/lead-ads-offline/
But I'm having issues with a json string passed as a parameter to curl in PHP. It looks like it's adding backslashes ("match_keys":"Invalid keys \"email\" etc.) which are causing the API call to fail.
I've tried playing around with:
json_encode($array,JSON_UNESCAPED_SLASHES);
I've tried a bunch of SO answers already like Curl add backslashes but no luck.
<?php
$email = hash('sha256', 'test#gmail.com');
$data = array("match_keys" => '{"email": $email}',
"event_time" =>1477632399,
"event_name"=> "Purchase",
"currency"=> "USD",
"value"=> 2.00);
$fields = [
// 'upload_tag'=>'2016-10-28-conversions',
'access_token'=>'#######',
'data'=> $data
];
$url = 'https://graph.facebook.com/v2.8/#######/events';
echo httpPost($url, $fields);
function httpPost($url, $fields)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
?>
This is the response:
Array{"error":{"message":"(#100) Invalid parameter","type":"OAuthException","code":100,"error_data":{"match_keys":"Invalid keys \"email\" were found in param \"data[match_keys]\".","event_time":"Out of bounds array access: invalid index match_keys","event_name":"Out of bounds array access: invalid index match_keys","currency":"Out of bounds array access: invalid index match_keys","value":"Out of bounds array access: invalid index match_keys"},"fbtrace_id":"BrVDnZPR99A"}}%
You are mixing JSON in with PHP arrays. I doubt it's actually JSON you intend using to send your data, since you're using http_build_query. Try this:
$data = array("match_keys" => ["email" => $email],
"event_time" =>1477632399,
"event_name"=> "Purchase",
"currency"=> "USD",
"value"=> 2.00
);
With this, you define your data as an array, and leave http_build_query to do the encoding for you.
I am working on an payment gateway API to process refunds.
On successful operation, the API returns a json array like this
{
"currencyCode" : "GBP",
"amount" : 100,
"originalMerchantRefNum" : "MERCHANTREF12346",
"mode" : "live",
"confirmationNumber" : 1997160616609792,
"authType" : "refund",
"id" : "25TWPTLHRR81AIG1LF"
}
On error the array returned is
{
"error": {
"code": "400",
"message": "Amount exceeds refundable amount"
}
}
I need to decode the json output and then show it to the user. But since the structure of the json array is different in both cases, how do I go arnd parsing the json array, so as to give relevant readable data to the end user.
My code which, does all the talking and fetching data from the gateway processor is given below
<?php
include('lock.php');
$flag=0;
$oid=$_POST['oid'];
if(isset($_POST['amount']))
{
$amount=$_POST['amount'];
$amount = $amount*100;
$flag=1;
}
// generate random number
$merchantref=mt_rand(10,9999999999);
//API Url
$url = 'https://api.netbanx.com/hosted/v1/orders/'.$oid.'/refund';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
if($flag==1)
{
$jsonData = array(
"amount" => $amount,
'merchantRefNum' => $merchantref
);
}
else
{
$jsonData = array(
'merchantRefNum' => $merchantref
);
}
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json and HTTP Authorization code
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("..") //Base 64 encoding and appending Authorization: Basic
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the request
$result = curl_exec($ch);
$jdata=$result;
//decode the json output and store it in a variable
$jfo = json_decode($jdata);
//Handle decision making based on json output
?>
Basically something as simple as:
$response = json_decode(..., true);
if (isset($response['error'])) {
echo 'Sorry, ', $response['error']['message'];
} else {
echo 'Yay!';
}
What exactly you need to check for depends on the possible values the API may return. Most APIs specify something along the lines of "status will be set to 'success' or 'error'", or maybe "if the error key is present, this indicates an error, otherwise a success".
I have simple function in PHP that gives me
HTTP Error 500 (Internal Server Error):
When I comment it, the simple echo does get printed.
Here is the function:
error_reporting(E_ALL);
ini_set('display_errors', '1');
function invokeAuthenticationServiceAPI()
{
$json = <<<"JSON"
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
$data_string = json_decode($json);
echo $data_string;
/*
$ch = curl_init('https://apirestserverdemo/api');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
echo $result;
*/
}
I call it in the HTML file like this:
<?php
invokeAuthenticationServiceAPI();
?>
As you can see, I need to send it to rest api server. But it does fail only on the string to json formatting.
I have two questions:
Maybe I have done something that php doesn't like. Ok, but can I get some kind of error message and not "Error 500 (Internal Server Error)"?
What am I doing wrong?
You should check the web-server error log for the details of the error, but judging by the code you have posted, the problem is probably that there are spaces before the end of the heredoc JSON; and the first time you use JSON it should not be quoted.
You should use this:
$json = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON; // no spaces before JSON;
instead of this:
$json = <<<"JSON"
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
Although personally I would generate an array or object in php and use json_encode to generate the correct output.
Remove double quotes around JSON and remove extra spaces which invalidate the PHP heredoc syntax
$json = <<<"JSON"
should be
$json = <<<JSON
Like
<?php
$str = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
echo $str;
?>
If you have a 500 Internal Server Error you almost certainly have a fatal error in PHP. Depending on your code you may find the error in your error logs or you may have to debug your code using for example xdebug.
You don't need quotes around JSON. Other than that there's nothing immediately wrong with your code. However you should generate JSON using json_encode.
I've researched everywhere and cannot figure this out.
I am writing a test cUrl request to test my REST service:
// initialize curl handler
$ch = curl_init();
$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);
$postArgs = 'order=new&data=' . $data;
// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');
// execute curl
curl_exec($ch);
This works fine and the request is accepted by my service and $_Post is populated as required, with two variables, order and data. Data has the encoded JSON object. And when I print out $_Post['data'] it shows:
{"products":{"product1":"abc","product2":"pass"}}
Which is exactly what is expected and identical to what was sent in.
When I try to decode this, json_decode() returns nothing!
If I create a new string and manually type that string, json_decode() works fine!
I've tried:
strip_tags() to remove any tags that might have been added in the http post
utf8_encode() to encode the string to the required utf 8
addslashes() to add slashes before the quotes
Nothing works.
Any ideas why json_decode() is not working after a string is received from an http post message?
Below is the relevant part of my processing of the request for reference:
public static function processRequest($requestArrays) {
// get our verb
$request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method) {
case 'post':
$data = $requestArrays->post;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if (isset($data['data'])) {
// translate the JSON to an Object for use however you want
//$decoded = json_decode(addslashes(utf8_encode($data['data'])));
//print_r(addslashes($data['data']));
//print_r($decoded);
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
Turns out that when JSON is sent by cURL inside the post parameters & quot; replaces the "as part of the message encoding. I'm not sure why the preg_replace() function I tried didn't work, but using html_entity_decode() removed the " and made the JSON decode-able.
old:
$return_obj->setData(json_decode($data['data']));
new:
$data = json_decode( urldecode( $data['data'] ), true );
$return_obj->setData($data);
try it im curious if it works.