Trying to get property of 'non-object' - json_decode from API - php

I am having trouble when trying to use my Livezilla chatbot script to talk to my REST API, both of which I have stored on my local PC. I am using a code snippet very similar from the Livezilla chatbot API page and have modified it, but I am getting some errors.
27.02.19 11:34:11 ::1 ERR# 129 Error connecting USER API, invalid response:
http://localhost/livezilla/programytalk.php (
Notice: Trying to get property 'answer' of non-object in
C:\xampp\htdocs\livezilla\programytalk.php on line 11
) IN LINE 0
the code for programytalk.php is as follows:
<?php
$requestobj = json_decode($_POST["livezilla_user_api_request"]);
$responseNode = array();
$responseNode["ResponseTo"] = "";
$responseNode["Id"] = rand(1111111,9999999);
$responseNode["SearchKB"] = false;
$url = "http://localhost:8989/api/rest/v1.0/ask? question=".rawurlencode($requestobj->Value)."&userid=".$requestobj-
>VisitorId;
$sdata = json_decode(file_get_contents($url));
$responseNode["Value"] = $sdata->answer;
if(!empty($responseNode["Value"]))
echo json_encode($responseNode);
?>
This is the JSON format the API responds in:
[{"response":{"answer":"Good morning.","question":"hello world","userid":"1234567890"}},200]

By that API response you don't need to read
$responseNode["Value"] = $sdata->answer;
instead of that you need to read
$responseNode["Value"] = $sdata[0]->response->answer;
because answer is nested under response...
Hint: just do this
$data = json_decode('[{"response":{"answer":"Good morning.","question":"hello world","userid":"1234567890"}},200]');
print_r($data);
and output will be:
Array
(
[0] => stdClass Object
(
[response] => stdClass Object
(
[answer] => Good morning.
[question] => hello world
[userid] => 1234567890
)
)
[1] => 200
)

Please do this;
<?php
$requestobj = json_decode($_POST["livezilla_user_api_request"]);
$responseNode = array();
$responseNode["ResponseTo"] = "";
$responseNode["Id"] = rand(1111111,9999999);
$responseNode["SearchKB"] = false;
$url = "http://localhost:8989/api/rest/v1.0/ask? question=".rawurlencode($requestobj->Value)."&userid=".$requestobj-
>VisitorId;
$sdata = json_decode(file_get_contents($url), true);
$responseNode["Value"] = $sdata->answer;
if(!empty($responseNode["Value"]))
echo json_encode($responseNode, true);
?>

Related

Square up php create card using php sdk api - card nonce error

I have tried to fix this issue but unable to do so. Field 'card_nonce' is not found on the server although it is recently created. I have used npm and node to generate a card_nonce.
Code Used:
$billing_address = new Address();
$billing_address->setAddressLine1('500 Electric Ave');
$billing_address->setAddressLine2('Suite 600');
$billing_address->setLocality('New York');
$billing_address->setAdministrativeDistrictLevel1('NY');
$billing_address->setPostalCode('10003');
$billing_address->setCountry('AU');
// $body = new CreateCustomerCardRequest($_POST['nonce']);
$body = new CreateCustomerCardRequest('CBASECw9ri-7s1THlCWDoSVsVY8');
$body->setBillingAddress($billing_address);
$body->setCardholderName('Gaurav Gulati');
$api_response = $customersApi->createCustomerCard($customer_id, $body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$customer_card = $api_response->getCard();
$customer_card_id = $customer_card->getId();
} else {
$errors = $api_response->getErrors();
}
Response:
[0] => Square\Models\Error Object
(
[category:Square\Models\Error:private] => INVALID_REQUEST_ERROR
[code:Square\Models\Error:private] => NOT_FOUND
[detail:Square\Models\Error:private] => Resource not found.
[field:Square\Models\Error:private] => card_nonce
)
Anyone has idea how to resolve this error.
You've removed the "cnon:" from the parameter. "CBASECw9ri-7s1THlCWDoSVsVY8" should be cnon:CBASECw9ri-7s1THlCWDoSVsVY8.

PHP for each loop, parse_str receiving "Notice: Undefined index: title"

