PhP Webservices development - php

I was developing a PhP webservice using NuSOAP library but facing an error. I couldn't understand the error. If anyone knows a solution, please help. Following is my code.
------ server.php ------
<?php
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the server instance
$server = new soap_server;
// Register the method to expose
$server->register('hello');
// Define the method as a PHP function
function hello($name)
{
return 'Hello, ' . $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);
?>
------ client.php ------
<?php
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the client instance
$client = new nusoap_client('server.php');
// 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>';
}
}
?>
When I run the client, following error arises.
Error
no transport found, or selected transport is not yet supported!

When you instantiate the nusoap_client:
new nusoap_client('server.php');
Your constructor parameter 'server.php' does not look valid to me. It's supposed to be a valid endpoint:
docs
So, wherever your 'server.php' actually is. Maybe if it's on the same machine running client.php, it might be something like: http://127.0.0.1/app/server.php

I think you should read NuSoap documents more accurate. Some wrongs i found in your code:
An array will be passed to your method and you've used string parameter $name for hello method.
$name['name']; //is correct!
Client should call some instances or web url not HDD url(server.php).
new nusoap_client(SOME_IP_OR_HOSTNAME . '/server.php'); //is correct!
require_once 'server.php';
new nusoap_client($server); //is correct!
new nusoap_client(WSDL_INSTANCE_OBJECT); //is correct!
new nusoap_client('server.php'); //is incorrect!
for more information read NuSoap document.

Related

How to fix XML-RPC Client returning fault code in PHP?

It is my first experience with XML-RPC. I am having a problem retrieving the data from the server as it's being returned to client as fault code. Why is this happening? Do I also need to make an XML-RPC Server file or is it already set up here?
$beerClient = new xmlrpc_client('localhost:1234/341/xmlrpc-lab/xmlrpcserver.php','alvin.ist.rit.edu:8100',1234);
Is it because the data does not match the server return type or something else I'm missing?
I made sure I included the xmlrpc libraries to the right path and everything.
The webpage error returns:
An XML-RPC Fault Occured
Fault Code:-1
Fault Desc:java.lang.NoSuchMethodException: BeerHandler.List()
XML-RPC Client:
<?php
require_once('xmlrpc-3.0.0.beta/lib/xmlrpc.inc');
// Initialize $Beers as an empty Array.
// $Beers will hold all the information available for each beer.
// (BeerID, Name, Rating, Comments)
//
// It will be used later to create the HTML output.
$Beers = Array();
// GET A LIST OF THE AVAILABLE BEERS ON THE XML-RPC SERVER
$beerClient = new xmlrpc_client('localhost:1234/341/xmlrpc-lab/xmlrpcserver.php','alvin.ist.rit.edu:8100',1234);
$msg_listBeers = new xmlrpcmsg('beer.List');
$response = $beerClient->send($msg_listBeers);
if($response == false)
{
die('Unable to contact XML-RPC Server');
}
if(!$response->faultCode()) // faults occurred?
{
// convert to a more usable PHP Array
$beerList = xmlrpc_decode($response->value());
foreach($beerList as $beerID => $beerName)
{
// for each available beer listed by the server grab it's
// a) Rating
// b) Comments
//
// and put the data into the $Beer array. This is incredibly
// inefficient since it performs a lot of HTTP calls to grab each
// piece of data. Not recommended for use beyond this example.
$Beers[$beerID]['name'] = $beerName;
// GET THE RATING FOR THE CURRENT BEER
// Build XML-RPC Request for the Beer's Rating
$msg_beerRating = new xmlrpcmsg('beer.Rating',array(new xmlrpcval($beerID, 'int')));
// Send the Message to the server
$response = $beerClient->send($msg_beerRating);
// Negative number If no rating found
$Beers[$beerID]['rating'] = (!$response->faultCode()) ? xmlrpc_decode($response->value()) : -1;
// GET THE COMMENTS FOR THE CURRENT BEER
$msg_beerComments = new xmlrpcmsg('beer.Comments', array(new xmlrpcval($beerID,'int')));
// Send the Message to the server
$response = $beerClient->send($msg_beerComments);
// Fill in the Comments for the Beer
$Beers[$beerID]['comments'] = (!$response->faultCode()) ? xmlrpc_decode($response->value()) : array(); //empty array for not Comments
} // END foreach ($beerList as ...
}
else // XML-RPC returned a fault...
{
echo '<h1>An XML-RPC Fault Occured</h1>';
printf('<b>Fault Code:</b>%s<br/>',$response->faultCode());
printf('<b>Fault Desc:</b>%s<br/>',$response->faultString());
die();
}
// GENERATE THE OUTPUT
$xmlrpc_client->setDebug(1); // turn on debugging, if I/O fault occurred between communication xmlrpc_client and xmlrpc_server
?>
<html>
<head>
<title>Beer List XML-RPC</title>
<meta charset="utf-8">
</head>
<body>
<h1>Beer List</h1>
<ol type="1">
<?php
if(count($Beers))
{
foreach($Beers as $BeerData)
{
printf('<font size="+2" color="#990000"><li> %s</font><br>', $BeerData['beer']);
// Output the beer's rating if it exists
if($BeerData['rating'] != -1)
{
printf('<b>Rating: %s/5.0</b><br>',$BeerData['rating']);
}
// Output the beer's comments if they exist
if(count($BeerData['comments']))
{
echo '<b>Comments:</b><ul>';
foreach($BeerData['comments'] as $Comment)
{
echo "<li> $Comment";
}
echo '</ul>';
}
}
}
else
{
echo '<li> Darn No Beers Found';
}
?>
</ol>
</body>
</html>

