Handle when api doesn't respond - php

I am trying to get euro, dollar and turkish liras currencies and comparing them. But sometimes api (i am using a random currency website json values) can't respond.
Cannot get any value and page loading 30 sec, after execute time was done, error appears.
What i am trying to do is: if it couldn't get any value in 1 second(or less) from api, return null. How can i do that. If anybody can help, i would glad. This is my php codes. I was tried to use if else in this, but can't worked.
ps: I have a ajax codes for that, its refreshing when the value are change. This is working most times. But 2-3 times in a day, it throws error.
$json_eur = file_get_contents('https://doviz.com/api/v1/currencies/EUR/latest');
$val_eur = json_decode($json_eur, true);
echo $val_eur['selling'];
EDIT
This is the solve. Added some codes to JRoss answer.
$ctx_dollar = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
$usd_url = 'https://doviz.com/api/v1/currencies/USD/latest';
if (#file_get_contents($usd_url)):
$json_usd = file_get_contents($usd_url, 0, $ctx_dollar);
$val_usd = json_decode($json_usd, true);
if (is_numeric($val_usd['selling'])) {
echo $val_usd['selling'];
}
else {
echo "loading...";
}
endif;

$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
file_get_contents("https://doviz.com/api/v1/currencies/EUR/latest", 0, $ctx);
http://php.net/file_get_contents
and on top of that I would catch exceptions. try {} catch (Exception $e) {}

Related

Getting messages from multiple chats madelineproto

I am looking for some help here.
I am trying to get messages from multiple chats in Telegram using MadelineProto using the user IDs with code:
require 'vendor\autoload.php';
$settings[ 'logger' ][ 'logger' ] = 0;
$settings[ 'serialization' ][ 'serialization_interval' ] = 30;
$MadelineProto = new API('session.madeline', $settings);
$MadelineProto->async(true);
$MadelineProto->start();
$chat_one = 1234567;
$chat_two = 3254682;
$chat_three = 154789965;
function getMessagesById($u_id, $MadelineProto){
$offset_id = 0;
$limit = 100;
do {
$messages_Messages = $MadelineProto->messages->getHistory(
['peer' =>$u_id,
'offset_id' => $offset_id,
'offset_date' => 0,
'add_offset' => 0,
'limit' => $limit,
'max_id' => 0,
'min_id' => 0,
'hash' => 0 ]
);
if (count($messages_Messages['messages']) == 0) break;
print_r($messages_Messages);
$offset_id = end($messages_Messages['messages'])['id'];
yield $MadelineProto->sleep(3);
} while (true);
}
getMessagesById($chat_one , $MadelineProto);
getMessagesById($chat_two , $MadelineProto);
getMessagesById($chat_three , $MadelineProto);
But this does not return any message. I tried it by setting async to false and I get the messages only for the first function call and not two others.
Any idea here, what I am missing?
What I am actually after is only getting messages from specifics contacts and the code above works with async set to false for only one contact. I use ajax to refresh it every 10 seconds for new messages but sometimes it returns empty, so any better idea to do this would be appreciated. I went through the docs but nothing helped on getting messages, all sendMessage.
Thanks
It is necessary to transfer the object:
$inputChannel = ['_' => 'inputPeerChat', 'chat_id' => $u_id];
['peer' => inputChannel,

Stripe - partial refund with PHP, iOS and Alamofire

Hi I get an error of responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) I guess this is caused by the amount I passed to my backend server. But, I couldn't find out why. If I process full refund (not using amount and currency), everything works fine.
Below code is in iOS.
print(countOrders)
var requestString = "http://xxxxx.com/fullRefund.php"
var params = ["chargeId": chargeId]
let amountStr = String(Int(sellingPrice * Double(quantity)))
if countOrders > 1 {
requestString = "http://xxxxx.com/partialRefund.php"
params = ["chargeId": chargeId, "amount": amountStr, "currency": currency]
}
print(requestString)
print(chargeId)
print(amountStr)
print(currency)
Alamofire.request(requestString, method: .post, parameters: params).responseJSON { (response) in
switch response.result {
case .success(_):
break
case .failure(let error):
print(error)
break
}
}
Every input should be correct as it prints
2
http://xxxxx.com/partialRefund.php
ch_1BDdTTLYXQrQQLvfRzXnzLsh
4083
CNY
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Here is the charge detail from Stripe
ID: ch_1BDdTTLYXQrQQLvfRzXnzLsh
Amount: ¥6,366.00 CNY → $7,391.84 HKD
Below code is partialRefund.php. I guess something wrong in amount since error shows inputDataNilOrZeroLength
<?php
require_once('stripe-php/init.php');
\Stripe\Stripe::setApiKey('sk_test_keyyyyyyyyyyyyyyyy');
$chargeId = $_POST['chargeId'];
$amount = $_POST['amount']; // this line is deleted in fullRefund.php
$currency = $_POST['currency']; // this line is deleted in fullRefund.php
try {
$re = \Stripe\Refund::create(
array(
"charge" => $chargeId,
"amount" => $amount*100, // this line is deleted in fullRefund.php
"currency" => $currency // this line is deleted in fullRefund.php
)
);
$json = array(
'status' => 'Success'
);
echo json_encode($json);
} catch(\Stripe\Error\Card $e) {
$json = array(
'status' => 'Failure',
'message' => $e->getMessage()
);
echo json_encode($json);
}
?>
That looks like you're getting an error in your response to the iOS app, rather than in something coming into your PHP script. You might want to try switching to responseString to see if that fixes it, or try adding a Content-Type header before you echo your JSON:
header('Content-Type: application/json');

SoapClient Returns "NULL", but __getLastResponse() returns XML

The variable $response in the below code is NULL even though it should be the value of the SOAP request. (a list of tides). When I call $client->__getLastResponse() I get the correct output from the SOAP service.
Anybody know what is wrong here? Thanks! :)
Here is my code :
$options = array(
"trace" => true,
"encoding" => "utf-8"
);
$client = new SoapClient("http://opendap.co-ops.nos.noaa.gov/axis/webservices/highlowtidepred/wsdl/HighLowTidePred.wsdl", $options);
$params = array(
"stationId" => 8454000,
"beginDate" => "20060921 00:00",
"endDate" => "20060922 23:59",
"datum" => "MLLW",
"unit" => 0,
"timeZone" => 0
);
try {
$result = $client->getHLPredAndMetadata($params);
echo $client->__getLastResponse();
}
catch (Exception $e) {
$error_xml = $client->__getLastRequest();
echo $error_xml;
echo "\n\n".$e->getMessage();
}
var_dump($result);
The reason that the $result (or the response to the SoapCall) is null is indeed because the WSDL is invalid.
I just ran into the same problem - the WSDL said the response should be PackageChangeBatchResponse yet the actual XML returns has PackageChangeResponse
Changing the WSDL to match the response / changing the response to match the WSDL resolves the issue
you should give an option parameter as below :
<?php
// below $option=array('trace',1);
// correct one is below
$option=array('trace'=>1);
$client=new SoapClient('some.wsdl',$option);
try{
$client->aMethodAtRemote();
}catch(SoapFault $fault){
// <xmp> tag displays xml output in html
echo 'Request : <br/><xmp>',
$client->__getLastRequest(),
'</xmp><br/><br/> Error Message : <br/>',
$fault->getMessage();
}
?>
"trace" parameter enables the output of request. Now, you should see the SOAP request.
(source: PHP.net

SoapClient connection to SoapServer

I need to connect to a SOAP Server from php, I read a lot of documentation, examples and tutorials, but I still cannot make authentication to my server. I have done the work below:
$agencyNumber = 7818619810;
$fullTransmission = false;
//$context = array('header' => 'Content-type: application/soap+xml; charset=utf-8');
$params = array( 'agencyNumber' => 7818619810, 'fullTransmission' => 0/*,$context*/);
$client = new SoapClient("http://link/to/server?wsdl");
$test = $client->__getFunctions();
var_dump($test );// returns the functions my supplier provides, as well __getTypes() gives a bunch of variable arrays ect..
$response = $client->__soapCall('GetTransmissionTicket',array($params) );//line 16 which is mentioned on error print
var_dump($response);
Even though I set $context, when I try to run, I get the error below:
Fatal error: Uncaught SoapFault exception: [HTTP] Cannot process the
message because the content type 'text/xml; charset=utf-8' was not the
expected type 'application/soap+xml; charset=utf-8'. in
C:\xampp\htdocs\xml\inc\connection_test.php:16 Stack trace: #0
[internal function]: SoapClient->__doRequest('http://interfac...', '..//my-provider...', 1, 0) #1
C:..path..test.php(16): SoapClient->__soapCall('GetTransmission...',
Array) #2 {main} thrown in C:..path..test.php on line 16
The remote method I'm trying to call is called GetTransmissionTicket which takes two parameters, (int)agencyNumber and fullTransmission(bool)..
I want to emphasize that there are a lot of threads on this topic, some of which are really close to my question(1, 2, 3 and so on ..), but I really couldn't solve the problem. Please give a hand..
Kind Regards..
Try $params = array( 'agencyNumber' => 7818619810, 'fullTransmission' => false);
instead of $params = array( 'agencyNumber' => 7818619810, 'fullTransmission' => 0);
OR
Use $client = new SoapClient("http://link/to/server?wsdl", array('soap_version' => SOAP_1_1));
because
application/soap+xml is the content-type passed when using SOAP 1.2, text/xml is used with SOAP 1.1,
Reference : how to change content-type of request?
A simple example with soap and php can be
$url="your WSDL url";
$method = "Method you are calling";
$error=0;
$client = new SoapClient($url);
try
{
$info = $client->__call($method, array($param));
}
catch (SoapFault $fault)
{
$error = 1;
errorReport($fault->faultcode,$fault->faultstring);
die;
/*echo '<script type="text/javascript">alert("Sorry,App Returne the following ERROR:'.$fault->faultcode."-".$fault->faultstring.' We will now take you back to our homepage."); window.location = "'.$_SERVER['PHP_SELF'].'";</script> '; */
}
if($error==1)
{
$xml=$fault->faultstring;
}else{
$xml = $info;
}
return $xml;
Try implementing it and let me know. if it works for you.
Shouldn't the last line be var_dump($response); instead of var_dump($client);
Anyways, you can also try using this to get the result :
$response = $client->GetTransmissionTicket(array($params) );
var_dump($response);
I resolved this problem by switching from SOAP 1.2 to SOAP 1.1:
$this->client = new SoapClient(
$url,
array(
"trace" => TRUE,
"exception" => 0,
"soap_version" => SOAP_1_1,
"cache_wsdl" => WSDL_CACHE_MEMORY,
"local_cert" => 'mycert.pem',
)
);
I will answer my own question so that it helps someone one day. I used nusoap and changed the encoding to utf-8. The code snippet is below:
require_once "nusoap.php";
$client = new nusoap_client("http://interface.--Serivce-Supplier-Link/Service.svc?wsdl", "wsdl");
$client->soap_defencoding = 'UTF-8';
$result = $client->call("GetTransmissionTicket", array( 'agencyNumber' => 13155, 'fullTransmission' => false));
var_dump($result);
Kind Regards
may be little late but could help others. so here it goes:
$params is already an array so you don't have to use array($params) in
$response = $client->__soapCall('GetTransmissionTicket',array($params) );
instead use simple $params while calling.check it like this
$response = $client->GetTransmissionTicket($params);
also use $client->__getTypes(); to verify params to be passed.
use catch to good effect to trace faultstringand faultactor.
at the end if still not getting solution check it with soapUI(a software).

SoapClient + PHP + Sharepoint + Getting images from a list OR GetItemsByIds

I am using SoapClient to pull data out of a sharepoint list. If its a normal text field it works fine and gives me the image. I can even attach the image to the individual list elements and link it into another field and get the image that way. The problem with that is it asks me to log in to my sharepoint account whenever I access the page, which obviously a normal user of my site will not be able to do.
First, if there is a way around this, that will be a sufficient answer because that is my ideal way of doing it.
However, if the better way is to make a picture gallery and then pull the pictures from there then that isn't a problem.
Basically what I need to know is how to use the Imaging library and maybe the GetItemsByIds method? I am very new to soap and sharepoint in general so I appologize for what may be trivial questions but I really need to know how to do this and I can find no resource on the internet that explains what I need to know (if there is one, link it!). Keep in mind, I have to do this in PHP.
Here is some code that I use to pull the list data:
<?php
$authParams = array(
'login' => 'username',
'password' => 'pass'
);
$listName = "{GUID}";
$rowLimit = '500';
$wsdl = "list.wsdl";
$soapClient = new SoapClient($wsdl, $authParams);
$params = array(
'listName' => $listName,
'rowLimit' => $rowLimit;
);
echo file_get_contents($wsdl, FILE_TEXT, stream_context_create(array('http' => array('timeout' => 1))), 0, 1);
$rawXMLresponse = null;
try{
$rawXMLresponse = $soapClient->GetListItems($params)->GetListItemsResult->any;
}
catch(SoapFault $fault){
echo 'Fault code: '.$fault->faultcode;
echo 'Fault string: '.$fault->faultstring;
}
echo '<pre>' . $rawXMLresponse . '</pre>';
$dom = new DOMDocument();
$dom->loadXML($rawXMLresponse);
$results = $dom->getElementsByTagNameNS("#RowsetSchema", "*");
?>
//do the useful thing
<?php
unset($soapClient);
?>
It was an issue with the user permissions. Once we had an account with the correct permissions, it worked fine.

Categories