Trouble creating web service with PHP NuSOAP - php

I'm trying to set up a simple web service but I'm having trouble. The service seems to be available, but I can't seem to return a response. Var_dump on $client shows a connection to the web service, but nothing comes back in response. No errors are caught either.
Any help would be greatly appreciated.
server.php
<?php
require_once ("lib/nusoap.php");
$URL = "https://www.domain.com";
$namespace = $URL . '?wsdl';
$server = new soap_server;
$server->debug_flag = false;
$server->configureWSDL('Test', $namespace);
$server->wsdl->schemaTargetNamespace = $namespace;
function get_message($your_name)
{
if(!$your_name)
{
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
$server->register('get_message');
// create HTTP listener
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
client.php
<?php
$wsdl = "https://www.domain.com/webservice/server.php?wsdl";
require_once ('lib/nusoap.php');
$param = array("your_name" => "Liam");
$client = new SoapClient($wsdl, array("trace" => true));
$response = $client->get_message($param);
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>

There were bugs in the code of client and server files, I have updated the code
server.php
<?php
require_once ("lib/nusoap.php");
$URL = "http://www.domian.com/server.php";
$namespace = $URL . '?wsdl';
$server = new soap_server(); //added ()
$server->debug_flag = false;
$server->configureWSDL('Test', $namespace);
//$server->wsdl->schemaTargetNamespace = $namespace;
function get_message($your_name)
{
if(!$your_name)
{
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
$server->register('get_message',
array('request' => 'xsd:ArrayReq'), // ArrayReq is type for your parameters
array('return' => 'xsd:String'),
'urn:Test',
'urn:Test#get_message',
'rpc',
'encoded',
'show message'); // added request return array
// create HTTP listener
//$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service(file_get_contents('php://input'));
exit();
?>
Client.php
<?php
$wsdl = "http://www.domian.com/server.php?wsdl";
require_once ('lib/nusoap.php');
$param = array("your_name" => "Liam");
$client = new nusoap_client($wsdl); // user nusoap_client() for creating client object
//$client = new SoapClient($wsdl, array("trace" => true));
$response = $client->call('get_message', $param); // use call() to call the server functions
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
it's working!

Related

set soapclient HTTP_METHOD

Im trying to consume a webserivce usnig soapclient.
The instructions for the connection is to use:
request method = "POST";
request ContentType = "application/soap+xml";
This is the code im using to create the client
public function init_client(){
if( $this->env == 'dev'){
$api_url = self::$test_url;
}else{
$api_url = self::$production_url;
}
try{
$options = array(
'soap_version' => SOAP_1_2
);
$this->client = new SoapClient( $api_url , $options );
return true;
}catch(Exception $e){
return $e->getMessage();
}
}
How can i set the client's method and content type ?

Setting proxy in Goutte

I've tried using Guzzle's docs to set proxy but it's not working. The official Github page for Goutte is pretty dead so can't find anything there.
Anyone know how to set a proxy?
This is what I've tried:
$client = new Client();
$client->setHeader('User-Agent', $user_agent);
$crawler = $client->request('GET', $request, ['proxy' => $proxy]);
I have solved this problem =>
$url = 'https://api.myip.com';
$client = new \Goutte\Client;
$client->setClient(new \GuzzleHttp\Client(['proxy' => 'http://xx.xx.xx.xx:8080']));
$get_html = $client->request('GET', $url)->html();
var_dump($get_html);
You thinking rigth, but in Goutte\Client::doRequest(), when create Guzzle client
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body
);
options are not passed when create request object. So, if you want to use a proxy, then override the class Goutte\Client, the method doRequest(), and replace this code on
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body,
$request->getParameters()
);
Example overriding class:
<?php
namespace igancev\override;
class Client extends \Goutte\Client
{
protected function doRequest($request)
{
$headers = array();
foreach ($request->getServer() as $key => $val) {
$key = implode('-', array_map('ucfirst', explode('-', strtolower(str_replace(array('_', 'HTTP-'), array('-', ''), $key)))));
if (!isset($headers[$key])) {
$headers[$key] = $val;
}
}
$body = null;
if (!in_array($request->getMethod(), array('GET','HEAD'))) {
if (null !== $request->getContent()) {
$body = $request->getContent();
} else {
$body = $request->getParameters();
}
}
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body,
$request->getParameters()
);
foreach ($this->headers as $name => $value) {
$guzzleRequest->setHeader($name, $value);
}
if ($this->auth !== null) {
$guzzleRequest->setAuth(
$this->auth['user'],
$this->auth['password'],
$this->auth['type']
);
}
foreach ($this->getCookieJar()->allRawValues($request->getUri()) as $name => $value) {
$guzzleRequest->addCookie($name, $value);
}
if ('POST' == $request->getMethod() || 'PUT' == $request->getMethod()) {
$this->addPostFiles($guzzleRequest, $request->getFiles());
}
$guzzleRequest->getParams()->set('redirect.disable', true);
$curlOptions = $guzzleRequest->getCurlOptions();
if (!$curlOptions->hasKey(CURLOPT_TIMEOUT)) {
$curlOptions->set(CURLOPT_TIMEOUT, 30);
}
// Let BrowserKit handle redirects
try {
$response = $guzzleRequest->send();
} catch (CurlException $e) {
if (!strpos($e->getMessage(), 'redirects')) {
throw $e;
}
$response = $e->getResponse();
} catch (BadResponseException $e) {
$response = $e->getResponse();
}
return $this->createResponse($response);
}
}
And try send request
$client = new \igancev\override\Client();
$proxy = 'http://149.56.85.17:8080'; // free proxy example
$crawler = $client->request('GET', $request, ['proxy' => $proxy]);
You can directly use in Goutte or Guzzle Request
$proxy = 'xx.xx.xx.xx:xxxx';
$goutte = new GoutteClient();
echo $goutte->request('GET', 'https://example.com/', ['proxy' => $proxy])->html();
Use Same method in Guzzle
$Guzzle = new Client();
$GuzzleResponse = $Guzzle->request('GET', 'https://example.com/', ['proxy' => $proxy]);
You can set a custom GuzzleClient and assign it to Goutte client.
When Guzzle makes the request through Goutte uses the default config. That config is passed in the Guzzle construct.
$guzzle = new \GuzzleHttp\Client(['proxy' => 'http://192.168.1.1:8080']);
$goutte = new \Goutte\Client();
$goutte->setClient($guzzle);
$crawler = $goutte->request($method, $url);
For recent versions use:
Goutte Client instance (which extends Symfony\Component\BrowserKit\HttpBrowser)
use Symfony\Component\HttpClient\HttpClient;
use Goutte\Client;
$client = new Client(HttpClient::create(['proxy' => 'http://xx.xx.xx.xx:80']));
...

Getting blank data in a SalesForce integration with PHP

I am trying integration with SalesForce using SOAP webservice.
I can build a connection with PHP and SOAP after that if I'm trying to call my method that is authenticate user, I am not getting any data, I'm getting blank.
Below is the code
define("USERNAME", "xxxxxxxxxxx");
define("PASSWORD", "xxxxxxxxxxx");
define("SECURITY_TOKEN", "xxxxxxxxxxx");
require_once ('soapclient/SforcePartnerClient.php');
require_once ('soapclient/SforceHeaderOptions.php');
// Login
$sfdc = new SforcePartnerClient();
$SoapClient = $sfdc->createConnection('soapclient/PartnerWSDL.xml');
$loginResult = false;
$loginResult = $sfdc->login('USERNAME', 'PASSWORD' . 'SECURITY_TOKEN');
// Define constants for the web service. We'll use these later
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", 'CustomerPortalServices');
define ("_WS_WSDL_", _WS_NAME_ . '.xml');
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
//echo _WS_ENDPOINT_;
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
// SOAP Client for Web Service
$client = new SoapClient('http://localhost/SFDC/soapclient/CustomerPortalServices_WSDL.xml');
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
// username and password sent from Form
echo $myusername=addslashes($_POST['login_username']);
echo $mypassword=addslashes($_POST['login_password']);
try {
// call the web service via post
$wsParams=array(
'username'=>'abc#gmail.com',
'password'=>'mypassword'
);
print_r($wsParams);
$response = $client->authenticateUser($wsParams);
// dump the response to the browser
print_r($response);
//header("location: index.php");
// this is really bad.
} catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Ooop! Error: <b>" . $errors . "</b>";
die;
}
This is the method i am calling
global class CustomerPortalServicesNew {
webService static Summary authenticateUserNew(String uname,String passwd) {
System.debug('##'+'Entered in the authenticateUser');
List<contact> checkConList = new List<Contact>([select id,Email, Password__c, AccountId from contact where Email =:uname]);
System.debug('##'+'contact '+checkConList);
for(contact c:checkConList){
system.debug('##'+'Iterating in contactList'+checkConList);
if(c.Password__c==passwd){
system.debug('##'+c.AccountId);
return getAccountSummary(c.AccountId);
}
else{
system.debug('##'+'password has not matched');
return null;
}
}
system.debug('##'+'class finished');
return null;
}
I am getting response like this
object(stdClass)[8]
public 'result' =>
object(stdClass)[9]
not getting data
I think you need to print:
print_r($response->result);
If it's not working, try a var_dump($response)

return utf-8 (farsi) string from nuSOAP webservice

i wrote a very simple webservice that you can see it's code below:
SERVER :
<?php
ini_set('error_reporting', E_STRICT);
require_once("nuSOAP/lib/nusoap.php");
$namespace = "http://localhost/webservice/index.php";
// create a new soap server
$server = new soap_server();
$server->soap_defencoding = 'utf-8';
$server->decode_utf8 = false;
// configure our WSDL
$server->configureWSDL("HelloExample");
// set our namespace
$server->wsdl->schemaTargetNamespace = $namespace;
//Register a method that has parameters and return types
$server->register(
// method name:
'HelloWorld',
// parameter list:
array('name'=>'xsd:string'),
// return value(s):
array('return'=>'xsd:string'),
// namespace:
$namespace,
// soapaction: (use default)
false,
// style: rpc or document
'rpc',
// use: encoded or literal
'encoded',
// description: documentation for the method
'Simple Hello World Method');
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
// pass our posted data (or nothing) to the soap service
$server->service($POST_DATA);
exit();
?>
CLIENT :
<!doctype html>
<html>
<head>
<title>Title</title>
<meta charset="utf-8"/>
</head>
<body>
<?php
require_once("nuSOAP/lib/nusoap.php");
$client = new nusoap_client('http://localhost/webservice/index.php?wsdl');
$client->soap_defencoding = 'UTF-8';
$client->decode_utf8 = true;
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
die();
}
$parameters = array('name' => "محمد");
$result = $client->call('HelloWorld', $parameters);
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
die();
}
else
{
echo $result;
}
?>
</body>
</html>
this Should return Hello محمد But this return Hello ????
is this unicode problem?
any help for fixing this will appreciated
i fixed it myself :)
use this for Server code :
$server->soap_defencoding = 'UTF-8';
$server->decode_utf8 = false;
$server->encode_utf8 = true;
and for Client code :
$client->soap_defencoding = 'UTF-8';
$client->decode_utf8 = false;

