ups, fedex and USPS shipping integration with joomla easily

step-1-> create a fedex10.php under /administrator/components/com_virtuemart/classes/shipping
---------------------------------------------------------------------------------------------
<?php
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/* You must fill in the "Service Logins
/* values below for the example to work   
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/

/*********** Shipping Services ************/
/* Here's an array of all the standard
/* shipping rates. You'll probably want to
/* comment out the ones you don't want
/******************************************/
// UPS
//$services['ups']['14'] = 'Next Day Air Early AM';
//$services['ups']['01'] = 'Next Day Air';
$services['ups']['65'] = 'Saver';
//$services['ups']['59'] = '2nd Day Air Early AM';
$services['ups']['02'] = '2nd Day Air';
$services['ups']['12'] = '3 Day Select';
$services['ups']['03'] = 'Ground';
/*$services['ups']['11'] = 'Standard';
$services['ups']['07'] = 'Worldwide Express';
$services['ups']['54'] = 'Worldwide Express Plus';
$services['ups']['08'] = 'Worldwide Expedited';*/


// FedEx
$services['fedex']['FEDEXGROUND'] = 'Ground';
$services['fedex']['PRIORITYOVERNIGHT'] = 'Priority Overnight';
$services['fedex']['STANDARDOVERNIGHT'] = 'Standard Overnight';
//$services['fedex']['FIRSTOVERNIGHT'] = 'First Overnight';
//$services['fedex']['FEDEX2DAY'] = '2 Day';
$services['fedex']['FEDEXEXPRESSSAVER'] = 'Express Saver';

/*$services['fedex']['FEDEX1DAYFREIGHT'] = 'Overnight Day Freight';
$services['fedex']['FEDEX2DAYFREIGHT'] = '2 Day Freight';
$services['fedex']['FEDEX3DAYFREIGHT'] = '3 Day Freight';
$services['fedex']['GROUNDHOMEDELIVERY'] = 'Home Delivery';
$services['fedex']['INTERNATIONALECONOMY'] = 'International Economy';
$services['fedex']['INTERNATIONALFIRST'] = 'International First';
$services['fedex']['INTERNATIONALPRIORITY'] = 'International Priority';*/

 $dbu = new ps_DB; // user data
        $dbv = new ps_DB; // vendor data
        $dbc = new ps_DB; // country data

        // get user info
        $q  = "SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_info_id='" . @$_REQUEST["ship_to_info_id"]."' AND ( country=country_2_code OR country=country_3_code)";
        $dbu->query($q);
        if ($dbu->num_rows()==0) {
            $vmLogger->debug("Fedex::__construct() no user information returned from database where \$_REQUEST[\"ship_to_info_id\"]==".@$vars["ship_to_info_id"]);

            // missing ship_to_info_id. probably a shop set up with no "choose a shipping address" step
            // let's choose the first ST address we can find
            $q="SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_id='". $_SESSION['auth']['user_id'] ."' AND address_type='ST' AND ( country=country_2_code OR country=country_3_code)";
            $dbu->query($q);
            if ($dbu->num_rows()==0) {
                // or default to BT address.
                $vmLogger->debug("Fedex::__construct() - Using first BT address found.");
                $q="SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_id='". $_SESSION['auth']['user_id'] ."' AND address_type='BT' AND ( country=country_2_code OR country=country_3_code)";
                $dbu->query($q);

                // ups module will fail if none of these queries return results.
            } else {
                $vmLogger->debug("Fedex::__construct() - Using first ST address found.");
            }
        }
        $dbu->next_record();
       
        // destination country
        $dbu->f("country_2_code");
        // destination state code
        // TODO: Make sure this works for Non-US countries
        $dbu->f('state');       
        //destination ZIP
        trim($dbu->f("zip"));       
        // Get a list of vendor data (including shipping address)
        $q  = "SELECT * FROM #__{vm}_vendor WHERE vendor_id='".$_SESSION['ps_vendor_id']."'";
        $dbv->query($q);
        $dbv->next_record();

        // source country
        $vendor_country_2_code;
       
       
        // source state code
        // TODO: Make sure this works for Non-US countries
        $dbv->f('vendor_state');
       
        // Source ZIP
       
         trim($dbv->f("vendor_zip"));

