Welcome Guest, Not a member yet? Register   Sign In
nusoap, wsdls and fedex equals huh?
#1

[eluser]FuzzyJared[/eluser]
I have started to work attempt to work the fedex api into an application that I am building, and I am having some problems in my first or second step. I have decided that I will be utilizing the nusoap library within my hopeful final solution but I am having some problems getting started.

This could all just be me, but I am having some problems hitting the ground running. The sad or unfortunate part of this is it is difficult to know where to start beyond getting my files together and my developer credentials from fedex. Which took 2 phone calls and countless emails, but that is another story.

The point of my long winded start is does anyone have any good suggestions on where to get started with nusoap and CI? Articles or tutorials?

As a secondary question, the nusoap library has classes within the library file. I am unfamiliar with this being done in CI, and don't know exactly how to declare new object in this manner. All the examples ( not CI examples ) that I have found follows the include php file and then declare a new object.
Code:
$wsdl = new wsdl($wsdl_url)

But how would this work within the CI environment where normally we load the library in the constructor?
#2

[eluser]Nathan Pitman (Nine Four)[/eluser]
I have no idea but you're right that it would be great if some of the more knowledgeable folk here were able to put together a very simple tutorial using the NuSoap Library on the Wiki. Smile
#3

[eluser]FuzzyJared[/eluser]
I have gone ahead and built a simple library to work with it, but it has not yet been approved by fedex. When that gets done I will probably be making a post on the wiki or forum with the fedex library.
#4

[eluser]Nathan Pitman (Nine Four)[/eluser]
Out of interest, you don't happen to have gotten NuSoap working without querystrings???
#5

[eluser]FuzzyJared[/eluser]
It has been a while since I worked on this portion of the site, I didn't end up using nusoap. Most of my initial woes were from incorrect commenting from Fedex integration files. And one case of code dyslexia on my part =)

Below is the sample from the code that I was able to get working with Fedex.

Code:
function rateCart($service_type, $weight) {
        // SHIPPER INFO
        // CART INFORMATION
        
        ini_set("soap.wsdl_cache_enabled", "0");
        
        $newline = '<br />';
        $client = new SoapClient('wsdl/RateService_v2.wsdl', array('trace' => 1)); // replace with valid path to WSDL

        $request['WebAuthenticationDetail'] = array('UserCredential' =>
            array('Key' => $this->CI->fedex_key, 'Password' => $this->CI->fedex_password)
        );
        $request['ClientDetail'] = array('AccountNumber' => $this->CI->fedex_account_number, 'MeterNumber' => $this->CI->fedex_meter_number);// Replace 'XXX' with your account and meter number
        $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v2 using PHP ***');
        $request['Version'] = array('ServiceId' => 'crs', 'Major' => '2', 'Intermediate' => '0', 'Minor' => '0');
        $request['Origin'] = array('StreetLines' => array($this->CI->shipper_address), // Origin details
        'City' => $this->CI->shipper_city,
        'StateOrProvinceCode' => $this->CI->shipper_state,
        'PostalCode' => $this->CI->shipper_zipcode,
        'CountryCode' => 'US');
        $request['Destination'] = array('StreetLines' => array($this->CI->shipper_address), // Origin details
        'City' => $this->CI->shipping_info['city'],
        'StateOrProvinceCode' => $this->CI->shipping_info['state'],
        'PostalCode' => $this->CI->shipping_info['zipcode'],
        'CountryCode' => 'US');
        $request['Payment'] = array('PaymentType' => 'SENDER'); // valid codes RECIPIENT, SENDER and THIRD_PARTY
        $request['DropoffType'] = 'REGULAR_PICKUP'; // valid codes BUSINESS_SERVICE_CENTER, DROP_BOX, REGULAR_PICKUP, REQUEST_COURIER and STATION
        $request['ServiceType'] = $service_type; // valid codes STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
        $request['PackagingType'] = 'YOUR_PACKAGING'; // valid codes FEDEX_BOK, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
        $request['ShipDate'] = date('Y-m-d');
        $request['RateRequestTypes'] = 'ACCOUNT'; // valid codes ACCOUNT, LIST

        // Passing single piece shipment rate request
        $request['PackageCount'] = 1; // currently only one occurrence of RequestedPackage is supported
        $request['Packages'] = array(0 => array('Weight' => array('Value' => $weight, 'Units' => 'LB'), // valid code LB and KG
        'InsuredValue' => array('Amount' => 100, 'Currency' => 'USD'),
        'Dimensions' => array('Length' => '1', 'Width' => '1', 'Height' => '1', 'Units' => 'IN'), // valid code IN and CM
        'SpecialServicesRequested' => array('SpecialServiceTypes' => 'APPOINTMENT_DELIVERY'))); // valid codes HOLD_AT_LOCATION, ...

        try
        {
            $response = $client ->__soapCall("getRate", array('parameters' => $request));

            if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
            {
                return $response->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount;
                return returnRequestResponse($client);
            }
            else
            {
                echo 'Error in processing transaction.'. $newline. $newline;
                foreach ($response -> Notifications as $notification)
                {          
                    if(is_array($response -> Notifications))
                    {              
                       echo $notification -> Severity;
                       echo ': ';          
                       echo $notification -> Message . $newline;
                    }
                    else
                    {
                        echo $notification . $newline;
                    }
                }
                $this->_writeToLog($client);    // Write to log file
                //return $return;
                return '';
                
            }

            

        } catch (SoapFault $exception) {
            $this->printFault($exception, $client);
        }
        
    }
