How to solve xml load parsing soap payload using nusoap? - php

I am new in using web service nusoap. When I try to run my program I got an error like this:
XML error parsing SOAP payload on line 1: Not well-formed (invalid
token)
Here is my client.php :
<?php
require_once('lib/nusoap.php');
$data = json_decode(file_get_contents("php://input"), true);
$doc_type = $data['doc_type'];
$transaction_date = $data['transaction_date'];
$file_name = $data['file_name'];
$file_path = $data['file_path'];
//create client instance
$client = new nusoap_client('http://computer_name:2224/WebService/webservice.php?wsdl' , true);
//to check if the request method is POST or not
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//check for error
$err = $client->getError();
if($err){
//Display error
echo '<h2>Constructor error </h2> <pre>' . $err . '</pre>' ;
}
//declare variables
$datas = array(
'doc_type' => $doc_type,
'transaction_date' => $transaction_date,
'file_name' => $file_name,
'file_path' => $file_path
);
//call the function InsertData and pass the parameters being instantiated
$result = $client->call('InsertData', $datas);
if($client->fault){
echo '<h2> Fault (Expect - The request contains an invalid SOAP body) </h2> <pre>';
print_r($result);
echo '</pre>' ;
}else {
$err = $client->getError();
if($err){
echo '<h2> Error </h2><pre>' . $err . '</pre>' ;
}else {
echo '<h2> Result </h2><pre>' ;
print_r($result);
echo '</pre>';
}
}
} else if ($_SERVER['REQUEST_METHOD'] != 'POST'){
echo "Method is not POST";
}
?>
webservice.php
<?php
// require the nusoap.php
require_once ('lib/nusoap.php');
//create new instance
$server = new soap_server();
//initialize WSDL support
$server->configureWSDL('Database Data Insertion', 'urn:Insert');
//character encoding
$server->soap_defencoding = 'utf-8';
// Registering different functions of your Web service
$server->register ('InsertData',
array(
'doc_type' => 'xsd:doc_type',
'transaction_date' =>'xsd:transaction_date',
'file_name' =>'xsd:file_name',
'file_path' =>'xsd:file_path'), //input values
array('return' =>'xsd:string'),
'urn:Insert', // Namespace
'urn:Insertwsdl#InsertData', //SoapAction
'rpc', //style
'literal' // can be encoded but it doesn't work with silverlight
);
// function for inserting data
function InsertData($doc_type,$transaction_date,$file_name,$file_path) {
//set initial values for connection
$db_host = 'localhost' ;
$db_username = 'root' ;
$db_password = '' ;
$db_name = 'sample' ;
//making connection
$conn = new mysqli($db_host, $db_username ,$db_password , $db_name);
//checking if connection is successful
if($conn->connect_error){
trigger_error('Database connection failed : ' .$conn->connect_error , E_USER_ERROR);
}
//inserting data in the edi_doc_type table
$sql = "INSERT INTO transaction_tbl (`transaction_date`,`edi_doc_type_id`,`file_name`,`file_path`,`creation_date`)
VALUES ('$transaction_date',( SELECT edi_doc_type_id FROM `edi_doc_type` WHERE doc_type = $doc_type ),'$file_name','$file_path',NOW()) " ;
//Checking query if it is successful
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
}
$HTTP_RAW_POST_DATA = isset ($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA: '' ;
$server->service($HTTP_RAW_POST_DATA);
?>
Now , when I try to run this I got the above error. so what could be the possible problem? By the way, I can still insert in my database , but the problem is it returns the above error and not all the data in the script can be inserted . When I check my php error logs I have this :
PHP Fatal error: Wrong SQL: INSERT INTO transaction_tbl
(transaction_date,edi_doc_type_id,file_name,file_path,creation_date)
VALUES ('2015-05-28 22:33:00',( SELECT edi_doc_type_id FROM edi_doc_type
WHERE doc_type = 997),'87749-20150528223345027_54423526_54423945.xfa','/home/sample/test/87749-20150528223345027_54423526_54423945.xfa',NOW())
Error: Subquery returns more than 1 row
C:\xampp\htdocs\WebService\webservice.php on line 65
Any help will be appreciated. Thanks :)