PHP SOAP webservice with NuSOAP gives no result if WSDL is configured

I have a php soap webservice which I've created with using NuSOAP. I use the file 'test.php' to test it in the browser as 'http://www.mydowmain.com:8080/webservice/5/test.php'.
My code:
webservice.php
<?php
require_once('../lib/nusoap.php');
$server = new nusoap_server();
$server ->configureWSDL('server', 'urn:server'); //this line causes to 'no result'
$server ->wsdl->schemaTargetNamespace = 'urn:server'; //this line causes to 'no result'
$server -> register('getData');
function getData ()
{
$items = array(array("item1"),array("item2"));
return $items;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server ->service($HTTP_RAW_POST_DATA);
?>
test.php
<?php
require_once('../lib/nusoap.php');
$client = new nusoap_client("http://www.mydowmain.com:8080/webservice/5/webservice.php?wsdl");
$result = $client ->call('getData');
print_r($result);
?>
Problem:
If I remove these lines
$server ->configureWSDL('server', 'urn:server');
$server ->wsdl->schemaTargetNamespace = 'urn:server';
it shows me the result fine. Otherwise I get a blank screen, get nothing. But I really need to configure the WSDL.
How can I edit the webservice.php so that the WSDL will be configured and I can get the result array on the test.php ?
To see error information about client you can add this :
$result = $client->call('getData');
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2>' . $err;
// At this point, you know the call that follows will fail
exit();
}
else
{
echo $result;
}
After that, in the server.php, maybe the register needs more information about the return value.
$server->register('getData',
array("response"=>"xsd:string"),
'http://www.mydowmain.com:8080'
);
Try changing this:
$server ->wsdl->schemaTargetNamespace = 'urn:server';
Into this:
$server ->wsdl->schemaTargetNamespace = $namespace;
and define $namespace on top of it. That did the trick for me.
This is my code of my NuSOAP webservice:
require_once("lib/nusoap.php");
$namespace = "http://localhost:8080/Testservice/service.php?wsdl";
$server = new soap_server();
$server->configureWSDL("TestService");
$server->wsdl->schemaTargetNamespace = $namespace;

Categories