Call asp.net web service from php - php

Hi im calling an aps.net web service from a php service. The service searches both databases with a search parameter. Im not sure how to pass a search parameter to the asp.net service. Code is below. ( there is no search paramter currently but im just interested in how it would be passed to the asp.net service)
$link = mysql_connect($host, $user, $passwd);
mysql_select_db($dbName);
$query = 'SELECT firstname, surname, phone, location FROM staff ORDER BY surname';
$result = mysql_query($query,$link);
// if there is a result
if ( mysql_num_rows($result) > 0 ) {
// set up a DOM object
$xmlDom1 = new DOMDocument();
$xmlDom1->appendChild($xmlDom1->createElement('directory'));
$xmlRoot = $xmlDom1->documentElement;
// loop over the rows in the result
while ( $row = mysql_fetch_row($result) ) {
$xmlPerson = $xmlDom1->createElement('staff');
$xmlFname = $xmlDom1->createElement('fname');
$xmlText = $xmlDom1->createTextNode($row[0]);
$xmlFname->appendChild($xmlText);
$xmlPerson->appendChild($xmlFname);
$xmlSname = $xmlDom1->createElement('sname');
$xmlText = $xmlDom1->createTextNode($row[1]);
$xmlSname->appendChild($xmlText);
$xmlPerson->appendChild($xmlSname);
$xmlTel = $xmlDom1->createElement('phone');
$xmlText = $xmlDom1->createTextNode($row[2]);
$xmlTel->appendChild($xmlText);
$xmlPerson->appendChild($xmlTel);
$xmlLoc = $xmlDom1->createElement('loc');
$xmlText = $xmlDom1->createTextNode($row[3]);
$xmlLoc->appendChild($xmlText);
$xmlPerson->appendChild($xmlLoc);
$xmlRoot->appendChild($xmlPerson);
}
}
//
// instance a SOAP client to the dotnet web service and read it into a DOM object
// (this really should have an exception handler)
//
$client = new SoapClient('http://stuiis.cms.gre.ac.uk/mk05/dotnet/dataBind01/phoneBook.asmx?WSDL');
$xmlString = $client->getDirectoryDom()->getDirectoryDomResult->any;
$xmlDom2 = new DOMDocument();
$xmlDom2->loadXML($xmlString);
// merge the second DOM object into the first
foreach ( $xmlDom2->documentElement->childNodes as $staffNode ) {
$xmlPerson = $xmlDom1->createElement($staffNode->nodeName);
foreach ( $staffNode->childNodes as $xmlNode ) {
$xmlElement = $xmlDom1->createElement($xmlNode->nodeName);
$xmlText = $xmlDom1->createTextNode($xmlNode->nodeValue);
$xmlElement->appendChild($xmlText);
$xmlPerson->appendChild($xmlElement);
}
$xmlRoot->appendChild($xmlPerson);
}
// return result
echo $xmlDom

you might want to look at the Apache Stonehenge project, http://www.interoperabilitybridges.com/projects/apache-stonehenge it talks about mixing and matching PHP clients and webservices including those from ASP.NET
jas

Related

Passing Array via SOAP for SAP Webservice

I am trying to pass a 2D Array via SOAP for SAP Webservice.
But I am unable to pass the same.
I am able to pass a value, also I am able to accept a table output from SAP.
Please guide.
I tried to typecast array as an object.
My Code:
<?php
include("include/config.php");
$sql = "SELECT tid,OrderNumber FROM transhistory ORDER by timestamp ASC limit 2";
$result= mysqli_query($db,$sql);
$i=0;
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
//Array based on output table
$pmt[$i][0] = ""; //Mandt
$pmt[$i][1] = $row["tid"]; //Refnum
$pmt[$i][2] = $row["OrderNumber"]; //Orderno
$i++;
}
/*Two methods I tried */
$object = (object) $pmt;
$object = json_decode(json_encode($pmt), FALSE);
#Define Authentication
$SOAP_AUTH = array( 'login' => 'abc',
'password' => 'abc');
#Specify WSDL
$WSDL = "working URL here";
#Create Client Object, download and parse WSDL
$client = new SoapClient($WSDL,$SOAP_AUTH);
#Setup input parameters (SAP Likes to Capitalise the parameter names)
$params = array(
'Zpmt' => $object
);
#Call Operation (Function). Catch and display any errors
try {
$result = $client->ZphpOT($params);
} catch (SoapFault $exception) {
echo 'Error!Server Connectivity issue. Please try again later.';
die();
}
?>
I don't know if the answer may be useful for somebody but usually you send parameters like this
$result = $client->ZphpOT("VARIABLE_NAME"=>$params);

Create a WSDL with REST

