nuSoap Function is Not a Valid method - php

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)

Related

Basic authorization on PHP soapClient

I am trying to call a function on a web service defined on a Tomcat server, but I can not make the call due to a credentials failure.
The structure of this web service asks for a Basic Authorization embedded on the envelope (not the header itself). Using the SOAPui tool I have no problem to make this call entering the username and password. But using the PHP client is not possible to access the web service.
I have already tried to use nusoal library which actually works, but it doesn't help with the parameters because I can not filter the query. I mean is like this call doesn't use the parameters at all returning all the results.
I would like to give it a try with the default soapClient.
<?php
$username = "user";
$password = "pass";
$wsdl = 'http://192.168.1.185:8080/msw/gestionSolicitudes?wsdl';
$options = array(
'Username' => $username,
'Password' => $password,
);
$client = new SoapClient($wsdl, $options);
$parametros = array("statusId"=>2, "startDate"=>'2019-01-01', "endDate"=>'2019-09-01', "name"=>'Maria');
$result = $client->__soapCall('getSolicitudesLista', $parametros);
foreach ($result as &$valor) {
foreach ($valor as &$solicitud) {
if (is_object($solicitud)) {
echo nl2br (">>>Solicitud init ============================================\r\n");
....
} else {
echo nl2br (">>>Result ============================================\r\n\r\n");
var_dump($solicitud);
echo nl2br (">>>Result ============================================\r\n\r\n");
}
}
}
?>

Magento Integration With T-Hub

