Integrating UPS Xml soap feed (PHP) - php

I am trying to get the xml rate soap feed from UPS working.
Currently I am getting the error "Wrong version" (__Soapcall Exeption) or "0FailureHard10002The XML document is well formed but the document is not valid1" (Respons from server or php).
I took the example provided in the developers toolkit. I tried everything =>
Change soap version to 1.2
Grab wsdl from remote url instead of on
the disk
I double checked the endpoint and userid, accesskey, pass,
...
Does anyone have a working script ?, or even better can someone correct my mistake :)
Code:
<?php
class UpsRate{
private $access,$userid,$passwd,$wsdl,$operation,$endpointurl;
public function __construct() {
$this->setConfig();
}
public function setConfig($is_test = true){
$this->access = sfConfig::get('app_shipping_ups_access');
$this->userid = sfConfig::get('app_shipping_ups_userid');
$this->passwd = sfConfig::get('app_shipping_ups_password');
$this->wsdl = sfConfig::get('sf_data_dir').'/wsdl/ups/RateWS.wsdl';
$this->operation = "ProcessRate";
$this->endpointurl = $is_test?'https://wwwcie.ups.com/ups.app/xml/Rate':'https://onlinetools.ups.com/ups.app/xml/Rate';
}
private function processRate(){
//create soap request
$option['RequestOption'] = 'Shop';
$request['Request'] = $option;
$pickuptype['Code'] = '01';
$pickuptype['Description'] = 'Daily Pickup';
$request['PickupType'] = $pickuptype;
$customerclassification['Code'] = '01';
$customerclassification['Description'] = 'Classfication';
$request['CustomerClassification'] = $customerclassification;
$shipper['Name'] = 'Trutec';
$shipper['ShipperNumber'] = 'Y5562A';
$address['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$address['City'] = 'Antwerp';
//$address['StateProvinceCode'] = 'MD';
$address['PostalCode'] = '2100';
$address['CountryCode'] = 'BE';
$shipper['Address'] = $address;
$shipment['Shipper'] = $shipper;
$shipto['Name'] = 'Imani Imaginarium';
$addressTo['AddressLine'] = '21 ARGONAUT SUITE B';
$addressTo['City'] = 'ALISO VIEJO';
//$addressTo['StateProvinceCode'] = 'CA';
$addressTo['PostalCode'] = '92656';
$addressTo['CountryCode'] = 'US';
$addressTo['ResidentialAddressIndicator'] = '';
$shipto['Address'] = $addressTo;
$shipment['ShipTo'] = $shipto;
$shipfrom['Name'] = 'Trutec';
$addressFrom['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$addressFrom['City'] = 'Deurne';
//$addressFrom['StateProvinceCode'] = 'MD';
$addressFrom['PostalCode'] = '2100';
$addressFrom['CountryCode'] = 'BE';
$shipfrom['Address'] = $addressFrom;
$shipment['ShipFrom'] = $shipfrom;
$service['Code'] = '03';
$service['Description'] = 'Service Code';
$shipment['Service'] = $service;
$packaging1['Code'] = '02';
$packaging1['Description'] = 'Rate';
$package1['PackagingType'] = $packaging1;
$dunit1['Code'] = 'IN';
$dunit1['Description'] = 'cm';
$dimensions1['Length'] = '5';
$dimensions1['Width'] = '4';
$dimensions1['Height'] = '10';
$dimensions1['UnitOfMeasurement'] = $dunit1;
$package1['Dimensions'] = $dimensions1;
$punit1['Code'] = 'KG';
$punit1['Description'] = 'KG';
$packageweight1['Weight'] = '4';
$packageweight1['UnitOfMeasurement'] = $punit1;
$package1['PackageWeight'] = $packageweight1;
$shipment['Package'] = array( $package1 );
$shipment['ShipmentServiceOptions'] = '';
$shipment['LargePackageIndicator'] = '';
$request['Shipment'] = $shipment;
return $request;
}
public function getRate(){
try {
//nitialize soap client
$client = new SoapClient($this->wsdl , array('soap_version' => 'SOAP_1_1','trace' => 1));
//set endpoint url
$client->__setLocation($this->endpointurl);
//create soap header
$usernameToken['Username'] = $this->userid;
$usernameToken['Password'] = $this->passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $this->access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
//get response
return $client->__soapCall($this->operation ,array($this->processRate()));
}
catch(Exception $ex)
{
echo '<pre>';
return print_r($client->__getLastResponse());
echo '</pre>';
}
}
}
?>

The error notifies that your XML is being correctly formatted but you have included one or more elements that are incompatible. Are you able to dump the XML sent ? This may be easier to determine where the error is being detected.
I wouldn't recommend depending on the examples in the UPS documentation to work, they are for illustrative purposes only and probably have not been updated since the first issue.

I had the same issue, and worked this out:
When I would make test calls, they would work. The endpoint I used for the test calls was
https://wwwcie.ups.com/webservices/Rate
However, when I would change to the live calls, then I would receive the wrong version error. That endpoint is:
https://onlinetools.ups.com/webservices
I reviewed the wsdl document, and found near the end a section that looks like this:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<!-- <soap:address location="https://onlinetools.ups.com/webservices/Rate"/> -->
<!-- CIE (Customer Integration Environment) URL -->
<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>
</wsdl:port>
I noticed that the live version endpoint was commented out, so I changed the section as follows:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<soap:address location="https://onlinetools.ups.com/webservices/Rate"/>
<!-- CIE (Customer Integration Environment) URL -->
<!--<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>-->
</wsdl:port>
I'm not sure this will help anyone else, but this ended up resolving my issues.

Related

PHP Function - Convert HTML form input into resuable function for multiple inputs

I'm using the Zillow API in order to get some data from user inputs. So far I've been able to correctly use the API to get the desired data from a single input.
The issue I'm running into is when I try and convert my simple block of code into a function that I can reuse multiple times with multiple inputs.Eventually, I want the user to be able to uploaded a CSV file or something and run this function through multiple inputs.
Below is my code that is functioning properly:
HTML
<form action="logic.php" method="post">
<p>Address: <input type="text" name="address"></p>
<p>City/State: <input type="text" name="csz"></p>
<input type="submit">
</form>
PHP
//API Key
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$addressID;
$estimate_result = file_get_contents($zurl);
$estimate_data = simplexml_load_string($zresult);
$estimate = $zdata->response->zestimate->amount;
echo $estimate;
Now the issue is when I try and wrap both of these up into two separate functions in order to use them for multiple inputs.
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function getAddressID($ad,$cs){
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$ad."&citystatezip=".$cs;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID){
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$aID;
$estimate_result = file_get_contents($estimate_url);
$estimate_data = simplexml_load_string($estimate_result);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID); //Calling function doesn't return anything
If essentially I'm doing this same thing as the first PHP example. Why isn't this working from within a function? Did I overlook something?
Ant help on this would be greatly appreciated.
The problem is that you are using the $api_key variable inside both functions, and that variable is not available there. PHP works a bit different then other languages. You can read up on it here: http://php.net/manual/en/language.variables.scope.php
I suggest you extract a function for calling the api. This way you can declare the api key in that function. It also allows you to easier maintain your code (you could improve your api call by adding some error handling or switching to curl or something). The golden rule of a programmer, Don't Repeat Yourself.
The code could look something like this (untested):
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function callZillow($endpoint, array $params)
{
$params['zws-id'] = 'XXX'; // this would be your api_key
$url = 'http://www.zillow.com/webservice/' . $endpoint . '.htm?' . http_build_query($params);
$result = file_get_contents($url);
return simplexml_load_string($result);
}
function getAddressID($ad, $cs)
{
//Get Address ID From API
$data = callZillow('GetSearchResults', ['address' => $ad, 'citystatezip' => $cs]);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID)
{
//Get Estimate from API (using adressID)
$estimate_data = callZillow('GetZestimate', ['zpid' => $aID]);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID);

PHP [function.file-get-contents]: Failed to open stream

This is really annoying me, the php script was working and returning the weather from open weather map but literally all of a sudden the php script takes forever to execute and the following error is produced:
Warning: file_get_contents(http://api.openweathermap.org/data/2.5/weather?lat=&lon=&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070) [function.file-get-contents]: failed to open stream: Connection timed out in /xxx/xxx/public_html/fullweather.php on line 15
Any help would be appreciated. The php script can be viewed below. Only the beginning is important (first 18 lines) but I have included the full thing.
<?php
$lat = $_POST["latitude"];
$lon = $_POST["longitude"];
$url="http://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
// Make call with cURL
$session = curl_init($url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
$json=file_get_contents($url);
$data=json_decode($json,true);
class weatherdata
{
public $temp = "";
public $weather = "";
public $clouds = "";
public $area = "";
public $humidity = "";
public $humidpressure = "";
public $weatherdesc = "";
public $tempmin = "";
public $tempmax = "";
public $windspeed = "";
public $winddirec = "";
}
$data1 = $data['main']['temp'];
$data2 = $data['weather'][0]['main'];
$data3 = $data['clouds']['all'];
$data4 = $data['name'];
$data5 = $data['main']['humidity'];
$data6 = $data['main']['pressure'];
$data7 = $data['weather'][0]['description'];
$data8 = $data['main']['temp_min'];
$data9 = $data['main']['temp_max'];
$data10 = $data['wind']['speed'];
$data12 = $data['wind']['deg'];
$weatherdata = new weatherdata();
$weatherdata->temp = $data1;
$weatherdata->weather = $data2;
$weatherdata->clouds = $data3;
$weatherdata->area = $data4;
$weatherdata->humidity = $data5;
$weatherdata->humidpressure = $data6;
$weatherdata->weatherdesc = $data7;
$weatherdata->tempmin = $data8;
$weatherdata->tempmax = $data9;
$weatherdata->windspeed = $data10;
$weatherdata->winddirec = $data12;
$output[] = $weatherdata;
print(json_encode($output));
?>
I think the API was just down, cause the link is working for me right now.
Try one more time.
May be the API had change it's url by the time. Try to check the documentation for any updated information. I think that they could change it and your code couldnt find because this $url doesn't exist anymore.
i added https instead of http in url and it worked.
so maybe change http in url like this url.
$url="https://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
Edit
Also you should not show your api key to anyone as some one can use it.

codeigniter rest server POST "not allowed", but GET works fine

I am using codeigniter-restserver by Phil Sturgeon,
https://github.com/chriskacerguis/codeigniter-restserver
here is an problem I encountered:
When I do PUT request, everything works, but when I do POST, I got
"500 Internal Server Error"
<div id="container">
<h1>An Error Was Encountered</h1>
<p>The action you have requested is not allowed.</p>
</div>
my code is the following:
function test_post()
{
$this->response('ok', 200); // 200 being the HTTP response code
}
function test_get()
{
$this->response('ok', 200); // 200 being the HTTP response code
}
the working GET handelling can be found in the following URL
https://manage.pineconetassel.com/index.php/api/example/test/
NOTE that I allowed https only.
I used hurl.it to test the POST method, and it does not work.
here is the rest.php config:
$config['force_https'] = TRUE;
$config['rest_default_format'] = 'json';
$config['rest_status_field_name'] = 'status';
$config['rest_message_field_name'] = 'error';
$config['enable_emulate_request'] = TRUE;
$config['rest_realm'] = 'REST API';
$config['rest_auth'] = false;
$config['auth_source'] = 'ldap';
$config['auth_library_class'] = '';
$config['auth_library_function'] = '';
$config['rest_valid_logins'] = array('admin' => '1234');
$config['rest_ip_whitelist_enabled'] = false;
$config['rest_ip_whitelist'] = '';
$config['rest_ip_blacklist_enabled'] = false;
$config['rest_ip_blacklist'] = '';
$config['rest_database_group'] = 'default';
$config['rest_keys_table'] = 'keys';
$config['rest_enable_keys'] = FALSE;
$config['rest_key_column'] = 'key';
$config['rest_key_length'] = 40;
$config['rest_key_name'] = 'X-API-KEY';
$config['rest_logs_table'] = 'logs';
$config['rest_enable_logging'] = FALSE;
$config['rest_access_table'] = 'access';
$config['rest_enable_access'] = FALSE;
$config['rest_logs_json_params'] = FALSE;
$config['rest_limits_table'] = 'limits';
$config['rest_enable_limits'] = FALSE;
$config['rest_ignore_http_accept'] = FALSE;
$config['rest_ajax_only'] = FALSE;
Did I do something wrong or use a wrong way to test the POST or I need to configure something?
set $config['csrf_protection'] = FALSE; in config/config.php
Note it is not uder config/rest.php
The accepted answer is right.
But if you don't want to disable $config['csrf_protection'] in case you need it for web form, you need to exclude the REST API URIs, for example, your REST url starts with /api/, simply set
$config['csrf_exclude_uris'] = array(
'api/[a-z0-9/_-]+'
);
It is also under config/config.php. I use regular expression to make it simple.

Cannot instantiate a Note object using Evernote API in PHP

I am trying to develop a script (using the PHP example app as a basis) that will post a note to Evernote based on GET values.
When I insert this to the end of functions.php's listNotebooks()
$note_obj = new Note(array(
'contents' => $note_contents,
'title' => $title
));
It throws a 500 error. (In my code, $title & $note_contents are defined earlier. I have spent a lot of time trying to find proper documentation for the PHP API but it just seems non-existent. Any information on this topic would be greatly appreciated
Update: I did not realize the API was using PHP Namespaces: This fixed the issue:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
My code to add a note still does not work but I'll post it here once I figure it out.
These classes need to be imported:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
This will define our new note:
$noteAttr = new NoteAttributes();
$noteAttr->sourceURL = "http://www.example.com";
$note = new Note();
$note->guid = null;
$note->title = "My Title";
$note->content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd"><en-note>My Content</en-note>';
$note->contentHash = null;
$note->contentLength = null;
$note->created = time()*1000;
$note->updated = time()*1000;
$note->deleted = null;
$note->active = null;
$note->updateSequenceNum = null;
$note->notebookGuid = null;
$note->tagGuids = null;
$note->resources = null;
$note->attributes = $noteAttr;
$note->tagNames = null;
addNote($note);
This function will add a new note:
function addNote($newnote) {
global $noteRet;
if (empty($noteRet)) {
define("noteStoreHost", "sandbox.evernote.com");
define("noteStorePort", "80");
define("noteStoreProto", "https");
define("noteStoreUrl", "edam/note/");
$noteStoreTrans = new THttpClient(noteStoreHost, noteStorePort, noteStoreUrl . $_SESSION['shardId'], noteStoreProto);
$noteStoreProt = new TBinaryProtocol($noteStoreTrans);
$noteStore = new NoteStoreClient($noteStoreProt, $noteStoreProt);
$noteRet = $noteStore->createNote($_SESSION['accessToken'], $newnote);
return $noteRet;
}
}

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