// Config
global $weight_total;
//echo $weight_total."<br>";
$formarweight=number_format($weight_total,2);
//echo $formarweight."<br>";
$arrayweight=explode('.',$formarweight);
//print_r($arrayweight)."<br>";
$extract_weight=$arrayweight[0].'.'.intval($arrayweight[1]);
//echo $extract_weight;
$config = array(
    // Services
    'services' => $services,
    // Weight
    'weight' =>$extract_weight, // Default = 1
    'weight_units' => 'lb', // lb (default), oz, gram, kg
    // Size
    //'size_length' => 0, // Default = 8
    //'size_width' => 6, // Default = 4
    //'size_height' => 3, // Default = 2
    //'size_units' => 'in', // in (default), feet, cm
    // From
    'from_zip' =>  trim($dbv->f("vendor_zip")),
    'from_state' =>$dbv->f('vendor_state'), // Only Required for FedEx
    'from_country' => $vendor_country_2_code,
    // To
    'to_zip' => trim($dbu->f("zip")),
    'to_state' =>$dbu->f('state'), // Only Required for FedEx
    'to_country' => $dbu->f("country_2_code"),
   
    // Service Logins
    'ups_access' => '0C2D05F55AF310D0', // UPS Access License Key
    'ups_user' => 'dwstudios', // UPS Username 
    'ups_pass' => 'dwstudios', // UPS Password 
    'ups_account' => '81476R', // UPS Account Number
    'usps_user' => '229DARKW7858', // USPS User Name
    'fedex_account' => '510087020', // FedEX Account Number
    'fedex_meter' => '100005263' // FedEx Meter Number
);

require_once(CLASSPATH ."shipping/fedex10/ShippingCalculator.php");
// Create Class (with config array)
$ship = new ShippingCalculator($config);
// Get Rates
$rates_array = $ship->calculate();



        foreach ($rates_array['fedex'] as $fedexservicename=>$fedexrate)
        {
            if($fedexrate!=""||$fedexrate!=NULL ||$fedexrate!=0)
            {
            $fedexservice_name[]=$services['fedex'][$fedexservicename];
            $fedexservice_name_key[]=$fedexservicename;
            $fedexservice_rate[] = $fedexrate;
            }
        }
       
    $cleancount=count($fedexservice_rate);
    if ($cleancount == 0)
        {
    echo '<img src="fedex.jpg" border="0"><br>';
            $vmLogger->notice("Fedex not provide the service your zip code.");
            return false;
        }
        else
        {
        $radioSelected = false;
        // iterate each service option and output information
        echo "<div style='margin-bottom:20px;'>";
          echo '<img src="fedex.jpg" border="0"><br>';
          for ($service_loop=0;$service_loop < $cleancount;$service_loop++)
            {       
            $html = "";           
            $current_service_display_name = str_replace('&lt;sup&gt;&amp;reg;&lt;/sup&gt;','',$fedexservice_name[$service_loop]);           
            $servicerate = $GLOBALS['CURRENCY']->convert( $fedexservice_rate[$service_loop], 'USD',$this->currency);
            $servicerateFormatted = $CURRENCY_DISPLAY->getFullValue($servicerate);
           
            $shipping_rate_id = urlencode("fedexv2|FEDEX|".html_entity_decode($current_service_display_name)."|".$servicerate);
           
            if (((urlencode(@$d["shipping_rate_id"])==$shipping_rate_id) || ($radioSelected==false))) {
                $checked = "checked=\"checked\"";
                $radioSelected = true;
            }else{
                $checked = "";
            }
            $html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" ".$checked." value=\"$shipping_rate_id\" />\n";
            $html .= html_entity_decode($current_service_display_name)." ";
            $html .= "<strong>(" . $servicerateFormatted . ")</strong>";           
            $html .= "<br />";
            // output the html
            echo $html;
            $_SESSION[$shipping_rate_id] = 1;
           
           }
           echo "</div>";
        }

