How to Invoke External PHP Web Services with WSO2 ESB - php

Hello WSO2 ESB community,
I have a services in PHP. I have invoked into WSO2ESB through WSDL proxy and no problem with that. But, when I tried to call it from either SOAP client or 'try this services' built in WSO2ESB, that services can't be called and show an error :
org.apache.axis2.AxisFault: Read timed out
Can you help me what's wrong..? As a note, that's PHP services is goes well when call directly from SOAP client, not through WSO2ESB..
this is my PHP services code..
**
<?php
//call library
require_once ('../nusoap/lib/nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
$server->configureWSDL('hellowsdl', 'urn:hellowsdl');
// Register the method to expose
$server->register('hello', // method name
array('name' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:hellowsdl', // namespace
'urn:hellowsdl#hello', // soapaction
'rpc', // style
'encoded', // use
'Says hello to the caller' // documentation
);
// Define the method as a PHP function
function hello($name) {
return 'Hellooo, ' . $name;
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
**
and the client look like this one..
<?php
require_once ('../nusoap/lib/nusoap.php');
// Create the client instance
$wsdl="http://localhost:8280/services/HelloNuSOAP?wsdl";
$client =new nusoap_client($wsdl,true);
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$result = $client->call('hello', array('name' => 'Scott'));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $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($result);
echo '</pre>';
}
}
?>
on the part of client code,
$wsdl="http://localhost:8280/services/HelloNuSOAP?wsdl";
is WSDL address from WSO2ESB. The result when we called it is "request time out".
If we change that with direct WSDL address from services server where the services code take placed, let's say
$wsdl="http://localhost/ws/hello_serper_nusoap.php"
the result is server will be invoked succesfully and we'll got a result.
So, we can make a conclusion that WSO2ESB can't call that PHP web services. Is there any way to invoke php web services on WSO2ESB?

Wow.. i have resolved my problem above..!
the only one cause is because my PHP services is running on IIS server.
I have tried change my server to Apache (with wamp).. then access it with SOAPUI through WSO2ESB.
Then..
Viola... WSO2 ESB read that PHP services successfully without any problem. I only should add my PHP client with PHP cURL Extension to access it if PHP client will be used.
I don't know what happen between IIS and WSO2ESB. Hopefully it can useful for others.
Thank You..

Related

SOAP API: PHP Code doesn't work, but SOAP UI works

I'm trying to create a rental module for my work's website. When I use the same parameters in SmartBear's SOAP UI, it works. So, I'm assuming that it's something to do with my code, but I cannot find the error.
<?php //Submit Reservation
require("connect.php");
$sessionId = $_SESSION['sessionId'];
$moveInDate = date("yy-m-d", strtotime($_POST['moveIn']));
$billDate = date("d", strtotime($_POST['moveIn']));
$rentalOptions = array(
"customer.company" =>$company,
"account.startDate"=> $moveInDate,
"contact.firstName"=>$_POST['fname'],
"contact.lastName"=>$_POST['lname'],
"contact.companyName"=>$_POST['companyName'],
"contact.street1"=>$_POST['street'],
"contact.street2"=>"",
"contact.city"=>$_POST['city'],
"contact.state"=>$_POST['state'],
"contact.zip"=>$_POST['zip'],
"contact.country"=>"US",
"phone.1" => $_POST['mobile'],
"contact.email"=>$_POST['email'],
"account.currency"=>"1",
"account.billDay"=> $billDate,
"user.paymentMethod"=>"1",
"user.draftDay"=>"",
"unit.id"=>$_POST['unit-name'],
"postAccount"=>"Y",
"promotionId"=>$_POST['promo'],
"insuranceId"=>$_POST['insurance']
);
var_dump($rentalOptions);
echo "<br/>". $sessionId ."<br/>Return";
$client = new SoapClient("https://api.doorswap.com/service/system.wsdl");
// Make API Call
$dsReceiver = "customer";
$dsAction = "saveNewCustomer";
$result = $client->makeReceiverCall($sessionId, $dsReceiver, $dsAction, $rentalOptions);
//if($result["success"] == "true") {
//}
?>
The var_dump() and print_r() displays correct variables from the previous form. In fact, ALL variables are correctly output. I just do not understand WHY it isn't working. It's not giving me an error, it's just not POSTING.
FYI: I have tried using javascript SOAP and I run into similar issues. The code is right, the variables are correct, but the addition to the system is not going through.
I'm open to trying anything.
Initialization of the SoapClient class
First of all inialize your soap client the right way. The soap client class takes several options to debug your application. In the following example a soap client is initalized with some options, that will make your life more easy when testing.
try {
$client = new SoapClient('https://api.doorswap.com/service/system.wsdl', [
'exceptions' => true,
'trace' => true,
]);
} catch (SoapFault $fault) {
var_dump($fault->getMessage());
if ($client instanceof SoapClient) {
var_dump(
$client->__getLastRequest(),
$client->__getLastResponse()
);
}
}
As you can see the soap client class is initialized with different option parameters. The exception option is set to true so that the soap client class throws exceptions, when an error occurs. That 's why the code is wrapped in a try and catch block. The trace option allows us to see, what the last request and response looks like. If the soap client was initialized you can use the build in methods __getLastRequest() and __getLastResponse() to see what the sent and received xml looks like. Keep in mind, that these can be empty if the xml wasn 't compiled by the client.
The makeReceiverCall method was a "name"/"value" system. So the above array of $rentalOptions SHOULD have been done as such. This is currently working, and has been flawless in execution.
$rentalOptions = array(
array("name"=> "customer.company","value"=> $company),
array("name"=> "account.startDate", "value"=> $moveInDate),
...
);
This was the error that I had run into and finally figured out. Thank you to all those who tried to help.

PHP Soap calling Error

I am trying to connect to webservice using SOAP / wsdl, but I constantly get the error. I am new in soap-api in php. I have a document of api detail, it shows:
public WSGetCalendarFareResponse GetCalendarFare(WSGetCalendarFareRequest calanderFareRequest)
I made my code accordingly but still found error/exception. Please review my php code in following:
$wsdl = "http://api.abc.com/xyz/service.asmx?wsdl"; // This is a test Web Service URL
$h = array();
$opta["GetCalendarFare"]["request"]= array(
"Origin"=>"DEL",
"Destination"=>"IXR",
"DepartureDate"=>"2015-05-01T00:00:00",
"ReturnDate"=>"2015-05-01T00:00:00",
"Type"=>"OneWay",
"CabinClass"=>"All",
"PreferredCarrier"=>"",
"AdultCount"=>1,
"ChildCount"=>1,
"InfantCount"=>"0",
"SeniorCount"=>"0",
"PromotionalPlanType"=>"Normal",
"IsDirectFlight"=>false
);
$client_header = new SoapHeader('http://192.168.0.0/TEST/BookingAPI','AuthenticationData',$hparams,false);
$cliente = new SoapClient($wsdl, array('trace' => 0));
$cliente->__setSoapHeaders(array($client_header));
try{
$h= (array)$cliente->__call('GetCalendarFare',$opta);
}catch(Exception $e)
{
echo '<pre>';
var_dump($e);
}
When I execute my code, it returns following error:
"System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at BookingAPI.WSCalendarFareInput(WSGetCalendarFareRequest calanderFareRequest) in c:\inetpub\wwwroot\api.tektravel.com\TboApi_V7\App_Code\Service.cs:line 4544
at BookingAPI.GetCalendarFare(WSGetCalendarFareRequest calanderFareRequest) in c:\inetpub\wwwroot\api.tektravel.com\TboApi_V7\App_Code\Service.cs:line 4360
Can anyone please suggest that where problem exists? It hit & try many times but couldn't get the error point.
Can you debug the execution of your POST on the server side? It is heavy guessing from my side, but I assume that you do not set a mandatory value in the request, which the server needs to deserialize your object. Hence the NullReferenceException.
Problem has resolved.
The Request array should be like this:
$opta["GetCalendarFare"]["calanderFareRequest"]= array(
"Origin"=>"DEL",
"Destination"=>"IXR",
"DepartureDate"=>"2015-05-01T00:00:00",
"ReturnDate"=>"2015-05-01T00:00:00",
"Type"=>"OneWay",
"CabinClass"=>"Economy",
"PreferredCarrier"=>"",
"AdultCount"=>1,
"ChildCount"=>1,
"InfantCount"=>"0",
"SeniorCount"=>"0",
"PromotionalPlanType"=>"Normal",
"IsDirectFlight"=>false
);

Get method name from soap service call

I have a working soap service with several methods available. I am wondering if it is possible to get the name of the method that the user contacting the service is requesting; for example:
try{
$soapServer = new Zend_Soap_Server('http://path-to-service/wsdl');
$soapServer->setClass('My\Soap\Server\Class');
$soapServer->handle();
// is something like this available? :
// $callName = $soapServer->getLastRequestedMethod();
// or
// $callName = $soapServer->getMethod();
}catch(SoapFault $e){
echo $e->getMessage();
}
I didn't see anything like this in the docs # zend or php.net, but just thought I would check to see if anyone knows a way to do this; would be useful for logging purposes. Thanks!
Zend_Soap_Server supports a getLastRequest() method. Example usage would be:
$soapServer = new Zend_Soap_Server('http://path-to-service/wsdl');
$soapServer->setClass('My\Soap\Server\Class');
$soapServer->handle();
$lastRequestXML = $soapServer->getlastRequest()`;

PHP webservice request and response

I'm using PHP 5.3, and trying to develop a simple web service that gets some parameters with POST method and has a response.
function start(){
getAndValidateParams();
global $response;
echo json_encode($response);
}
function getAndValidateParams(){
// token (mandatory)
if(isset($_POST[PARAM_TOKEN])){
echo 'got your token';
}else{
$response[ERROR_CODE] = ERR2_INVALID_TOKEN;
$response[DESCRIPTION] = CODE2_DESC;
}
}
I'm trying to test that with Postman:
The problems:
1. About the Xdebug HTML I saw the following question, If I turn the var_dump off, will it disable usage of var_dump() inside my php code? (I want to be able use it for debugging but not seeing that in the response).
2.Also I have a problem to pass the parameter 'token', I don't see it in getAndValidateParams().
Any help will be appreciated.
I have used your function to just get insight in this and for tesing you can use also there is Advanced REST client in chrome similar to postMAN that you are using --
use the below lines to debug this --
function start(){
$response = getAndValidateParams();
return json_encode($response);
}
// calling function ends here
// statrt another function that is being called
function getAndValidateParams(){
// token (mandatory)
// print_r($_POST);die; // just for debug purpose
if(isset($_POST[PARAM_TOKEN])){
$response[ERROR_CODE] = 0;
$response[DESCRIPTION] = "Success";
$response[DEtail] = $yourdetailarr; // array of data that you want to retuen
}else{
$response[ERROR_CODE] = ERR2_INVALID_TOKEN;
$response[DESCRIPTION] = CODE2_DESC;
}
return $response;
}
/// ends here
check the response here by calling start function .

nuSoap Function is Not a Valid method

When trying to instantiate my nuSoap method authenticateUser, it says:
Fatal error: Uncaught SoapFault exception: [Client] Function ("authenticateUser") is not a valid method for this service in /Applications/MAMP/htdocs/projo/dev/home.php:14
But when I replace that method name for one that already works, everything works just fine. So I think the instantiation syntax isn't wrong.
/*-----------
Authenticate User
------------*/
$server->register(
// method name
'authenticateUser',
// input parameters
array('sessionUserName' => 'xsd:string', 'sessionHash' => 'xsd:string', 'user' => 'xsd:string', 'pass' => 'xsd:string'),
// output parameters
array('return' => 'xsd:string'),
// namespace
$namespace,
// soapaction
$namespace . '#authenticateUser',
// style
'rpc',
// use
'encoded',
// documentation
'authenticates a user and returns a json array of the user info'
);
function authenticateUser($sessionUserName, $sessionHash, $user, $pass)
{
//Check to see if a countryCode was provided
if ($sessionUserName != '' && $sessionHash != '' && $user == $GLOBALS['wsUser'] && $pass == $GLOBALS['wsPass'])
{
$suid = 'AUTH'.$GLOBALS['guid'].'SESSION';
$database = new SQLDatabase();
$database->openConnection();
$database->selectDb();
//Query
$sql = "SELECT * FROM members WHERE member_email='" . $sessionUserName . "' LIMIT 1";
//Query MySQL
$return = $database->query($sql);
$userDetails = $database->fetch_array( $return );
if(!empty($userDetails)) {
$userDetails[0]['authSession'] = $suid;
$newArr = $userDetails[0];
$response = json_encode($newArr);
}
/*print $sql.'<br /><pre>';
print_r($response);
echo '</pre>';*/
//Throw SQL Errors
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
//Return on Success
return $response;
//Close Connection
mysql_close($con);
}
else
{
return 'Error: You must supply all of the inputs!x';
}
}
There are two things I can think of that would cause this error:
More likely: my registration of the function is somehow incorrect, even though the wsdl gui shows that the function is registered correctly and I've been able to successfully consume the method via the SoapUI program.
Less likely: somehow, the function isn't broken anymore, but its cached and so I'm seeing an old error.
The Question: When trying to consume this soap service method via PHP, why do I get an output error stating that this function doesn't exist in the service, when it clearly is?
Set
ini_set("soap.wsdl_cache_enabled", "0");
In every file you use soap from, or set wsdl_cache_enabled
to 0 in your php.ini file.
[soap]
; Enables or disables WSDL caching feature.
soap.wsdl_cache_enabled=0
If you are on Linux, you can also directly delete the cached wsdl file from /tmp/ dir
It was the CACHE!!! stupid. All I had to do was close my computer and go to bed. When I woke up, I ran the file again and it worked like a charm.
This is the second time this has happened with a function in a SOAP service.
Now I need to know how to clear the cache of a soap service. (nuSoap)

Categories