#6

[eluser]FuzzyJared[/eluser]
I should also note that although this does work and kicks back rates, but I have not gone through and done a complete test of log file tracking and such.

Also the majority of this code was provided by Fedex, I just had to tweak certain areas and build a library and a couple models around it.
#7

[eluser]devain[/eluser]
since you got the following working is there a way that you can post complete code and how to call it
#8

[eluser]FuzzyJared[/eluser]
Code:
class Fedex_api
{
    // --------------------------------------------------------------------

    /**
     *
     */
    function Fedex_api()
    {
        $this->CI=& get_instance();
        //log_message('debug', "Fedex API Class Initialized");
        $this->CI->load->library('db_session');
        $this->CI->load->library('ShoppingCart','shoppingcart');
        $this->CI->load->library('Nusoap','nusoap');
        $this->CI->load->model('shippingmodel','shippingmodel');
        $this->CI->load->model('fedexmodel','fedexmodel');
        $this->CI->load->model('usermodel','usermodel');
        $this->CI->load->model('productsmodel', 'productsmodel');
        $this->CI->load->helper('fedex_helper');
        
        // COMPANY VARIABLES
        $this->CI->credentials = $this->CI->fedexmodel->returnCredentials();
        $this->CI->fedex_key = $this->CI->credentials['access_key'];
        $this->CI->fedex_password = $this->CI->credentials['password'];
        $this->CI->fedex_account_number = $this->CI->credentials['account_number'];
        $this->CI->fedex_meter_number = $this->CI->credentials['meter_number'];
        $this->CI->shipper_address = $this->CI->credentials['address'];
        $this->CI->shipper_city = $this->CI->credentials['city'];
        $this->CI->shipper_state = $this->CI->credentials['state'];
        $this->CI->shipper_zipcode = $this->CI->credentials['zipcode'];
        // USER VARIABLES
        $this->CI->user_id = $this->CI->db_session->userdata('id');
        //$this->CI->user_info = $this->CI->usermodel->getUserById($this->CI->user_id);
        $this->CI->default_shipping = $this->CI->shippingmodel->getDefaultShippingAddressForUser($this->CI->user_id);
        foreach($this->CI->default_shipping->result() as $info)
        {
            $this->CI->shipping_info = array(
                'name'=> $info->name,
                'address'=> $info->address,
                'address_2'=>$info->address_2,
                'company'=>$info->company,
                'city'=>$info->city,
                'state'=>$info->state,
                'zipcode'=>$info->zipcode
            );
            
        }
        
    }
#9

[eluser]FuzzyJared[/eluser]
Code:
// --------------------------------------------------------------------