Connection error when accessing a web service on Shared Hosting using PHP Soap

I'm trying to access a web service using PHP and SOAP (NuSoap library to be exact) but keep hitting the following error:
HTTP Error: Couldn't open socket connection to server http://rsvpdb01/CRMWebService prior to connect(). This is often a problem looking up the host name.
When accessing this service locally it was necessary to amend my hosts file to redirect the IP address to the 'rsvpdb01' location, however I'm not sure how to do the same on the web server (or if that will actually solve the problem).
The basics of my script are:
<?php
// Pull in the NuSOAP code
require_once('nusoap/lib/nusoap.php');
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
// Create the client instance
$action_authenticate = array('Action'=> 'http://tempuri.org/ICRMWebServiceAPI/AuthenticateUser');
$client = new SoapClient('http://81.144.199.11/CRMWebService?wsdl',$action_authenticate);
$client->soap_defencoding = 'UTF-8';
// Call the SOAP method
$result = $client->call('AuthenticateUser', array('Username' => 'username', 'Password' => 'password'));
// Display the request and response
echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
// Check for a fault
if ($client->fault) {
echo '<p><b>Fault: ';
print_r($result);
echo '</b></p>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<p><b>Error: ' . $err . '</b></p>';
} else {
// Display the result
print_r($result);
}
}
?>
Could anybody shed any light on this?
The problem here was that the web service was pointing at a local machine and my server couldn't translate that physical address from the IP address I needed to use to connect.
I had to ask for root access on my hosting server so I could edit the 'hosts' file with the IP address against the local machine, it was a simple line to add like this:
123.456.5.1 xxxdb01

How to create folder on dropbox using php

I want to create the folder dynamically on dropbox and i am using the below code but it gives me error please help me
function CreateFolder($path) {
return $this->apiCall("fileops/create_folder", "POST", array('root'=> $this->rootPath, 'path' => $path));
}
$x = 'test';
CreateFolder($x);
But it gives me the error
Parse error: syntax error, unexpected '$x' (T_VARIABLE), expecting
function (T_FUNCTION) in
/home/stsgbnet/public_html/stockpile/DropPHP-master/DropboxClient.php
on line 451
My complete code is here
http://pastebin.com/HnPvV4b0
Since CreateFolder function seems to be in a class ($this->apiCall points to that), $x should be encapsulated in a function (that is the error that's shown). So to make it work, just call it from outside class.
You are using DropboxClient.php so following sample.php from this package your create a php file and put the following code on it:
<?php
// these 2 lines are just to enable error reporting and disable output buffering (don't include this in you application!)
error_reporting(E_ALL);
enable_implicit_flush();
// -- end of unneeded stuff
// if there are many files in your Dropbox it can take some time, so disable the max. execution time
set_time_limit(0);
require_once("DropboxClient.php");
// you have to create an app at https://www.dropbox.com/developers/apps and enter details below:
$dropbox = new DropboxClient(array(
'app_key' => "",
'app_secret' => "",
'app_full_access' => false,
),'en');
// first try to load existing access token
$access_token = load_token("access");
if(!empty($access_token)) {
$dropbox->SetAccessToken($access_token);
echo "loaded access token:";
print_r($access_token);
}
elseif(!empty($_GET['auth_callback'])) // are we coming from dropbox's auth page?
{
// then load our previosly created request token
$request_token = load_token($_GET['oauth_token']);
if(empty($request_token)) die('Request token not found!');
// get & store access token, the request token is not needed anymore
$access_token = $dropbox->GetAccessToken($request_token);
store_token($access_token, "access");
delete_token($_GET['oauth_token']);
}
// checks if access token is required
if(!$dropbox->IsAuthorized())
{
// redirect user to dropbox auth page
$return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?auth_callback=1";
$auth_url = $dropbox->BuildAuthorizeUrl($return_url);
$request_token = $dropbox->GetRequestToken();
store_token($request_token, $request_token['t']);
die("Authentication required. <a href='$auth_url'>Click here.</a>");
}
echo "<pre>";
echo "<b>Account:</b>\r\n";
print_r($dropbox->GetAccountInfo());
// Here will create the folder.
$dropbox->CreateFolder('test');
function store_token($token, $name)
{
if(!file_put_contents("tokens/$name.token", serialize($token)))
die('<br />Could not store token! <b>Make sure that the directory `tokens` exists and is writable!</b>');
}
function load_token($name)
{
if(!file_exists("tokens/$name.token")) return null;
return #unserialize(#file_get_contents("tokens/$name.token"));
}
function delete_token($name)
{
#unlink("tokens/$name.token");
}
function enable_implicit_flush()
{
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 0);
#ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
echo "<!-- ".str_repeat(' ', 2000)." -->";
}
?>
Hope it helps.

INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session

Similar issues -
INVALID_SESSION_ID using partner/enterprise wsdl for two different SF users - Tried solution but didn't work.
I was trying to use Salesforce PHP toolkit with ZF 2. I have added namespace to php files in salesforce soap client and used it in zend controller.
Added follwing line to all php files in Salesforce SOAP client library.
namespace Salesforce\Soapclient;
Then included it in ZF controller.
use Salesforce\Soapclient;
Here is the connetion code -
$empid = 'e1234567';
$sf_WSDL = 'C:\wamp\www\myapp\app\vendor\salesforce\wsdl\enterprise.wsdl.xml';
$sf_username = $config['salesforce']['username'];
$sf_password = $config['salesforce']['password'];
$sf_token = $config['salesforce']['token'];
/***********/
try {
// Create SOAP client instance
$sfSoapClient = new Soapclient\SforceEnterpriseClient();
// Create connection
$sfSoapClient->createConnection($sf_WSDL);
var_dump($_SESSION['enterpriseSessionId']);
if (isset($_SESSION['enterpriseSessionId'])) {
$location = $_SESSION['enterpriseLocation'];
$sessionId = $_SESSION['enterpriseSessionId'];
$sfSoapClient->setEndpoint($location);
$sfSoapClient->setSessionHeader($sessionId);
} else {
// Login to SF
$sfSoapClient->login($sf_username,$sf_password . $sf_token);
$_SESSION['enterpriseLocation'] = $sfSoapClient->getLocation();
$_SESSION['enterpriseSessionId'] = $sfSoapClient->getSessionId();
}
var_dump($_SESSION['enterpriseSessionId']);
// Get candidate profile by employee id
$candidate_profile = $this->getCandidateTable()->getCandidateByEmpId($empid);
$ids = array();
array_push($ids, $empid);
// If no profile for logged internal employee
if (!$candidate_profile){
$query = "SELECT Id, First_Name__c from Employee__c";
$response = $sfSoapClient->query($query);
echo "Results of query '$query'<br/><br/>\n";
foreach ($response->records as $record) {
echo $record->Id . ": " . $record->First_Name__c . "<br/>\n";
}
}
} catch (Exception $exc) {
//TODO Handle error login exception
die('Connection could not established.');
}
But I'm getting following error -
INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal
Session
Note that "Lock sessions to the IP address from which they originated" setting is turned off.

Problem using publishUserAction method to post to profile

I am using gigya php sdk, It works well I am able to post to user's wall or profile using socialise.setStatus method but I am have problems when I try to use the publishuseraction method. I get an error Invalid request signature.
$method = "socialize.publishUserAction";
$request = new GSRequest($apiKey,$secretKey,$method);
$userAction = new GSDictionary("{\"title\":\"This is my title\", \"userMessage\":\"This is a user message\", \"description\":\"This is a description\", \"linkBack\":\"http://google.com\", \"mediaItems\":[{\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}]}");
$request->setParam("userAction", $userAction);
$request->setParam("uid", $userUID);
$response = $request->send();
if($response->getErrorCode()==0){
echo "Success";
} else {
echo ("Error: " . $response->getErrorMessage());
}
UPDATED AFTER USING $response->getLog()
apiMethod=socialize.publishUserAction
apiKey=correct_api_key
params={"userAction":{},uid":"MY_UID","format":"json","httpStatusCodes":"false"}
URL=http://socialize.gigya.com/socialize.publishUserAction postData=uid=urlencoded(MY_UID)&format=json&httpStatusCodes=false&apiKey=correct_api_keyƗtamp=1296229876&nonce=1.29622987636E%2B12&sig=HEdzy%2BzxetV8QvTDjdsdMWh0%2Fz8%3D
server= web504
I used both put method
$userAction = new GSDictionary();
$userAction->put("title", "This is my title");
$userAction->put("userMessage", "This is my user message");
$userAction->put("description", "This is my description");
$userAction->put("linkBack", "http://google.com");
$mediaItems = array();
$mediaItems[0] = new GSDictionary("{\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}");
& JSON method
$userAction = new GSDictionary("{\"title\":\"This is my title\", \"userMessage\":\"This is a user message\", \"description\":\"This is a description\",
\"linkBack\":\"http://google.com\", \"mediaItems\":[ {\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}]}");
I get the same error. And User action is empty using both methods. I appreciate any help.
Thanks.
Try calling getLog() for a bit more information about the error:
if($response->getErrorCode()==0){
echo "Success";
} else {
echo ("Error: " . $response->getErrorMessage());
print "<pre>";
print_r($response->getLog());
print "</pre>";
}
Also, are you able to run getUserInfo w/ the SDK? This is a simple test that also requires a signature. Use the example on the PHP SDK page (about 1/2 way down).

Categories