catch error from a SOAP? - php

How to catch an error from a SOAP?
How can I avoid the fatal error and convert it to my own error.. In this example it's a SERVER_BUSY
code
class Validate_vatno {
private $client = null;
private $options = array(
'debug' => false
);
public function __construct(){
$this->client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', array('trace' => true));
}
public function check($country, $vatno){
$result = $this->client->checkVat(array(
'countryCode' => $country,
'vatNumber' => $vatno
));
if(!empty($this->options['debug'])){
echo '<pre>'.htmlentities($this->client->__getLastResponse()).'</pre>';
}
if($result->valid){
list($denomination, $name) = explode(' ', $result->name, 2);
return array(
'denomination' => utf8_decode($denomination),
'name' => ucwords(utf8_decode($name)),
'address' => ucwords(utf8_decode($result->address)),
);
}
else{
return array();
}
}
}
$vatValidation = new Validate_vatno();
if($return = $vatValidation->check('DK', 33214944)){
echo '<h1>valid one!</h1>';
echo 'denomination: ' . $return['denomination']. '<br/>';
echo 'name: ' . $return['name']. '<br/>';
echo 'address: ' . $return['address']. '<br/>';
}
else{
echo '<h1>Invalid VAT</h1>';
}
error
Fatal error: Uncaught SoapFault exception: [soapenv:Server] { 'SERVER_BUSY' } in /var/www/

Review how to handle exceptions
Throwing and Catching a Exception
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>

Related

Invalid likes count for Instagram Posts in PHP