I have a several problems to moment to create a WSDL with REST in PHP. I read a little bit about this, supposedly REST use WADL. I need a library or framework that generated a WADL or type WSDL of my code PHP (class, methods, vars).
Thanks a lot!
I created a simulation with php but this no get the return vars
... Class
... Methods
... Vars
if(isset($_GET['wadl'])):
header('Content-Type: text/xml');
$foo = new proveedores();
$get_class = get_class($foo);
// create the new XML document
$dom = new DOMDocument('1.0', 'iso-8859-1');
// create the root element
$list_of_teams = $dom->createElement($get_class);
$dom->appendChild($list_of_teams);
$class = new ReflectionClass($get_class);
$methods = $class->getMethods();
foreach ($methods as $m) {
$method = $class->getMethod($m->name);
// create the first element
$team = $dom->createElement($m->name);
$list_of_teams->appendChild($team);
$parameters = $method -> getParameters();
if(!empty($parameters)):
foreach ($parameters as $p) {
$name = $team->appendChild($dom->createElement('parameters'));
$name->appendChild($dom->createTextNode($p -> name));
}
endif;
}
print $xml_result = $dom->saveXML();
endif;

Retrieving Contact photo with Zend Gdata with PHP

When querying for contacts I use the code below to retrieve all my contacts
$gdata = new Zend_Gdata($client);
$gdata->setMajorProtocolVersion(3);
$query = new Zend_Gdata_Query(
"http://www.google.com/m8/feeds/contacts/default/full");
$feed = $gdata->getFeed($query);
As I look through each entry of the $feed I can get access to the contactId and according to the Contacts API I should be able to retrieve the picture by doing a GET on the following URL:
http://www.google.com/m8/feeds/photos/media/default/contactId
So I use the same mechanism to retrieve contacts and try to get a photo after setting $id:
$query = new Zend_Gdata_Query(
"http://www.google.com/m8/feeds/photos/media/default/$id");
$entryFeed = $gdata->getFeed($query);
But I get an error "DOMDocument cannot parse XML". Am I doing something wrong? Are there any example docs?
To get the photo use DOMXpath and search for the "//atom:link" tag, then use $gdata->get(href) to grab the photo. Check for the etag attribute for each link, this tells you whether or not there is a profile photo associated with this contact.
$doc = new DOMDocument;
$doc->recover = true;
$doc->loadXML($entry->getXML());
$xpath = new DOMXPath($doc);
$links = $xpath->query('//atom:link');
foreach($links as $link) {
if($link->getAttribute('etag') != "") {
$http_response = $gdata->get($link->getAttribute('href'));
$rawImage = $http_response->getBody();
$fp = fopen("/var/www/profile/$id.jpg", "w");
fwrite($fp, $rawImage);
fclose($fp);
break;
}
}

'Node no longer exists' error in PHP

I'm using the following code to turn user's IP into latitude/longitude information using the hostip web service:
//get user's location
$ip=$_SERVER['REMOTE_ADDR'];
function get_location($ip) {
$content = file_get_contents('http://api.hostip.info/?ip='.$ip);
if ($content != FALSE) {
$xml = new SimpleXmlElement($content);
$coordinates = $xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->ipLocation->children('gml', TRUE)->pointProperty->Point->coordinates;
$longlat = explode(',', $coordinates);
$location['longitude'] = $longlat[0];
$location['latitude'] = $longlat[1];
$location['citystate'] = '==>'.$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->children('gml', TRUE)->name;
$location['country'] = '==>'.$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->countryName;
return $location;
}
else return false;
}
$data = get_location($ip);
$center_long=$data['latitude'];
$center_lat=$data['longitude'];
This works fine for me, using $center_long and $center_lat the google map on the page is centered around my city, but I have a friend in Thailand who tested it from there, and he got this error:
Warning: get_location() [function.get-location]: Node no longer exists in /home/bedbugs/registry/index.php on line 21
So I'm completely confused by this, how could he be getting an error if I don't? I tried googling it and it has something to do with parsing XML data, but the parsing process is the same for me and him. Note that line 21 is the one that starts with '$coordinates =' .
You need to check the service actually has an <ipLocation> listed, you're doing:
$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->ipLocation
->children('gml', TRUE)->pointProperty->Point->coordinates
but the XML output for my IP is:
<HostipLookupResultSet version="1.0.1" xsi:noNamespaceSchemaLocation="http://www.hostip.info/api/hostip-1.0.1.xsd">
<gml:description>This is the Hostip Lookup Service</gml:description>
<gml:name>hostip</gml:name>
<gml:boundedBy>
<gml:Null>inapplicable</gml:Null>
</gml:boundedBy>
<gml:featureMember>
<Hostip>
<ip>...</ip>
<gml:name>(Unknown City?)</gml:name>
<countryName>(Unknown Country?)</countryName>
<countryAbbrev>XX</countryAbbrev>
<!-- Co-ordinates are unavailable -->
</Hostip>
</gml:featureMember>
</HostipLookupResultSet>
The last part ->children('gml', TRUE)->pointProperty->Point->coordinates gives the error because it has no children (for some IPs).
You can add a basic check to see if the <ipLocation> node exists like this (assuming the service always returns at least up to the <hostIp> node):
function get_location($ip) {
$content = file_get_contents('http://api.hostip.info/?ip='.$ip);
if ($content === FALSE) return false;
$location = array('latitude' => 'unknown', 'longitude' => 'unknown');
$xml = new SimpleXmlElement($content);
$hostIpNode = $xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip;
if ($hostIpNode->ipLocation) {
$coordinates = $hostIpNode->ipLocation->children('gml', TRUE)->pointProperty->Point->coordinates;
$longlat = explode(',', $coordinates);
$location['longitude'] = $longlat[0];
$location['latitude'] = $longlat[1];
}
$location['citystate'] = '==>'.$hostIpNode->children('gml', TRUE)->name;
$location['country'] = '==>'.$hostIpNode->countryName;
return $location;
}