//start ups shipping
  foreach ($rates_array['ups'] as $upsservicename=>$upsrate)
              {
                if($upsrate!=""||$upsrate!=NULL ||$upsrate!=0)
                {
                $upsservice_name[]=$services['ups'][$upsservicename];
                $upsservice_name_key[]=$upsservicename;
                $upsservice_rate[] = $upsrate;
                }
              }
             $cleancount=count($upsservice_rate);

             if ($cleancount == 0)
                {
                   echo    '<img src="ups_logo.jpg" border="0"><br>';
                   $vmLogger->notice("UPS not provide the service your zip code.");
                   return false;
                 }else
                 {
                     $radioSelected = false;
                   // iterate each service option and output information
                   echo "<div style='margin-bottom:20px;'>";
                   echo '<img src="ups_logo.jpg" border="0"><br>';
                   for ($service_loop=0;$service_loop < $cleancount;$service_loop++)
                   {
                        $html = "";           
                        $current_service_display_name = str_replace('&lt;sup&gt;&amp;reg;&lt;/sup&gt;','',$upsservice_name[$service_loop]);           
                        $servicerate = $GLOBALS['CURRENCY']->convert( $upsservice_rate[$service_loop], 'USD',$this->currency);
                        $servicerateFormatted = $CURRENCY_DISPLAY->getFullValue($servicerate);               
                        $shipping_rate_id = urlencode("ups|UPS|".html_entity_decode($current_service_display_name)."|".$servicerate);           
                    if (((urlencode(@$d["shipping_rate_id"])==$shipping_rate_id) || ($radioSelected==false)))
                       {
                         $checked = "checked=\"checked\"";
                         $radioSelected = true;
                       }else
                       {
                        $checked = "";
                       }
                        $html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" value=\"$shipping_rate_id\" />\n";
                        $html .= html_entity_decode($current_service_display_name)." ";
                        $html .= "<strong>(" . $servicerateFormatted . ")</strong>";               
                        $html .= "<br />";
                       // output the html
                        echo $html;
                        $_SESSION[$shipping_rate_id] = 1;
               
                     }
                                echo "</div>";
                   }


?>
---------------------------------------------End shipping class------------------------------------------
2 step-> create fedex10.ini under /administrator/components/com_virtuemart/classes/shipping

# $Id: fedex10.ini 617 2007-01-04 12:43:08 -0700 (Thu, 04 Jan 2012) soeren_nb $
[General]
name = FedEXdc
version = 10.02
creationDate = September 2005
author

= AJay
authorEmail = bikash@techwave.com
authorUrl = www.techwave.com.com/
copyright = (c) 2012 Vermonster LLC
license = GNU/GPL
description = The FedEX

Shipping module by bikash ranjan nayak.

[File]
filename = fedex10.php
-------------------------------------------End ini file-------------------------------------------------------

step 3-> create to ShippingCalculator.php under administrator/components/com_virtuemart/classes/shipping/fedex10
---------------------------------------------------------------------------------------------------
<?php
class ShippingCalculator  {
    // Defaults
    var $weight = 1;
    var $weight_unit = "lb";
    var $size_length = 4;
    var $size_width = 8;
    var $size_height = 2;
    var $size_unit = "in";
    var $debug = false; // Change to true to see XML sent and recieved
   
    // Batch (get all rates in one go, saves lots of time)
    var $batch_ups = false; // Currently Unavailable
    var $batch_usps = true;
    var $batch_fedex = false; // Currently Unavailable
   
    // Config (you can either set these here or send them in a config array when creating an instance of the class)
    var $services;
    var $from_zip;
    var $from_state;
    var $from_country;
    var $to_zip;
    var $to_stat;
    var $to_country;
    var $ups_access;
    var $ups_user;
    var $ups_pass;
    var $ups_account;
    var $usps_user;
    var $fedex_account;
    var $fedex_meter;
   
    // Results
    var $rates;
   
    // Setup Class with Config Options
    function ShippingCalculator($config) {
        if($config) {
            foreach($config as $k => $v) $this->$k = $v;
        }
    }
   
    // Calculate
    function calculate($company = NULL,$code = NULL) {
        $this->rates = NULL;
        $services = $this->services;
        if($company and $code) $services[$company][$code] = 1;
        foreach($services as $company => $codes) {
            foreach($codes as $code => $name) {
                switch($company) {
                    case "ups":
                        /*if($this->batch_ups == true) $batch[] = $code; // Batch calculation currently unavaiable
                        else*/ $this->rates[$company][$code] = $this->calculate_ups($code);
                        break;
                    case "usps":
                        if($this->batch_usps == true) $batch[] = $code;
                        else $this->rates[$company][$code] = $this->calculate_usps($code);
                        break;
                    case "fedex":
                        /*if($this->batch_fedex == true) $batch[] = $code; // Batch calculation currently unavaiable
                        else*/ $this->rates[$company][$code] = $this->calculate_fedex($code);
                        break;
                }
            }
            // Batch Rates
            //if($company == "ups" and $this->batch_ups == true and count($batch) > 0) $this->rates[$company] = $this->calculate_ups($batch);
            if($company == "usps" and $this->batch_usps == true and count($batch) > 0) $this->rates[$company] = $this->calculate_usps($batch);
            //if($company == "fedex" and $this->batch_fedex == true and count($batch) > 0) $this->rates[$company] = $this->calculate_fedex($batch);
        }
       
        return $this->rates;
    }
   