I am using the below function to get the like_count and the comments_count of user's last 10 instagram posts. However it returns invalid amounts. When I visit the instagram profile and add up the likes of last 10 posts it shows a greater value than the value recorded in the database. I was wondering if I have to pass any additional parameters with the business_discovery request?
Any help is appreciated.
/**
* Get post engagment ratio
*/
public function getPostEngagmentRatio()
{
try {
$userResponse = $this->fb->get(
'/'.$this->instagram_user_id.'?fields=username',
$this->page_access_token
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $userResponse->getGraphNode();
$userResponse = $graphNode->asArray();
if (empty($userResponse)) {
$response = array(
'status' => 'error',
'message' => 'not able to find instagram user'
);
return $response;
}
$this->instagram_user_name = $userResponse['username'];
try {
$businessDiscoveryResponse = $this->fb->get(
'/'.$this->instagram_user_id.'?fields=business_discovery.username('.$this->instagram_user_name.'){followers_count,media_count,media{comments_count,like_count}}',
$this->page_access_token
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $businessDiscoveryResponse->getGraphNode();
$businessDiscoveryResponse = $graphNode->asArray();
if (empty($businessDiscoveryResponse)) {
$response = array(
'status' => 'error',
'message' => 'not able to get user business discovery data'
);
return $response;
}
if (count($businessDiscoveryResponse['business_discovery']['media']) > 10) {
$total_posts = 10;
$breakloop = true;
} else {
$total_posts = count($businessDiscoveryResponse['business_discovery']['media']);
$breakloop = false;
}
$posts = array(
'likes' => 0,
'comments' => 0,
'total_posts' => $total_posts,
'engagement_ratio' => 0,
);
$posts['followers_count'] = $businessDiscoveryResponse['business_discovery']['followers_count'];
foreach ($businessDiscoveryResponse['business_discovery']['media'] as $key => $value) {
if ($breakloop && $key == 10) {
break;
}
//bug fix : undefined index like_count
if (isset($value['like_count'])) {
$posts['likes'] += $value['like_count'];
}
if (isset($value['comments_count'])) {
$posts['comments'] += $value['comments_count'];
}
}
return $posts;
}

Fatal error: Uncaught Exception: Response has unsuccessful status

I am trying to send SMS through RingCentral. This is the error I am getting below.
Fatal error: Uncaught Exception: Response has unsuccessful status in /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Http/Client.php:39 Stack trace: #0 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Platform/Platform.php(276): RingCentral\SDK\Http\Client->send(Object(GuzzleHttp\Psr7\Request)) #1 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Platform/Platform.php(363): RingCentral\SDK\Platform\Platform->sendRequest(Object(GuzzleHttp\Psr7\Request), Array) #2 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Platform/Platform.php(183): RingCentral\SDK\Platform\Platform->requestToken('/restapi/oauth/...', Array) #3 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/includes/ring-central.class.php(26): RingCentral\SDK\Platform\Platform->login(Array, '#Gc090486', '101') #4 /Applicati in /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Http/Client.php on line 50
<?php
use RingCentral\SDK\SDK;
define("FAILED", 1);
define("LOCKED", 2);
class RingCentralConnection {
private $_sdk;
private $_platform;
function __construct($clientId, $secret) {
}
//https://platform.ringcentral.com/restapi/v1.0/account/159048008/extension/171857008/call-log?dateFrom=2012-08-26
public function sendSMS($from, $to, $text) {
$_credentials = require (getPluginDir().'/includes/credentials.php');
$_sdk = new SDK($_credentials['appKey'], $_credentials['appSecret'], $_credentials['server'], '2FA Demo', '1.0.0');
//print_r($_sdk);
$_platform = $_sdk->platform();
try {
$_platform->login($_credentials['username'], $_credentials['extension'], $_credentials['password']);
// $code = generateRandomCode(6);
// $myNumber = $_credentials['username'];
// try {
// $response = $_platform->post('/account/~/extension/~/sms', array(
// 'from' => array('phoneNumber' => $myNumber),
// 'to' => array(array('phoneNumber' => $to)),
// 'text' => $message
// ));
// $status = $response->json()->messageStatus;
// echo $status;
// if ($status == "SendingFailed" || $status == "DeliveryFailed") {
// //$db->close();
// createResponse(new Response(FAILED, "RC server connection error. Please try again."));
// } else {
// //$timeStamp = time();
// //$query = "UPDATE users SET code= " . $code . ", codeexpiry= " . $timeStamp . " WHERE email='" . $email . "'";
// //$db->query($query);
// //$db->close();
// createResponse(new Response(LOCKED, $message));
// }
// } catch (ApiException $e) {
// //$db->close();
// $this->createResponse(new Response(FAILED, "RC server connection error. Please try again in."));
// }
} catch (ApiException $e) {
//$db->close();
//print_r($e);
$this->createResponse(new Response(FAILED, "RC server connection error. Please try again out."));
}
}
function createResponse($res) {
$response = json_encode($res);
echo $response;
}
function databaseError() {
$res = new Response(UNKNOWN, "Unknown database error. Please try again.");
$response = json_encode($res);
die($response);
}
}
class Response {
function __construct($error, $message) {
$this->error = $error;
$this->message = $message;
}
public $error;
public $message;
}
//credentials
return array(
'username' => '+13128589951',
'extension' => '101', // extension number
'password' => '',
'appKey' => '',
'appSecret' => '',
'server' => 'https://platform.devtest.ringcentral.com'// for production - https://platform.ringcentral.com
);

php mongodb findandmodify not working

I am using php and mongodb. I want to use findandmodify. My field is { "_id" : ObjectId("58d37e612d4ffa498b99c2d4"), "userid" : "1234", "active_time" : "hai" }
I want to modify active_time. For example change the value "hai" to "1234"
I am using MongoDB\Driver\Manager.
try {
$mng = new MongoDB\Driver\Manager("mongodb://username:password#localhost:27017/db");
$userid = '1234';
$retval = $mng->findAndModify(
array("userid" => $userid), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
$command = new MongoDB\Driver\Command($retval);
$cursor = $manager->executeCommand('db.online', $command);
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
It shows the error is
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::findAndModify()
in line
$retval = $mng->findAndModify(
array("userid" => $userid), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
How it possible? please help me?
I got the answer. Change the findAndModify to update. The modified code is shown below.
$bulk->update(
array("userid" => '1234'), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
$mng->executeBulkWrite("browser.online", $bulk);
if(!empty($mng)) {
echo "success";
} else {
echo "not";
}

PHP - Don't load the page if exception is caught

I'm new to OO PHP...I'm trying to create a PHP class called MyClass and some methods that should:
validate that parameters are numeric
validate that parameters are defined
if any of the above fail I need to send an exception with explanation
When I call the MyFunction method like this:
$quotation = new Quotations\MyClass();
echo $quotationResult = $quotation -> MyFunction('A', 'B', 2, 'a');
to test if it will throw an exception but for some reason page doesn't load saying - "localhost is currently unable to handle this request". But when I call it like this:
$quotation = new Quotations\MyClass();
echo $quotationResult = $quotation -> MyFunction('A', 'B', 2, 3);
it works fine (I can see blank page).
Why it doesn't allow me to print an exception in the browser?
My script:
<?php
namespace Quotations;
class MyClass {
var $is_number;
var $is_defined;
private $number;
private $defined;
private function isNumeric($w, $c){
if(is_numeric($w) && is_numeric($c)){
$number = true;
}
else{
$number = false;
}
return $number;
}
private function isDefined($t, $f, $w, $c){
if(isset($t, $f, $w, $c)){
$defined = true;
}
else{
$defined = false;
}
return $defined;
}
function MyFunction($to, $from, $weight, $cube) {
try{
if(!$this -> isNumeric($weight, $cube)){
throw new InvalidArgumentException('Arguments are not numeric');
}
if(!$this -> isDefined($to, $from, $weight, $cube)){
throw new BadMethodCallException('Arguments are missing');
}
}catch(InvalidArgumentException $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}catch(BadMethodCallException $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}
?>
Use backslashes before the execption names to look for them in the global namespace. Otherwise, it looks for them in the Quotations namespace.
function MyFunction($to, $from, $weight, $cube) {
try {
if(!$this -> isNumeric($weight, $cube)){
throw new \InvalidArgumentException('Arguments are not numeric');
}
if(!$this -> isDefined($to, $from, $weight, $cube)){
throw new \BadMethodCallException('Arguments are missing');
}
} catch(\InvalidArgumentException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} catch(\BadMethodCallException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
First step is to enable error reporting -
error_reporting(E_ALL);
ini_set("display_errors", 1);.
From looking at your code you seem to be missing a closing bracket your code should look like this.
namespace Quotations;
class MyClass {
var $is_number;
var $is_defined;
private $number;
private $defined;
private function isNumeric($w, $c) {
if(is_numeric($w) && is_numeric($c)){
$number = true;
}
else {
$number = false;
}
return $number;
}
private function isDefined($t, $f, $w, $c){
if( isset( $t, $f, $w, $c ) ){
$defined = true;
}
else {
$defined = false;
}
return $defined;
}
function MyFunction($to, $from, $weight, $cube) {
try {
if(!$this -> isNumeric($weight, $cube)){
throw new InvalidArgumentException('Arguments are not numeric');
}
if(!$this -> isDefined($to, $from, $weight, $cube)){
throw new BadMethodCallException('Arguments are missing');
}
} catch(InvalidArgumentException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} catch(BadMethodCallException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}
Edit:
I saw you said in the comments you have added the } and still no luck so I looked through your code and found the following problem
So this is my last solutions I can think of xD
function MyFunction( $to, $from, $weight, $cube ) {
try
{
try
{
if( !$this->isNumeric( $weight, $cube ) ) {
throw new \InvalidArgumentException( 'Arguments are not numeric' );
}
} catch ( \InvalidArgumentException $e ) {
echo 'Error: ' . $e->getMessage();
}
try
{
if( !$this->isDefined( $to, $from, $weight, $cube ) ){
throw new \BadMethodCallException( 'Arguments are missing' );
}
} catch ( \BadMethodCallException $e ) {
echo 'Error: ' . $e->getMessage();
}
} catch ( Exception $e ) {
echo 'Error: ' . $e->getMessage();
}
}
Hope this helps

codeigniter nusoap client error: wsdl error: XML error parsing WSDL Mismatched tag

This is my controller.
class Cteam extends MY_Controller {
//This is my server
public function server(){
if($this->uri->rsegment(3) == "wsdl") {
$_SERVER['QUERY_STRING'] = "wsdl";
} else {
$_SERVER['QUERY_STRING'] = "";
}
//$ns= site_url()."cteam/cteam/server/wsdl";
$ns= site_url()."cteam/cteam/wsdl";
$endpoint = site_url()."cteam/cteam/server/wsdl";
$this->load->library("Nusoap_library"); //load the library here
$this->load->library('xmlrpc');
$this->nusoap_server = new soap_server();
$this->nusoap_server->configureWSDL('sever','urn:'.$ns,$endpoint);
$this->nusoap_server->wsdl->schemaTargetNamespace='urn:'.$ns;
$input_array = array ('count' => 'xsd:integer', 'type' => "xsd:string"); // method parameters
$return_array = array ("fruit" => "xsd:string");
$this->nusoap_server->register(
'fruits',
$input_array,
$return_array,
"urn:SOAPServerWSDL",
"urn:".$ns."/fruits",
"rpc",
"encoded",
"Fruit Types"
);
function fruits($count,$type){
switch($type){
case 'red':
return $count." Apple";
break;
case 'yellow':
return $count." banana";
break;
}
}
$this->nusoap_server->service(file_get_contents("php://input"));
}
//This is my client
function test_soap2(){
$this->load->library("Nusoap_library");
$n_params = array("count" => 4, "type" => "red");
$this->nusoap_client = new nusoap_client('http://localhost/desimd/cteam/cteam/wsdl/',array('soap_version' => SOAP_1_1));
$this->nusoap_client->soap_defencoding = 'UTF-8';
$err = $this->nusoap_client->getError();
if ($err){
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
$result = $this->nusoap_client->call('fruits', array('parameters' => $n_params));
echo $result;
// Check for a fault
if ($this->nusoap_client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result1);
echo '</pre>';
} else {
// Check for errors
$err = $this->nusoap_client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result1);
echo '</pre>';
}
}
}
}
Controller is located in controller/cteam/ folder.
This is my router:
$route['cteam/cteam/wsdl'] = 'cteam/cteam/server/wsdl';
When I call server: http://localhost/desimd/cteam/cteam/wsdl/
I am getting the xml.
When I call client: http://localhost/desimd/cteam/cteam/test_soap2/
It is giving me error: wsdl error: XML error parsing WSDL.... Mismatched tag
Can anybody help me?

Categories