PHP+SoapClient exceptions and headers? (UPS Rating)

I'm trying to use PHP and SoapClient to utilize the UPS Ratings web service. I found a nice tool called WSDLInterpreter to create a starting point library for creating the service requests, but regardless what I try I keep getting the same (non-descriptive) error:
EXCEPTION=SoapFault::__set_state(array(
'message' => 'An exception has been raised as a result of client data.',
'string' => '',
'code' => 0,
Um ok, what the hell does this mean?
Unlike some of the other web service tools I have implemented, the UPS Soap wants a security block put into the header. I tried doing raw associative array data but I wasn't sure 100% if I was injecting the header part correctly.
Using the WSDLInterpreter, it pulls out a RateService class with a ProcessRate method that excepts it's own (instance) datastructure for the RateRequest and UPSSecurity portions, but all of the above generates that same error.
Here's a sample of the code that I'm using that calls classes defined by the interpreter:
require_once "Shipping/UPS/RateService.php"; // WSDLInterpreter class library
class Query
{
// constants removed for stackoverflow that define (proprietary) security items
private $_upss;
private $_shpr;
// use Interpreter code's RateRequest class to send with ProcessRate
public function soapRateRequest(RateRequest $req, UPSSecurity $upss = null)
{
$res = false;
if (!isset($upss)) {
$upss = $this->__getUPSS();
}
echo "SECURITY:\n" . var_export($upss, 1) . "\n";
$upsrs = new RateService(self::UPS_WSDL);
try {
$res = $upsrs->ProcessRate($req, $upss);
} catch (SoapFault $exception) {
echo 'EXCEPTION=' . var_export($exception, 1) . "\n";
}
return $res;
}
// create a soap data structure to send to web service from shipment
public function getRequestSoap(Shipment $shpmnt)
{
$qs = new RateRequest();
// pickup information
$qs->PickupType->Code = '01';
$qs->Shipment->Shipper = $this->__getAcctInfo();
// Ship To address
$qs->Shipment->ShipTo->Address->AddressLine = $this->__getAddressArray($shpmnt->destAddress->address1, $shpmnt->destAddress->address2);
$qs->Shipment->ShipTo->Address->City = $shpmnt->destAddress->city;
$qs->Shipment->ShipTo->Address->StateProvinceCode = $shpmnt->destAddress->state;
$qs->Shipment->ShipTo->Address->PostalCode = $shpmnt->destAddress->zip;
$qs->Shipment->ShipTo->Address->CountryCode = $shpmnt->destAddress->country;
$qs->Shipment->ShipTo->Name = $shpmnt->destAddress->name;
// Ship From address
$qs->Shipment->ShipFrom->Address->AddressLine = $this->__getAddressArray($shpmnt->origAddress->address1, $shpmnt->origAddress->address2);
$qs->Shipment->ShipFrom->Address->City = $shpmnt->origAddress->city;
$qs->Shipment->ShipFrom->Address->StateProvinceCode = $shpmnt->origAddress->state;
$qs->Shipment->ShipFrom->Address->PostalCode = $shpmnt->origAddress->zip;
$qs->Shipment->ShipFrom->Address->CountryCode = $shpmnt->origAddress->country;
$qs->Shipment->ShipFrom->Name = $shpmnt->origAddress->name;
// Service type
// TODO cycle through available services
$qs->Shipment->Service->Code = "03";
$qs->Shipment->Service->Description = "UPS Ground";
// Package information
$pkg = new PackageType();
$pkg->PackagingType->Code = "02";
$pkg->PackagingType->Description = "Package/customer supplied";
// dimensions
$pkg->Dimensions->UnitOfMeasurement->Code = $shpmnt->dimensions->dimensionsUnit;
$pkg->Dimensions->Length = $shpmnt->dimensions->length;
$pkg->Dimensions->Width = $shpmnt->dimensions->width;
$pkg->Dimensions->Height = $shpmnt->dimensions->height;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageServiceOptions->DeclaredValue->MonetaryValue = $shpmnt->dimensions->value;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageWeight->UnitOfMeasurement = $this->__getWeightUnit($shpmnt->dimensions->weightUnit);
$pkg->PackageWeight->Weight = $shpmnt->dimensions->weight;
$qs->Shipment->Package = $pkg;
$qs->CustomerClassification->Code = 123456;
$qs->CustomerClassification->Description = "test_rate_request";
return $qs;
}
// fill out and return a UPSSecurity data structure
private function __getUPSS()
{
if (!isset($this->_upss)) {
$unmt = new UsernameToken();
$unmt->Username = self::UPSS_USERNAME;
$unmt->Password = self::UPSS_PASSWORD;
$sat = new ServiceAccessToken();
$sat->AccessLicenseNumber = self::UPSS_ACCESS_LICENSE_NUMBER;
$upss = new UPSSecurity();
$upss->UsernameToken = $unmt;
$upss->ServiceAccessToken = $sat;
$this->_upss = $upss;
}
return $this->_upss;
}
// get our shipper/account info (some items blanked for stackoverflow)
private function __getAcctInfo()
{
if (!isset($this->_shpr)) {
$shpr = new ShipperType();
$shpr->Address->AddressLine = array(
"CONTACT",
"STREET ADDRESS"
);
$shpr->Address->City = "CITY";
$shpr->Address->StateProvinceCode = "MI";
$shpr->Address->PostalCode = "ZIPCODE";
$shpr->Address->CountryCode = "US";
$shpr = new ShipperType();
$shpr->Name = "COMPANY NAME";
$shpr->ShipperNumber = self::UPS_ACCOUNT_NUMBER;
$shpr->Address = $addr;
$this->_shpr = $shpr;
}
return $this->_shpr;
}
private function __getAddressArray($adr1, $adr2 = null)
{
if (isset($adr2) && $adr2 !== '') {
return array($adr1, $adr2);
} else {
return array($adr1);
}
}
}
It doesn't even seem to be getting to the point of sending anything over the Soap so I am assuming it is dying as a result of something not matching the WSDL info. (keep in mind, I've tried sending just a properly seeded array of key/value details to a manually created SoapClient using the same WSDL file with the same error resulting)
It would just be nice to get an error to let me know what about the 'client data' is a problem. This PHP soap implementation isn't impressing me!
I know this answer is probably way too late, but I'll provide some feedback anyway. In order to make a custom SOAP Header you'll have to override the SoapHeader class.
/*
* Auth Class to extend SOAP Header for WSSE Security
* Usage:
* $header = new upsAuthHeader($user, $password);
* $client = new SoapClient('{...}', array("trace" => 1, "exception" => 0));
* $client->__setSoapHeaders(array($header));
*/
class upsAuthHeader extends SoapHeader
{
...
function __construct($user, $password)
{
// Using SoapVar to set the attributes has proven nearly impossible; no WSDL.
// It might be accomplished with a combined SoapVar and stdClass() approach.
// Security Header - as a combined XSD_ANYXML SoapVar
// This method is much easier to define all of the custom SoapVars with attributes.
$security = '<ns2:Security xmlns:ns2="'.$this->wsse.'">'. // soapenv:mustUnderstand="1"
'<ns2:UsernameToken ns3:Id="UsernameToken-49" xmlns:ns3="'.$this->wsu.'">'.
'<ns2:Username>'.$user.'</ns2:Username>'.
'<ns2:Password Type="'.$this->password_type.'">'.htmlspecialchars($password).'</ns2:Password>'.
'</ns2:UsernameToken>'.
'</ns2:Security>';
$security_sv = new SoapVar($security, XSD_ANYXML);
parent::__construct($this->wsse, 'Security', $security_sv, false);
}
}
Then call the upsAuthHeader() before the soap call.
$client = new SoapClient($this->your_ups_wsdl,
array('trace' => true,
'exceptions' => true,
'soap_version' => SOAP_1_1
)
);
// Auth Header - Security Header
$header = new upsAuthHeader($user, $password);
// Set Header
$client->__setSoapHeaders(array($header));

Categories