    // Calculate UPS
    function calculate_ups($code) {
        $url = "https://www.ups.com/ups.app/xml/Rate";
        $data = '<?xml version="1.0"?> 
<AccessRequest xml:lang="en-US"> 
    <AccessLicenseNumber>'.$this->ups_access.'</AccessLicenseNumber> 
    <UserId>'.$this->ups_user.'</UserId> 
    <Password>'.$this->ups_pass.'</Password> 
</AccessRequest> 
<?xml version="1.0"?> 
<RatingServiceSelectionRequest xml:lang="en-US"> 
    <Request> 
        <TransactionReference> 
            <CustomerContext>Bare Bones Rate Request</CustomerContext> 
            <XpciVersion>1.0001</XpciVersion> 
        </TransactionReference> 
        <RequestAction>Rate</RequestAction> 
        <RequestOption>Rate</RequestOption> 
    </Request> 
    <PickupType> 
        <Code>01</Code> 
    </PickupType> 
    <Shipment> 
        <Shipper> 
            <Address> 
                <PostalCode>'.$this->from_zip.'</PostalCode> 
                <CountryCode>'.$this->from_country.'</CountryCode> 
            </Address> 
        <ShipperNumber>'.$this->ups_account.'</ShipperNumber> 
        </Shipper> 
        <ShipTo> 
            <Address> 
                <PostalCode>'.$this->to_zip.'</PostalCode> 
                <CountryCode>'.$this->to_country.'</CountryCode> 
            <ResidentialAddressIndicator/> 
            </Address> 
        </ShipTo> 
        <ShipFrom> 
            <Address> 
                <PostalCode>'.$this->from_zip.'</PostalCode> 
                <CountryCode>'.$this->from_country.'</CountryCode> 
            </Address> 
        </ShipFrom> 
        <Service> 
            <Code>'.$code.'</Code> 
        </Service> 
        <Package> 
            <PackagingType> 
                <Code>02</Code> 
            </PackagingType> 
            <Dimensions> 
                <UnitOfMeasurement> 
                    <Code>IN</Code> 
                </UnitOfMeasurement> 
                <Length>'.($this->size_unit != "in" ? $this->convert_sze($this->size_length,$this->size_unit,"in") : $this->size_length).'</Length> 
                <Width>'.($this->size_unit != "in" ? $this->convert_sze($this->size_width,$this->size_unit,"in") : $this->size_width).'</Width> 
                <Height>'.($this->size_unit != "in" ? $this->convert_sze($this->size_height,$this->size_unit,"in") : $this->size_height).'</Height> 
            </Dimensions> 
            <PackageWeight> 
                <UnitOfMeasurement> 
                    <Code>LBS</Code> 
                </UnitOfMeasurement> 
                <Weight>'.($this->weight_unit != "lb" ? $this->convert_weight($this->weight,$this->weight_unit,"lb") : $this->weight).'</Weight> 
            </PackageWeight> 
        </Package> 
    </Shipment> 
</RatingServiceSelectionRequest>';
       
        // Curl
        $results = $this->curl($url,$data);
       
        // Debug
        if($this->debug == true) {
            print "<xmp>".$data."</xmp><br />";
            print "<xmp>".$results."</xmp><br />";
        }
       
        // Match Rate
        preg_match('/<MonetaryValue>(.*?)<\/MonetaryValue>/',$results,$rate);
       
        return $rate[1];
    }
   
    // Calculate USPS
    function calculate_usps($code) {
        // Weight (in lbs)
        if($this->weight_unit != 'lb') $weight = $this->convert_weight($weight,$this->weight_unit,'lb');
        else $weight = $this->weight;
        // Split into Lbs and Ozs
        $lbs = floor($weight);
        $ozs = ($weight - $lbs)  * 16;
        if($lbs == 0 and $ozs < 1) $ozs = 1;
        // Code(s)
        $array = true;
        if(!is_array($code)) {
            $array = false;
            $code = array($code);
        }
       
        $url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
        $data = 'API=RateV2&XML=<RateV2Request USERID="'.$this->usps_user.'">';
        foreach($code as $x => $c) $data .= '<Package ID="'.$x.'"><Service>'.$c.'</Service><ZipOrigination>'.$this->from_zip.'</ZipOrigination><ZipDestination>'.$this->to_zip.'</ZipDestination><Pounds>'.$lbs.'</Pounds><Ounces>'.$ozs.'</Ounces><Size>REGULAR</Size><Machinable>TRUE</Machinable></Package>';
        $data .= '</RateV2Request>';
       
        // Curl
        $results = $this->curl($url,$data);
       
        // Debug
        if($this->debug == true) {
            print "<xmp>".$data."</xmp><br />";
            print "<xmp>".$results."</xmp><br />";
        }
       
        // Match Rate(s)
        preg_match_all('/<Package ID="([0-9]{1,3})">(.+?)<\/Package>/',$results,$packages);
        foreach($packages[1] as $x => $package) {
            preg_match('/<Rate>(.+?)<\/Rate>/',$packages[2][$x],$rate);
            $rates[$code[$package]] = $rate[1];
        }
        if($array == true) return $rates;
        else return $rate[1];
    }
   