am setting up a sand box for a T-Hub Integration with Magento and quickbooks. I've set my life site up locally using WAMP server, and now Its on to trying to tie that local Magento site into T-hub.
The first error that I received stated the
"Connection to Magento store failed. Service authentication failure - Notice: Undefined index: httponly in c:\wamp\www\testsite\appcode\core\mage\Core\Model\Session\Abtract\Varien.php on line 98."
After some searching I found the the general consensus on that one was I had to put an ssl on my local server, done, that problem's gone. Now I'm get a general error message that simply says "Connection to Magento Failed"
I used the test page that atandra included with their files which returned this:
<RESPONSE Version="4.1">
<Envelope>
<Command>GETORDERS</Command>
<StatusCode>9001</StatusCode>
<StatusMessage>
Service authentication failure - Warning: array_key_exists() expects parameter 2 to be array, string given in C:\wamp\www\adamsarms\app\code\core\Mage\Captcha\Model\Observer.php on line 166
</StatusMessage>
<Provider>Magento</Provider>
</Envelope>
</RESPONSE>
Which kicks back to this is the php file:
public function checkUserLoginBackend($observer)
{
$formId = 'backend_login';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
$loginParams = Mage::app()->getRequest()->getPost('login', array());
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
if ($captchaModel->isRequired($login)) {
if (!$captchaModel->isCorrect($this->_getCaptchaString(Mage::app()->getRequest(), $formId))) {
$captchaModel->logAttempt($login);
Mage::throwException(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
}
}
$captchaModel->logAttempt($login);
return $this;
}
This line is the one it directly points to:
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
I'm not sure which direction I need to go to fix this error to make t-hub start talking to magento proper, I've included everything that I've got, if someone needs more information please let me know, I just need a better understanding of what might be causing this error to possibly find a path to fixing it.
This is an issue with a Legacy codebase with the T-Hub extension. It was created for PHP 5.3 & Magento versions 1.4 & below. They really should update this thing since people are using it.
The companies official response is this: http://support4.atandra.com/index.php?/Knowledgebase/Article/View/92/4/magento-array_key_exists-error
Which is horrible because it relies on overriding core files.
What's going on is Mage_Captcha_Model_Observer has an event checkUserLoginBackend() that gets fired. This expects the POST info for 'login' to be a certain format. This is something that has changed over the years since legacy code does not have it in this format.
This is a really hacky fix. But it's better than overriding core magento files.
Change the CheckUser() function of Mage/Thub/Model/Run/Run.php to this (I've removed some of their comments):
public function CheckUser()
{
try {
$username = $this->RequestParams['USERID'];
$password = $this->RequestParams['PASSWORD'];
//here we just set the POST to our specified format..
//which is what the observer model thinks it should be
Mage::app()->getRequest()->setPost('login', array(
'username' => $username,
'password' => $password
));
$user = Mage::getSingleton('admin/user');
$userRole = Mage::getSingleton('admin/role');
if ($user->authenticate($username, $password)) {
$loadRole = $userRole->load($user->getRoles($user));
} else {
print($this->xmlErrorResponse($this->RequestParams['COMMAND'], '9000',
'Order download service authentication failure - Login/Password supplied did not match', $this->STORE_NAME, ''));
exit;
}
} catch (Exception $e) {
$this->Msg[] = "Critical Error CheckUser (Exception e)=" . $e->getMessage(); //BB 11Nov2014
print($this->xmlErrorResponse($this->RequestParams['COMMAND'], '9001',
'Service authentication failure - ' . " " . $e->getMessage(), $this->STORE_NAME, ''));
// End - <TIBB> 13Dec2011
exit;
}
}
Another alternative is to extend the Mage_Captcha_Model_Observer class with your own version that removes those array checks in checkUserLoginBackend().

PHP Fatal Error: Class not found when loading URL

I have a strange bug at the moment in my web service I am coding.
When I am loading an specific url I get a success and error at the same time?
This is what I have in my index.php:
<?php
require_once 'functions/lib.php';
require_once 'core/init.php';
// Ask for request URL that was submitted and define scriptPath. Explode content of REQUEST URL to evaluate validity.
$requestURL = (($_SERVER['REQUEST_URI'] != "") ? $_SERVER['REQUEST_URI'] : $_SERVER['REDIRECT_URL']);
$scriptPath = dirname($_SERVER['PHP_SELF']);
$requestURL = str_replace($scriptPath, "", $requestURL);
$requestParts = explode("/", $requestURL);
// Check for valid api version
$validAPIVersions = array("v1");
$apiVersion = $requestParts[1];
// If API Version not in valid API array return 404, else OK.
if (!in_array($apiVersion, $validAPIVersions)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "API Version not valid";
exit();
}
// Check for valid API endpoint
$validEndPoints = array("tickets");
$endPoint = $requestParts[2];
if (!in_array($endPoint, $validEndPoints)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "Endpoint not valid";
exit();
}
// get the endpoint class name
$endPoint = ucfirst(strtolower($endPoint));
$classFilePath = "$apiVersion/$endPoint.php";
if (!file_exists($classFilePath)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
exit();
}
// load endpoint class and make an instance
try {
require_once($classFilePath);
$instance = new $endPoint($requestParts);
} catch (Exception $e) {
httpResponseCode(500);
echo $GLOBALS['http_response_code'];
exit();
}
and this is the corresponding "Tickets.php"
<?php
echo "OK";
?>
In the last two rows of my index.php, I am loading the specific class (named in the URL). For testing purposes, I have an "echo "OK" in this file. And this is the result when I am loading the URL I need:
http://api.medifaktor.de/v1/tickets
OK
Fatal error: Class 'Tickets' not found in /usr/www/users/kontug/api.medifaktor.de/webservice/index.php on line 45
I get the OK I was expecting AND the error for the Class Tickets, that is not found. Line 45 is
$instance = new $endPoint($requestParts);
Can someone give me a helping hand?
Best
Sebastian
The problem is that you don't have a class "Tickets" defined. After you load the tickets.php file, you are attempting to instantiate a class. Loading a file is not the same thing as defining a class. Within tickets.php (or some other included file), you need to define the class, like so:
class Tickets
{
// some properties here
private $endpoint;
// some methods here
public function __construct($endpoint)
{
$this->endpoint = $endpoint;
}
}
If you're not sure how to construct classes in PHP, read the section in the manual on classes.
Update: I added some example code within the class for version PHP5+.
Try the following for your test, in the 'ticket.php' file add:
class Ticket {
public function __construct()
{
echo 'testing';
}
}
Then make sure you either namespace or require the file.

How to Invoke External PHP Web Services with WSO2 ESB

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..

PHP SOAPClient WCF Error sending parameters

I'm working on a Webservice using PHP SoapClient.
The webservice url is: http://web.abaseguros.com/AutoConnect/ACCatalogos.svc?wsdl
And here is my code:
<?php
ini_set("soap.wsdl_cache_enabled", "0");
$pin = new SoapClient("http://web.abaseguros.com/AutoConnect/ACCatalogos.svc?wsdl");
class Token {
var $usuario;
var $password;
function Token($user,$pass) {
$this->usuario = $user;
$this->password = $pass;
}
}
//User and Password for the token object
$Token = new Token('usuarioWCF','Pa$$w0rd');
//XML 'Entrada' String
$Entrada = "<CAT><NEG>5786</NEG></CAT>";
$result = $pin->ObtenerMarcas($Token,$Entrada);
But PHP prints out the following error message:
Fatal error: Uncaught SoapFault exception: [a:DeserializationFailed] when i execute the script.
The company gave me a sample code written on C#
private void Obtener_Catalogo_ABASeguros()
{
string strEntrada, strSalida;
strEntrada = “<CAT><NEG>5786</NEG></CAT>“; +
ACCatalogosClient proxy = new ACCatalogosClient();
Token token = new Token();
token.usuario = "usuarioWCF";
token.password = "Pa$$w0rd";
try
{
strSalida = proxy.ObtenerMarcas(token, strEntrada);
}
catch (FaultException<Error> ex)
{
txtCotSalida.Text = string.Format("Ocurrio un error en el WCF:\n " +
"Origen: {0}\n "+
"Mensaje: {1}\n "+
"Stack: {2}", ex.Detail.Origen, ex.Detail.Mensaje, ex.Detail.StackTrace);
}
But I'm still unabled to understand how parameters are sent on both languages.
Any Help?
Your Soap client does not know how to deserialize the object Token. You need to convert that token object into a associate array and use that array as parameter to the operation instead.
$pin->ObtenerMarcas(get_object_vars($Token),$Entrada);
I am afraid even you get this error cleared, you will not be successful in working with the service yet. It looks like the a token is required in the soap header instead. the C code you put does not show you everything, it has the implementation encapsulated inside the Proxy class. You need to have a read the documentation is there's any, otherwise you will have to read the imported wsdl files embedded in your provided global wsdl link.

Categories