I have the following PHP Code:
<?php
$file = "Links.txt";
$parts = new SplFileObject($file); // this is your array of words
foreach($parts as $word) {
$content = file_get_contents($word);
parse_str($content, $ytarr);
echo $ytarr['title'];
unset($content);
}
?>
Please note:
The Links.txt file includes multiple external URL's, on each line is only one URL. Example:
www.External-URL-number-ONE.com
www.External-URL-number-TWO.com
www.External-URL-number-THREE.com
Each of this URL have the 'title' item in the variable $content (after filling it by "file_get_contents($word);".
For troubleshooting purpose, I tested each URL by adding it in the "links.txt" single. The result was for each URL successful. The issue occours, if I add multiple URL's. In that case, the behavior is:
Error message and result:
Notice: Undefined index: title in C:\xampp\htdocs\PHPexample\index.php on line 13
Display the Title of "www.External-URL-number-THREE.com"
How can I fix this problem? It should work also with multiple lines.
Thanks in advance.
EDIT:
The content of the variable $content is:
Array (
[reason] => Invalid parameters.
[status] => fail
[errorcode] => 2
)
Array (
[ISD] => 928398
[enable] => 1
[list] => 39/9339/30
[AMP] =>
[host] =>
[title] => This_Is_the_Title_Three
[token] => 1
)
UPDATE
I have used the isset() for checking the array before access it. And only the last for each loop have an index.
Read the file and read line by line
<?PHP
$file = "Links.txt";
$handle = #fopen($file, "r");
if ($handle) {
// Read line by line
while (($word = fgets($handle)) !== false) {
$content = file_get_contents($word);
// parse_str($content, $ytarr); // parse_str don't work in this case
//echo #$ytarr['title'];
//unset($content);
echo getDataTag($content, 'title');
}
fclose($handle);
}
//This is a dirty solution
function getDataTag($str, $tag){
$str = str_replace('+',' ',$str);
$data = explode(($tag.'='),$str);
$data = explode('&',$data[1]);
return $data[0];
}
?>

How to retrive image from parse.com using php

I am trying to fetch the image which is already in parse database. In array I am getting the all the fetched data including the image URL but when I am trying to echo that particular URL it is echoing blank!!
Bellow is the code
$object = new ParseQuery("billComputing");
$getdata=$object->descending("updatedAt");
$results = $object->find();
$data=$results[0];
echo "<pre>";
print_r($results);
echo "signature".$sign=$data->get('Signature["url"]');
In print_r() - I am getting this
[Signature] => Parse\ParseFile Object
(
[name:Parse\ParseFile:private] => tfss-8a4dbd13-7e16-4efc-abcf-08e901924f49-sign
[url:Parse\ParseFile:private] => http://files.parsetfss.com/864d47af-9eac-4b75-ae30-17b7352d16ca/tfss-8a4dbd13-7e16-4efc-abcf-08e901924f49-sign
[data:Parse\ParseFile:private] =>
[mimeType:Parse\ParseFile:private] =>
)
I am not able to display the URL. Appreciate help in advance.
Try this :
$object = new ParseQuery("billComputing");
$getdata=$object->descending("updatedAt");
$results = $object->find();
$data=$results[0];
echo "<pre>";
print_r($results);
$file = $data->get('imageColumnName');
$imageURL = $file->getURL();
// you will get image url in $imageURL variable.

PHP Soap Call Giving me Errors

Hi I'm trying to setup an api service with Limoanywhere system. But regardless of what I do I get invalid ApiKey & ApiID. I went into the back system and changed the ApiKey & ApiId multiple times but still no success.
Can anyone tell me if my code is correct?
<?php
$client = new SoapClient('https://qa.book.mylimobiz.com/api/ApiService.asmx?wsdl');
$options = array(
'ApiKey' => '***api key here****',
'ApiID' => '***api id here****'
);
$result = $client->__soapCall('Test', $options);
//var_dump($client->__getFunctions());
print_r($result);
?>
Here is the snippet from the service
http://qa.book.mylimobiz.com/api/ApiService.asmx?op=Test
Here is the result I get from when run my php code.
Array ( [TestResult] => Array ( [ResponseCode] => 1 [ResponseText] => Invalid ApiId or ApiKey ) )
Check this instead of test Test function not working giving error but test of the test all function are working.
<?php
$soapClient = new SoapClient("https://book.mylimobiz.com/api/ApiService.asmx?wsdl");
// Prepare SoapHeader parameters
$sh_param = array('apiId' => 'xxxxxx','apiKey' => 'xxxxxxxxxxxx');
$headers = new SoapHeader('https://book.mylimobiz.com/api/ApiService.asmx?wsdl', 'GetVehicleTypes', $sh_param);
// Prepare Soap Client
$trans = $soapClient->GetVehicleTypes($sh_param)->GetVehicleTypesResult;
echo "<pre>"; print_r($trans);
?>

SimpleXML Problem

Maybe someone can help me with a problem I am having regarding SimpleXML Objects.
I am integrating with the authorize.net CIM manager and sending in a customer profile. When I sent it in, the raw xml response is passed through a parser and turned into a SimpleXML object.
Here is the code that is used to submit the request:
$content =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>".
"<createCustomerProfileRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">".
MerchantAuthenticationBlock().
"<profile>".
//"<merchantCustomerId>".$userInsertedId."</merchantCustomerId>". // Your own identifier for the customer.
"<description>'New User Purchase'</description>".
"<email>" . $_GET["email"] . "</email>".
"<paymentProfiles>".
"<billTo>".
"<firstName>".$_GET["firstname"]."</firstName>".
"<lastName>".$_GET["lastname"]."</lastName>".
"<address>".$_GET["street"]."</address>".
"<city>".$_GET["city"]."</city>".
"<state>".$_GET["state"]."</state>".
"<zip>".$_GET["zip"]."</zip>".
"<country>".$_GET["country"]."</country>".
"<phoneNumber>".$_GET["phone"]."</phoneNumber>".
"</billTo>".
"<payment>".
"<creditCard>".
"<cardNumber>".$_GET["number"]."</cardNumber>".
"<expirationDate>".$_GET["year"]."-".$_GET["month"]."</expirationDate>". // required format for API is YYYY-MM
"<cardCode>".$_GET["code"]."</cardCode>".
"</creditCard>".
"</payment>".
"</paymentProfiles>".
"</profile>".
"<validationMode>testMode</validationMode>".
"</createCustomerProfileRequest>";
$CCresponse = send_xml_request($content);
//echo($CCresponse);
$parsedresponse = parse_api_response($CCresponse);
function parse_api_response($content)
{
$parsedresponse = simplexml_load_string($content, "SimpleXMLElement", LIBXML_NOWARNING);
if ("Ok" != $parsedresponse->messages->resultCode)
{
echo "The operation failed with the following errors:<br>";
foreach ($parsedresponse->messages->message as $msg)
{
echo "[" . htmlspecialchars($msg->code) . "] " . htmlspecialchars($msg->text) . "<br>";
}
echo "<br>";
}
return $parsedresponse;
}
When I do the following:
$parsedresponse = parse_api_response($CCresponse);
print_r($parsedresponse);
I get the following output:
SimpleXMLElement Object
(
[messages] => SimpleXMLElement Object
(
[resultCode] => Ok
[message] => SimpleXMLElement Object
(
[code] => I00001
[text] => Successful.
)
)
[customerProfileId] => 15642446
[customerPaymentProfileIdList] => SimpleXMLElement Object
(
[numericString] => 13865552
)
[customerShippingAddressIdList] => SimpleXMLElement Object
(
)
[validationDirectResponseList] => SimpleXMLElement Object
(
[string] => 1|1|1|(TESTMODE) This transaction has been approved.|000000|P|0|none|Test transaction for ValidateCustomerPaymentProfile.|1.00|CC|auth_only||*****|******||****|*******|******|******|USA|1234567890||email#email.com|none|none|none|none|none|none|none|none|0.00|0.00|0.00|FALSE|none|207BCBBF78E85CF174C87AE286B472D2|||||||||||||*******|*******||||||||||||||||
)
)
)
)
So from this is looks like all is working. But when I try and drill into the SimpleXML object, and do this:
echo $code = (string) $parsedresponse->messages->resultCode;
I am getting an output of "OkOk", it seems like it is running over it twice. This has been driving me absolutely crazy and I can't figure out what the heck is going on here. Can someone please point me in the right direction here so I can get this working?
Thanks!
Maybe you could try and use the xpath method to navigate the SimpleXMLElement like this:
$code = (string) $parsedresponse->xpath('messages/resultCode');
echo $code;

Categories