    // Calculate FedEX
    function calculate_fedex($code) {
        $url = "https://gatewaybeta.fedex.com/GatewayDC";
        $data = '<?xml version="1.0" encoding="UTF-8" ?>
<FDXRateRequest xmlns:api="http://www.fedex.com/fsmapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FDXRateRequest.xsd">
    <RequestHeader>
        <CustomerTransactionIdentifier>Express Rate</CustomerTransactionIdentifier>
        <AccountNumber>'.$this->fedex_account.'</AccountNumber>
        <MeterNumber>'.$this->fedex_meter.'</MeterNumber>
        <CarrierCode>'.(in_array($code,array('FEDEXGROUND','GROUNDHOMEDELIVERY')) ? 'FDXG' : 'FDXE').'</CarrierCode>
    </RequestHeader>
    <DropoffType>REGULARPICKUP</DropoffType>
    <Service>'.$code.'</Service>
    <Packaging>YOURPACKAGING</Packaging>
    <WeightUnits>LBS</WeightUnits>
    <Weight>'.number_format(($this->weight_unit != 'lb' ? convert_weight($this->weight,$this->weight_unit,'lb') : $this->weight), 1, '.', '').'</Weight>
    <OriginAddress>
        <StateOrProvinceCode>'.$this->from_state.'</StateOrProvinceCode>
        <PostalCode>'.$this->from_zip.'</PostalCode>
        <CountryCode>'.$this->from_country.'</CountryCode>
    </OriginAddress>
    <DestinationAddress>
        <StateOrProvinceCode>'.$this->to_state.'</StateOrProvinceCode>
        <PostalCode>'.$this->to_zip.'</PostalCode>
        <CountryCode>'.$this->to_country.'</CountryCode>
    </DestinationAddress>
    <Payment>
        <PayorType>SENDER</PayorType>
    </Payment>
    <PackageCount>1</PackageCount>
</FDXRateRequest>';
       
        // Curl
        $results = $this->curl($url,$data);
       
        // Debug
        if($this->debug == true) {
            print "<xmp>".$data."</xmp><br />";
            print "<xmp>".$results."</xmp><br />";
        }
   
        // Match Rate
        preg_match('/<NetCharge>(.*?)<\/NetCharge>/',$results,$rate);
       
        return $rate[1];
    }
   
    // Curl
    function curl($url,$data = NULL) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        if($data) {
            curl_setopt($ch, CURLOPT_POST,1); 
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        } 
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        $contents = curl_exec ($ch);
       
        return $contents;
       
        curl_close ($ch);
    }
   
    // Convert Weight
    function convert_weight($weight,$old_unit,$new_unit) {
        $units['oz'] = 1;
        $units['lb'] = 0.0625;
        $units['gram'] = 28.3495231;
        $units['kg'] = 0.0283495231;
       
        // Convert to Ounces (if not already)
        if($old_unit != "oz") $weight = $weight / $units[$old_unit];
       
        // Convert to New Unit
        $weight = $weight * $units[$new_unit];
       
        // Minimum Weight
        if($weight < .1) $weight = .1;
       
        // Return New Weight
        return round($weight,2);
    }
   
    // Convert Size
    function convert_size($size,$old_unit,$new_unit) {
        $units['in'] = 1;
        $units['cm'] = 2.54;
        $units['feet'] = 0.083333;
       
        // Convert to Inches (if not already)
        if($old_unit != "in") $size = $size / $units[$old_unit];
       
        // Convert to New Unit
        $size = $size * $units[$new_unit];
       
        // Minimum Size
        if($size < .1) $size = .1;
       
        // Return New Size
        return round($size,2);
    }
   
    // Set Value
    function set_value($k,$v) {
        $this->$k = $v;
    }

?>
--------------------------------end---------------------------------------------------
i hope enjoy and save the time
-------------------------------------------------------------
if you helpful my code please donate some few amount to
developing and free to post.
-------------------------------------------------------------

Comments

Popular posts from this blog

php format date string short month

curl service example in php