Related

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)

Soap, call a recovery service

I am new to SOAP. For a project, I need to use "Force.com Toolkit for PHP".
I made the first call to open a Salesforce session and retrieve the session ID , which will be used to call the recovery service of customer information. ( It's ok, i have the ID session)
I know that the customer information flows is called using the session ID obtained with the first call, but i don't how to do the second call ! I also have another WSDL file ( CallInListCustomer.wsdl.xml )
I also the customers informations flow addresses (found in WSDL ). I'm not sure , but i must the call in "post" format...
can you help me ?
<?php
session_start();
define("USERNAME", "my_username");
define("PASSWORD", "my_password");
define("SECURITY_TOKEN", "my_token");
require_once ('soapclient/SforcePartnerClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("Partner.wsdl.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// Now we can save the connection info for the next page
$_SESSION['location'] = $mySforceConnection->getLocation();
$_SESSION['sessionId'] = $mySforceConnection->getSessionId();
$sessionId = $_SESSION['sessionId'];
echo $sessionId;
// Here, i don't know how to call the recovery service of customer information with allInListCustomer.wsdl.xml
?>
Thanks for all
Here is my code.
Create separate file to store salesforce org details.
SFConfig.php
<?php
/*----------------------------------------------------------------
* We will define salesforce user anem and password with token.
* This file we used / include in every time when we need to
* communicate withy salesforce.
* ---------------------------------------------------------------*/
$USERNAME = "Your salesforce user name";
$PASSWORD = "Your password with security token";
?>
Get account data from salesforce
GetAccountData.php
<?php
// SET SOAP LIB DIRCTORY PATH
define("SOAP_LIB_FILES_PATH", "/<Put Your file location>/soapclient");
// Access sf config file
require_once ('/<Put Your file location>/SFConfig.php');
// Access partner client php lib file
require_once (SOAP_LIB_FILES_PATH.'/SforcePartnerClient.php');
try {
echo "\n******** Inside the try *******\n";
// Sf connection using ( SOAP ) partner WSDL
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection(SOAP_LIB_FILES_PATH.'/YourWSDLName.wsdl.xml');
$mySforceConnection->login($USERNAME, $PASSWORD);
echo "\n******** Login with salesforce is done *******\n";
// query for featch Versand data with last run datetime
$query = "SELECT Id, Name
FROM Account;
// Send query to salesforce
$response = $mySforceConnection->query($query);
// Store the query result
$queryResult = new QueryResult($response);
$isError = false ;
echo "Results of query '$query'<br/><br/>\n";
// Show result array
for ($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$record = $queryResult->current();
// Id is on the $record, but other fields are accessed via
// the fields object
echo "\nVersand value : ".$record->Abmelder__c."\n";
}
} catch (Exception $e) {
$GLOBALS['isTimeEnter'] = true;
echo "entered catch****\n";
echo "Exception ".$e->faultstring."<br/><br/>\n";
}
?>
Also if you want to call another services then just call using "$mySforceConnection" variable as per above.
For Example: (Create Contact)
$records = array();
$records[0] = new SObject();
$records[0]->fields = array(
'FirstName' => 'John',
'LastName' => 'Smith',
'Phone' => '(510) 555-5555',
'BirthDate' => '1957-01-25'
);
$records[0]->type = 'Contact';
$records[1] = new SObject();
$records[1]->fields = array(
'FirstName' => 'Mary',
'LastName' => 'Jones',
'Phone' => '(510) 486-9969',
'BirthDate' => '1977-01-25'
);
$records[1]->type = 'Contact';
$response = $mySforceConnection->create($records);
$ids = array();
foreach ($response as $i => $result) {
echo $records[$i]->fields["FirstName"] . " "
. $records[$i]->fields["LastName"] . " "
. $records[$i]->fields["Phone"] . " created with id "
. $result->id . "<br/>\n";
array_push($ids, $result->id);
}
Please check below link for more details:
https://developer.salesforce.com/page/Getting_Started_with_the_Force.com_Toolkit_for_PHP
I find the solution, here my code :
<?php
// salesforce.com Username, Password and TOken
define("USERNAME", "My_username");
define("PASSWORD", "My_password");
define("SECURITY_TOKEN", "My_token");
// from PHP-toolkit ( https://developer.salesforce.com/page/Getting_Started_with_the_Force.com_Toolkit_for_PHP )
require_once ('soapclient/SforcePartnerClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("Partner.wsdl.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// I Get the IDSESSION
$sessionId = $mySforceConnection->getSessionId();
// I create a new soapClient with my WSDL
$objClient = new SoapClient("my_service.wsdl.xml", array('trace' => true));
// I create the header
$strHeaderComponent_Session = "<SessionHeader><sessionId>$sessionId</sessionId></SessionHeader>";
$objVar_Session_Inside = new SoapVar($strHeaderComponent_Session, XSD_ANYXML, null, null, null);
$objHeader_Session_Outside = new SoapHeader('https://xxxxx.salesforce.com/services/Soap/class/myservice', 'SessionHeader', $objVar_Session_Inside);
$objClient->__setSoapHeaders(array($objHeader_Session_Outside));
// i call the service
$objResponse = $objClient->getinfo(array ( 'Zone' => "123456"));
// here i get the result in Json
$json = json_encode( (array)$objResponse);
echo $json;
?>

CRM dynamic "an error occurred when verifying security for the message"

I am tring to access http://xxxxxxxxxxx/CRM2011/XRMServices/2011/Organization.svc?wsdl
I can able to see functions list. means i can access to webservice. But while i tring to write data using function create it through "an error occurred when verifying security for the message" my code is below
<?php
date_default_timezone_set("Asia/Kolkata");
ini_set("soap.wsdl_cache_enabled", "0");
$location = "http://182.18.175.29/CRM2011/XRMServices/2011/Organization.svc?wsdl";
$config['Username'] = 'xxxxxxx';
$config['Password'] = 'xxxxxx';
$config['soap_version'] = SOAP_1_2;
$config['trace'] = 1; // enable trace to view what is happening
$config['use'] = SOAP_LITERAL;
$config['style'] = SOAP_DOCUMENT;
$config['exceptions'] = 0; // disable exceptions
$config["cache_wsdl"] = WSDL_CACHE_NONE; // disable any caching on the wsdl, encase you alter the wsdl server
$config["features"] = SOAP_SINGLE_ELEMENT_ARRAYS;
include_once 'ntlmSoap.php';
$client = new NTLMSoapClient($location, $config);
print('<pre>');
print_r($client->__getFunctions());
$HeaderSecurity = array("UsernameToken" => array("Username" => 'xxxxxx', "Password" => 'xxxxxx'));
$header[] = new SoapHeader($location, "Security", $HeaderSecurity);
$client->__setSoapHeaders($header);
$params = array(
"bmw_firstname" => "test",
"bmw_lastname" => "test"
);
try {
$response = $client->__soapCall("Create", $params);
var_dump($response);
} catch (Exception $e) {
print_r($e);
}
// display what was sent to the server (the request)
echo "<p>Request :" . htmlspecialchars($client->__getLastRequest()) . "</p>";
// display the response from the server
echo "<p>Response:" . htmlspecialchars($client->__getLastResponse()) . "</p>";

wsdl error: HTTP ERROR: socket read of chunk terminator timed out

I try to build a connection between data from a CMS and a CRM systems based on web services and using NuSOAP library. But when trying to form a request to a CRM server my web server (http://poseidonexpeditions.ru/soap/) returns this kind of error
wsdl error: Getting http://79.172.60.168/poseidon/soap.php?wsdl - HTTP ERROR: socket read of chunk terminator timed out"
Still, if the request is sent from another server - everything works fine. If the request is sent to another wsdl server - everything is fine:
http://poseidonexpeditions.ru/soap/client.php
The file looks like this:
<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
require($_SERVER["DOCUMENT_ROOT"]."/soap/lib/nusoap.php");
//$APPLICATION->IncludeComponent("pex:web.client");
require_once('./lib/nusoap.php');
$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
$client = new nusoap_client('http://79.172.60.168/poseidon/soap.php?wsdl', 'wsdl',
$proxyhost, $proxyport, $proxyusername, $proxypassword);
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
//$myWsdl = 'http://79.172.60.168/poseidon/soap.php?wsdl';
$myAuth = array(
'user_name' => 'foobar',
'password' => MD5('foobar'),
);
//$soapClient = new nusoap_client($myWsdl,true);
//var_dump($soapClient);
//
// Login
$loginParams = array('user_auth' => $myAuth);
$loginResult = $client->call('login', $loginParams);
$sessionId = $loginResult['id'];
$err = $client->getError();
echo $err;
echo '<h2>Отладка</h2>';
echo '<pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
echo $sessionId;
$set_entry = $client->call('set_entry', Array(
'session'=>$sessionId,
'module_name'=>'PsdnProducts',
'name_value_list'=>array(
array("name" => 'ID',"value" => 1),
array("name" => 'name',"value" => 'Test')
)));
echo '<pre>';
var_dump($set_entry);
echo '</pre>';
?>
I am just guessing,
The wsdl you are using to send data to CRM would have lots of sObjects and they will be referring one to another in a recursive manner. Sometimes it couldn't load wsdl properly due to it. So you should use one kind of sObject which is being used to send data, remove other sObjects. May be it will help.
Thanks,ambuj

SOAP returning "Internal Server Error"

My SOAP application written in NuSOAP returns an http 500 (Internal Server Error) error.
It is working fine on my local machine, I only get this error in live.
How do I diagnose this error?
Server:
require_once('nusoap.php');
// Create the server instance.
$server = new soap_server;
// Register the method to expose.
// Note: with NuSOAP 0.6.3, only method name is used without WSDL.
$server->register(
'hello', // Method name
array('name' => 'xsd:string'), // Input parameters
array('return' => 'xsd:string'), // Output parameters
'uri:helloworld', // Namespace
'uri:helloworld/hello', // SOAPAction
'rpc', // Style
'encoded' // Use
);
// Define the method as a PHP function.
function hello($name) {
require_once 'classes.php';
$db = new Database();
$sql = "select * from notifications where skey = '$name'";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
//return 'Hello, ' . $row['sales'];
$ret = "<salesdat>
<customername>". $row['sales']. "</customername>
</salesdat>";
return $ret;
}
// 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:
// Pull in the NuSOAP code.
require_once('nusoap.php');
// Create the client instance.
$client = new soapclient('http://----my site url ---/server.php');
//$client = new soapclient('http://localhost/cb/server.php');
// Check for an error.
$err = $client->getError();
if ($err) {
// Display the error.
echo '<p><b>Constructor error: ' . $err . '</b></p>';
// At this point, you know the call that follows will fail.
}
// Call the SOAP method.
$result = $client->call(
'hello', // method name
array('name' => 'shahidkari'), // input parameters
'uri:helloworld', // namespace
'uri:helloworld/hello' // SOAPAction
);
// Strange: the following works just as well!
//$result = $client->call('hello', array('name' => 'Scott'));
// 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);
}
}
This may due to the php error in your server script. Switch on the error reporting. Run the server in a browser.
server.php
error_reporting(-1);
ini_set('display_errors', 'On');
require_once './src/Test.php';
$server = new SoapServer("https://xxxx/Outbound.wsdl");
$server->setClass('Test');
$server->handle();
https://xxxx/server.php // calling this in a browser will throw the error.
In my case it was due to require_once './src/Test.php'; which was not including the class.

Categories