    /**
     * @param mixed $cart
     * @param integer $weight
     */
    
    
    function rateCart($service_type, $weight) {
        // NUSOAP SHIPPING INFO
        $this->CI->nusoap_client = new nusoap_client('wsdl/RateService_v2.wsdl', true);
        
        //print_r($this->CI->nusoap_client);

        if($this->CI->nusoap_client->fault)
        {
            $text = 'Error: '.$this->nusoap_client->fault;
        }
        else
        {
            if($this->CI->nusoap_client->getError())
            {
                $text = 'Error: '.$this->nusoap_client->getError();
            }
            else
            {
                $request = array();
                $request['WebAuthenticationDetail'] = array('UserCredential' =>
                    array('Key' => $this->CI->fedex_key, 'Password' => $this->CI->fedex_password)
                );
                $request['ClientDetail'] = array('AccountNumber' => $this->CI->fedex_account_number, 'MeterNumber' => $this->CI->fedex_meter_number);// Replace 'XXX' with your account and meter number
                $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v2 using PHP ***');
                $request['Version'] = array('ServiceId' => 'crs', 'Major' => '2', 'Intermediate' => '0', 'Minor' => '0');
                $request['Origin'] = array('StreetLines' => array($this->CI->shipper_address), // Origin details
                'City' => $this->CI->shipper_city,
                'StateOrProvinceCode' => $this->CI->shipper_state,
                'PostalCode' => $this->CI->shipper_zipcode,
                'CountryCode' => 'US');
                $request['Destination'] = array('StreetLines' => array($this->CI->shipper_address), // Origin details
                'City' => $this->CI->shipping_info['city'],
                'StateOrProvinceCode' => $this->CI->shipping_info['state'],
                'PostalCode' => $this->CI->shipping_info['zipcode'],
                'CountryCode' => 'US');
                $request['Payment'] = array('PaymentType' => 'SENDER'); // valid codes RECIPIENT, SENDER and THIRD_PARTY
                $request['DropoffType'] = 'REGULAR_PICKUP'; // valid codes BUSINESS_SERVICE_CENTER, DROP_BOX, REGULAR_PICKUP, REQUEST_COURIER and STATION
                $request['ServiceType'] = $service_type; // valid codes STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
                $request['PackagingType'] = 'YOUR_PACKAGING'; // valid codes FEDEX_BOK, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
                $request['ShipDate'] = date('Y-m-d');
                $request['RateRequestTypes'] = 'ACCOUNT'; // valid codes ACCOUNT, LIST
        
                // Passing single piece shipment rate request
                $request['PackageCount'] = 1; // currently only one occurrence of RequestedPackage is supported
                $request['Packages'] = array(0 => array('Weight' => array('Value' => $weight, 'Units' => 'LB'), // valid code LB and KG
                'InsuredValue' => array('Amount' => 100, 'Currency' => 'USD'),
                'Dimensions' => array('Length' => '1', 'Width' => '1', 'Height' => '1', 'Units' => 'IN'), // valid code IN and CM
                'SpecialServicesRequested' => array('SpecialServiceTypes' => 'APPOINTMENT_DELIVERY')));
                
                $response = $this->CI->nusoap_client->call("getRate", array($request));
                
                $err = $this->CI->nusoap_client->getError();
                if($err)
                {
                    echo $err;
                    
                }
                else
                {
                    if(count($response) > 0 && is_array($response)) {
                        if($response['HighestSeverity'] != 'FAILURE' && $response['HighestSeverity'] != 'ERROR')
                        return $response['RatedShipmentDetails']['ShipmentRateDetail']['TotalNetCharge']['Amount'];
                    } else {
                        foreach ($response['Notifications'] as $notification)
                        {
                            if(is_array($response -> Notifications))
                            {              
                               //echo $notification -> Severity;
                              // echo ': ';          
                               //echo $notification -> Message . $newline;
                            }
                            else
                            {
                                //echo $notification . $newline;
                            }
                        }
                        //$this->_writeToLog($client);    // Write to log file
                    }
                }
                
                
            }
        }
        
    }
    
    /**
     * SOAP request/response logging to a file
     */
    function _writeToLog($client){
        $transactions_log_file = 'logs/fedextransactions.log';
        if (!$logfile = fopen($transactions_log_file, "a"))
        {
            error_func("Cannot open " . $transactions_log_file . " file.\n", 0);
            exit(1);
        }
    
        fwrite($logfile, sprintf("\r%s:- %s",date("D M j G:i:s T Y"), $client->__getLastRequest(). "\n\n" . $client->__getLastResponse()));
        
    }

    
    /**
     *  Print SOAP Fault
     */  
    function printFault($exception, $client) {
        echo '<h2>Fault</h2>' . "\n";                        
        echo "<b>Code:</b>{$exception->faultcode}<br>\n";
        echo "<b>String:</b>{$exception->faultstring}<br>\n";
        $this->_writeToLog($client);
    }
    
}
#10

[eluser]FuzzyJared[/eluser]
The above 2 posts are the culmination from an ordeal which has been very frustrating. I was able to get the FedEx API using PHP's SOAP, but the live server did not have PHP compiled with SOAP. So I ended up utilizing NuSoap from the wiki contribution and modifications to my original code.

So above is pretty much my fedex library that I have not quite finished. But it is getting me the basics of what is needed for my app.




Theme © iAndrew 2016 - Forum software by © MyBB