Object reference not set to an instance of an object - php

It tells me that Object reference not set to an instance of an object, when trying to call this SOAP API.
I am doing this way
$client = new SoapClient("http://gateway.XXXXXXX/gateway/api/creditcards/creditcardAPI.asmx?wsdl");
$params = array("clsCreditCardAPIBE" => (Object) array(
"Username" => 'blabla',
"Password" => "Barrel of Oil",
"ProviderPIN" => 500,
"AccountID" => 1234
.......
));
$response = $client->__soapCall("Initiate_Deposit", $params);
What am i doing wrong?

You have to generate the client first, and then start using it
$client = new SoapClient("http://yourdomain.com?wsdl");

Related

Displaying SOAP API results in PHP

I've had some difficulty finding resources on this, to connect to a SOAP API using PHP and easily attach the array results to variables for display purposes.
Here is the SOAP API XML of GetCostCenters function within the API:
<Response><Status><Result>1</Result><Description>OK</Description></Status><CostCenters><CostCenter><ID>4</ID><Branch>Adelaide</Branch></CostCenter><CostCenter><ID>6</ID><Branch>Derby</Branch></CostCenter><CostCenter><ID>33</ID><Branch>GT Perth</Branch></CostCenter><CostCenter><ID>7</ID><Branch>Hobart Branch</Branch></CostCenter><CostCenter><ID>46</ID><Branch>Lawns & Maintenance</Branch></CostCenter><CostCenter><ID>10</ID><Branch>London</Branch></CostCenter><CostCenter><ID>3</ID><Branch>Melbourne</Branch></CostCenter><CostCenter><ID>45</ID><Branch>NECA Apprentices</Branch></CostCenter><CostCenter><ID>17</ID><Branch>New York</Branch></CostCenter><CostCenter><ID>48</ID><Branch>Nursing NSW</Branch></CostCenter><CostCenter><ID>1</ID><Branch>Perth</Branch></CostCenter><CostCenter><ID>44</ID><Branch>Registration</Branch></CostCenter><CostCenter><ID>16</ID><Branch>Rio</Branch></CostCenter><CostCenter><ID>50</ID><Branch>Subiaco</Branch></CostCenter><CostCenter><ID>51</ID><Branch>Subiaco</Branch></CostCenter><CostCenter><ID>2</ID><Branch>Sydney</Branch></CostCenter><CostCenter><ID>42</ID><Branch>test - tester</Branch></CostCenter><CostCenter><ID>49</ID><Branch>TesterOM</Branch></CostCenter><CostCenter><ID>8</ID><Branch>Tom Price</Branch></CostCenter><CostCenter><ID>47</ID><Branch>Traffic Control NSW</Branch></CostCenter></CostCenters></Response>
Here is my PHP:
$client = new SoapClient("https://api.myfeed.com/feed.asmx?WSDL", array(
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
// GET RESULTS
$result = $client->GetCostCenters(array(
'CompanyID' => 'MYID',
'APIKey' => 'MYKEY',
'APIPassword' => 'MYPASS',
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
echo '<pre>';
print_r($result);
echo '</pre>';
Outputs it all on one line in [any] like this:
stdClass Object
(
[GetCostCentersResult] => stdClass Object
(
[any] => 1OK4Adelaide6Derby33GT Perth7Hobart Branch46Lawns & Maintenance10London3Melbourne45NECA Apprentices17New York48Nursing NSW1Perth44Registration16Rio50Subiaco51Subiaco2Sydney42test - tester49TesterOM8Tom Price47Traffic Control NSW
)
)
and I can't figure out why, ideally I want it as an array so I can assign variables and run a loop to display the information.
Any ideas? Thanks in advance.
Convert the result from string to xml object (simplexml_load_string):
$resultAsXml = simplexml_load_string($result);
Then convert the object to array using the json encoding (json_encode, json_decode):
$resultAsArray = json_decode(json_encode($resultAsXml), true);
Note the second argument passed to json_decode:
When true, JSON objects will be returned as associative arrays;
In your case:
$client = new SoapClient("https://api.myfeed.com/feed.asmx?WSDL", array(
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
// GET RESULTS
$result = $client->GetCostCenters(array(
'CompanyID' => 'MYID',
'APIKey' => 'MYKEY',
'APIPassword' => 'MYPASS',
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
$resultAsXml = simplexml_load_string($result);
$resultAsArray = json_decode(json_encode($resultAsXml), true);
echo '<pre>';
print_r($resultAsArray);
echo '</pre>';

Guzzle not behaving like CURL

I want to migrate from pure CURL to Guzzle, but the API calls are not being registered correctly.
Working CURL (Class from here: https://stackoverflow.com/a/7716768/8461611)
...
$Curl = new CURL(); // setting all curl_opts there
// creating session
$session = explode(";", $Curl->post("http://www.share-online.biz/upv3_session.php", "username=".$un."&password=".$pw));
$session_key = $session[0];
$upload_server = $session[1];
// upload
$vars = ... // see below
var_dump(explode(";",$Curl->post($upload_server, $vars))); // works
Now the Guzzle stuff
...
$Curl = new GuzzleHttp\Client();
$jar = new GuzzleHttp\Cookie\FileCookieJar("cookie.txt", true);
//creating session
$session = explode(";", $Curl->request('POST', "http://www.share-online.biz/upv3_session.php",
["form_params" => ["username" => $un, "password" => $pw], 'cookies' => $jar])->getBody());
$session_key = $session[0];
$upload_server = $session[1];
$vars = ["username" => $un,
"password" => $pw,
"upload_session" => $session_key,
"chunk_no" => 1,
"chunk_number" => 1,
"filesize" => filesize($file),
"fn" => new CurlFile(realpath($file)),
"finalize" => 1,
"name" => "test",
"contents" => $file,
];
var_dump(
explode(";",$Curl->request(
'POST', "http://".$upload_server, ["multipart" => [$vars], 'cookies' => $jar])
->getBody()));
// outputs *** EXCEPTION session creation/reuse failed - 09-3-2017, 3:05 am ***
I assume I'm doing something wrong with cookies. They are being set as var_dump($jar); shows. API Docs : http://www.share-online.biz/uploadapi
First of all, Guzzle is not curl and cannot behave like curl. The only caveat is that it uses curl behind the scenes.
Here is the solution:
use GuzzleHttp\Client;
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://www.share-online.biz/',
'timeout' => 2.0,
]);
$response = $client->request('POST', 'upv3_session.php',
[
'form_params' => [
"username" => $un,
"password" => $pw
]
]
);
Use the output of your request like so:
$code = $response->getStatusCode(); // 200 || 400 | 500 etc
$reason = $response->getReasonPhrase();
$body = $response->getBody();
$response = $request->getBody(); //Explicitly cast to string.
$json_response = json_decode($response); //here the string response has be decoded to json string.
I hope it helps others that facing this situation
First of all, you have to call ...->getBody()->getContents() to get a string. Or cast body object to a string: (string) ...->getBody().
Then, you cannot use CurlFile class. Use fopen() to get a file handle and pass it directly to Guzzle like in the docs. Pay attentions that for file uploads you have to use multipart instead of form_params.

SOAP-ERROR: Encoding: object has no 'FinalBookingDate' property

Before starting, I know, this errors means that I should have defined the property FinalBookingDate, but just keep reading and you will understand my point of view.
The url is: http://bestbuyhotel1.cangooroo.net/ws/2013/ClientBackOffice_b.asmx?op=getBookingList
I was testing first with SoapUi, and I successfull get the list that I need:
And on php, I only can get this response:
The SoapClient from php is:
$params = array('soap_version' => SOAP_1_2, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, 'encoding'=>'UTF-8', 'trace' => 1, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE, 'features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new \SoapClient('http://bestbuyhotel1.cangooroo.net/ws/2013/ClientBackOffice_b.asmx?wsdl', $params);
And then, the code to retrieve the data:
/*
$query = array(
'InitialServiceDate' => '2015-01-20',
'InitialBookingDate' => '2015-01-20',
'FinalBookingDate' => '2015-01-20',
'FinalServiceDate' => '2015-01-20',
'CreationUserId' => 1338,
'CityId' => 4166,
'ServiceTypes' => array('eServiceType' => 'HOTEL')
);
*/
$query = array(
'InitialBookingDate' => '2015-01-20',
'ServiceTypes' => array('eServiceType' => 'HOTEL')
);
$args = new \stdClass;
$args->credential = new \stdClass;
$args->credential->UserName = $conn['userPass']['usr'];
$args->credential->Password = $conn['userPass']['pass'];
$args->searchBookingCriteria = new \stdClass;
$args->searchBookingCriteria->InitialBookingDate = '2015-01-20';
$args->searchBookingCriteria->ServiceTypes = new \stdClass;
$args->searchBookingCriteria->ServiceTypes->eServiceType = 'HOTEL';
//$args = array('credential'=>$credentials, 'searchBookingCriteria' => $query);
$data = $conn['client']->getBookingList($args);
print_r($data);
exit;
As you can see, I tried 2 ways to send the $args to getBookingList, as far I know both of then is valid and yet both of then (with array or object) return the same error. On the code commented at first you can see that I tried to define all does properties that the web service asks but after defining all of then I get a empty result.
My question is, there is some extra param to define on SoapClient that I should do? Why the SoapUI can do it with success? What I have missing here?
Bonus: A print of SoapUI full screen with the default request including the optional params https://www.evernote.com/shard/s14/sh/fb5ac276-8147-4e09-95bb-afa0be66d7a6/d273441c74186bf1e600b42ab3303899/deep/0/SoapUI-5.0.0.png
Can you try this more direct approach:
try {
$params = array('soap_version' => SOAP_1_2, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, 'encoding'=>'UTF-8', 'trace' => 1, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE, 'features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient('http://bestbuyhotel1.cangooroo.net/ws/2013/ClientBackOffice_b.asmx?wsdl',$params);
} catch (SoapFault $E) {
echo $E->faultstring;
}
if ($client) {
$req_params = array('credential' =>
array('userName' => 'XXXXXXX',
'Password' => 'XXXXXXX'),
'searchBookingCriteria' =>
array('BookingNumber' => array('int' => 'XXXXXXXXX'),
'ServiceTypes' => array('eServiceType' => 'HOTEL'),
'PassengerName'=> 'XXXXXXXX',
'InitialBookingDate'=> '2015-01-16',
'FinalBookingDate'=> '2015-01-16',
'InitialServiceDate' => '2015-01-18',
'FinalServiceDate' => '2015-01-18',
'BookingStatus'=> array('eStatus' => 'ACTIVATED'),
'PaymentStatus'=> array('ePaymentStatus' => 'Payed'),
'CreationUserId'=> 'XXX',
'CityId'=> 'XXXX',
'ExternalReference'=> '')
);
$response = $client->__soapCall('getBookingList',array($req_params));
var_dump($response);
}
Try (and add) this approach:
$args->searchBookingCriteria->FinalBookingDate = '2015-01-22';
$args->searchBookingCriteria->InitialServiceDate = '2015-01-22';
$args->searchBookingCriteria->FinalServiceDate = '2015-01-22';
$args->searchBookingCriteria->CreationUserId = 'abc';
$args->searchBookingCriteria->CityId = 'abc';

Convert old NuSoap code into PHP core soap functions

I've been testing nuSoap with codeIgniter (PHP Framework) but seems nuSoap isn't prepared to work with latest php 5.3, even if I download a patched nusoap version for php 5.3
I have the following code:
require_once(APPPATH.'libraries/NuSOAP/lib/nusoap'.EXT); //includes nusoap
$n_params = array('CityName' => 'San Juan', 'CountryName' => 'Argentina');
$client = new nusoap_client('http://www.webservicex.net/globalweather.asmx?WSDL');
$client->setHTTPProxy("10.2.0.1",6588,"","");
$result = $client->call('GetWeather', $n_params);
Can you help me to convert these functions into PHP soap functions? Including proxy function?
require_once(APPPATH.'libraries/NuSOAP/lib/nusoap'.EXT); //includes nusoap
$n_params = array('CityName' => 'San Juan', 'CountryName' => 'Argentina');
$client = new nusoap_client('http://www.webservicex.net/globalweather.asmx?WSDL');
$client->setHTTPProxy("10.2.0.1",6588,"","");
$result = $client->call('GetWeather', $n_params);
becomes
$url = 'http://www.webservicex.net/globalweather.asmx?WSDL';
$params = array(
'proxy_host' => '10.2.0.1',
'proxy_port' => '6588'
);
$client = new SoapClient($url, $params);
$client->__soapCall('GetWeather', $n_params);
The following code was the correct way of calling the above webservice. I've just only modified the $ser_params array. Now it has a sub array
$url = 'http://www.webservicex.net/globalweather.asmx?WSDL';
$conn_params = array(
'proxy_host' => '10.2.0.1',
'proxy_port' => '6588'
);
$ser_params = array (
'GetWeather' => array (
"CityName" => "San Juan",
"CountryName" => "Argentina"
)
);
$client = new SoapClient($url, $conn_params);
$result = $client->__soapCall('GetWeather', $ser_params);
print_r ($result);

PHP Soap non-WSDL call: how do you pass parameters?

I'm trying to make a non-WSDL call in PHP (5.2.5) like this. I'm sure I'm missing something simple. This call has one parameter, a string, called "timezone":
$URL = 'http://www.nanonull.com/TimeService/TimeService.asmx';
$client = new SoapClient(null, array(
'location' => $URL,
'uri' => "http://www.Nanonull.com/TimeService/",
'trace' => 1,
));
// First attempt:
// FAILS: SoapFault: Object reference not set to an instance of an object
$return = $client->__soapCall("getTimeZoneTime",
array(new SoapParam('ZULU', 'timezone')),
array('soapaction' => 'http://www.Nanonull.com/TimeService/getTimeZoneTime')
);
// Second attempt:
// FAILS: Generated soap Request uses "param0" instead of "timezone"
$return = $client->__soapCall("getTimeZoneTime",
array('timezone'=>'ZULU' ),
array('soapaction' => 'http://www.Nanonull.com/TimeService/getTimeZoneTime')
);
Thanks for any suggestions
-Dave
Thanks. Here's the complete example which now works:
$URL = 'http://www.nanonull.com/TimeService/TimeService.asmx';
$client = new SoapClient(null, array(
'location' => $URL,
'uri' => "http://www.Nanonull.com/TimeService/",
'trace' => 1,
));
$return = $client->__soapCall("getTimeZoneTime",
array(new SoapParam('ZULU', 'ns1:timezone')),
array('soapaction' => 'http://www.Nanonull.com/TimeService/getTimeZoneTime')
);
#Dave C's solution didn't work for me. Looking around I came up with another solution:
$URL = 'http://www.nanonull.com/TimeService/TimeService.asmx';
$client = new SoapClient(null, array(
'location' => $URL,
'uri' => "http://www.Nanonull.com/TimeService/",
'trace' => 1,
));
$return = $client->__soapCall("getTimeZoneTime",
array(new SoapParam(new SoapVar('ZULU', XSD_DATETIME), 'timezone')),
array('soapaction' => 'http://www.Nanonull.com/TimeService/getTimeZoneTime')
);
Hope this can help somebody.
The problem lies somewhere in the lack of namespace information in the parameter. I used the first case of your example since it was closest to what I came up with.
If you change the line:
array(new SoapParam('ZULU', 'timezone')),
to:
array(new SoapParam('ZULU', 'ns1:timezone')),
it should give you the result you expected.
You could try to add another array() call around your params like this:
$params = array('timezone'=>'ZULU' );
$return = $client->__soapCall("getTimeZoneTime",
array($params),
array('soapaction' => 'http://www.Nanonull.com/TimeService/getTimeZoneTime')
);
I can't test this, but you could.

Categories