Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 15 revisions

[h3]V1 - October 18, 2009[/h3]

The following library can be used to get shipping rates from UPS (United Parcel Service). You will need an account with UPS to get a developer's account and access key. Put your access key and account username/password into the configuration at the top of the class. The output is an array of services/prices from your zip code to the destination.

Blessings, Brian Gottier [url=http://brianswebdesign.com]Brian's Web Design - Temecula, CA[/url]

[b]Features[/b]

  1. Request a single service rate, or leave empty to "shop" for rates.
  2. Uses cURL to make the request
  3. Uses php5's simpleXML format

[b]Tested Environment[/b]

  1. [b]CodeIgniter 1.7.2[/b]
  2. PHP versions greater than 5.2.0

[code] <?php class United_parcel_service { // ========== CHANGE THESE VALUES TO MATCH YOUR OWN ===========

private $access_key =                'your-access-key';        // Your UPS Online Tools Access Key
private $ups_account_username =     'your-username';                // Your UPS Account Username
private $ups_account_password =     'your-password';            // Your UPS Account Password
private $zip_code =                 '60504';                // Zipcode you are shipping FROM
private $ups_account_number =         'your-account-number';                // Your UPS Account Number

// ============================================================

public function get_rate( $destination_zip , $service_type , $weight , $length , $width , $height , $insured_value )
{
    if($service_type == '')
    {
        $request_option = 'Shop';
    }
    else
    {
        $request_option = 'Rate';
    }
    $data ="&lt;?xml version=\"1.0\"?&gt;
                <AccessRequest xml:lang=\"en-US\">
                    <AccessLicenseNumber>" . $this->access_key . "</AccessLicenseNumber>
                    <UserId>" . $this->ups_account_username . "</UserId>
                    <Password>" . $this->ups_account_password . "</Password>
                </AccessRequest>
                &lt;?xml version=\"1.0\"?&gt;
                <RatingServiceSelectionRequest xml:lang=\"en-US\">
                    <Request>
                        <TransactionReference>
                            <CustomerContext>Rate Request From " . $_SERVER['HTTP_HOST'] . "</CustomerContext>
                            <XpciVersion>1.0001</XpciVersion>
                        </TransactionReference>
                        <RequestAction>Rate</RequestAction>
                        <RequestOption>$request_option</RequestOption>
                    </Request>
                    <PickupType>
                        <Code>01</Code>
                    </PickupType>
                    <Shipment>
                        <Shipper>
                            <Address>
                                <PostalCode>" . $this->zip_code . "</PostalCode>
                                <CountryCode>US</CountryCode>
                            </Address>
                            <ShipperNumber>" . $this->ups_account_number . "</ShipperNumber>
                        </Shipper>
                        <ShipTo>
                            <Address>
                                <PostalCode>$destination_zip</PostalCode>
                                <CountryCode>US</CountryCode>
                                <ResidentialAddressIndicator/>
                            </Address>
                        </ShipTo>
                        <ShipFrom>
                            <Address>
                                <PostalCode>" . $this->zip_code . "</PostalCode>
                                <CountryCode>US</CountryCode>
                            </Address>
                        </ShipFrom>
                        <Service>
                            <Code>$service_type</Code>
                        </Service>
                        <Package>
                            <PackagingType>
                                <Code>02</Code>
                            </PackagingType>
                            <Dimensions>
                                <UnitOfMeasurement>
                                    <Code>IN</Code>
                                </UnitOfMeasurement>
                                <Length>$length</Length>
                                <Width>$width</Width>
                                <Height>$height</Height>
                            </Dimensions>
                            <PackageWeight>
                                <UnitOfMeasurement>
                                    <Code>LBS</Code>
                                </UnitOfMeasurement>
                                <Weight>$weight</Weight>
                            </PackageWeight>
                            <PackageServiceOptions>
                            <InsuredValue>
                                <CurrencyCode>USD</CurrencyCode>
                                <MonetaryValue>$insured_value</MonetaryValue>
                            </InsuredValue>
                        </PackageServiceOptions>
                        </Package>
                    </Shipment>
                </RatingServiceSelectionRequest>";

    $ch = curl_init("https://www.ups.com/ups.app/xml/Rate");
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch,CURLOPT_POST,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);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    $result=curl_exec &#40;$ch&#41;;

    //echo '&lt;!-- '. $result. ' --&gt;'; // uncomment to debug

    $data = strstr($result, '&lt;?');
    $shipping_types = array(
        '01' => 'UPS Next Day Air',
        '02' => 'UPS Second Day Air',
        '03' => 'UPS Ground',
        '07' => 'UPS Worldwide Express',
        '08' => 'UPS Worldwide Expedited',
        '11' => 'UPS Standard',
        '12' => 'UPS Three-Day Select',
        '13' => 'Next Day Air Saver',
        '14' => 'UPS Next Day Air Early AM',
        '54' => 'UPS Worldwide Express Plus',
        '59' => 'UPS Second Day Air AM',
        '65' => 'UPS Saver'
        );
    $xml = new SimpleXMLElement($data);
    if($xml->Response->ResponseStatusCode == '1')
    {
        foreach($xml->RatedShipment as $shipping_choice)
        {
            $k = $shipping_types[(string) $shipping_choice->Service->Code];
            $shipping_choices[$k] = (string) $shipping_choice->TotalCharges->MonetaryValue;
        }
        return $shipping_choices;
    }
    else
    {
        return FALSE;
    }
}

} [/code]

[b]Usage[/b]

[code] <?php // parameters are in order // 1. Zip code shipping TO // 2. A UPS service #, or leave empty for shop mode // 3. The weight in US pounds // 4. The length of the package in inches // 5. The width of the package in inches // 6. The height of the package in inches // 7. The insured value of the package in US dollars $this->load->library('United_parcel_service'); $this->united_parcel_service->get_rate(60504,'',1,6,6,6,99); [/code]

[h3]V2 - December 23, 2009[/h3] Added some features like multiple packages, commercial addresses, ship date (to get arrival date), etc. Enjoy, Dan Frist twitter.com/danfrist

[code] <?php /*

EXAMPLE USE: // parameters are in order // 1. Zip code shipping TO // 2. A UPS service #, or leave empty for shop mode // 3. Number of packages // 4. Total weight of all packages in US pounds // 5. Ship date (unix or string) // 6. Residential (boolean)

$this->load->library('United_parcel_service'); $resultArr = $this->united_parcel_service->get_rate(60504,'',1,2,'12/25/09',true);

*/ class United_parcel_service { // ========== CHANGE THESE VALUES TO MATCH YOUR OWN =========== private $access_key='your-access-key';// Your UPS Online Tools Access Key private $ups_account_username='your-username';// Your UPS Account Username private $ups_account_password='your-password';// Your UPS Account Password private $zip_code='29615';// Zipcode you are shipping FROM private $ups_account_number='your-account-number';// Your UPS Account Number // ============================================================ public function get_rate($destination_zip, $service_type, $number_of_packages, $weight, $ship_date, $residential) { $request_option = 'Rate'; if ($service_type == '') { $request_option = 'Shop'; }

    if (is_numeric($ship_date))
    {
        $shipDate = date('Y-m-d', $ship_date);
    }
    else
    {
        $shipDate = date('Y-m-d', strtotime($ship_date));
    }

    $resStr = "";
    if ($residential)
    {
        $resStr = "<ResidentialAddressIndicator/>";
    }
    
    if ($number_of_packages > 1)
    {
        $indPackWeight = $weight / $number_of_packages;
        $i = 0;
        $packageCode = '';
        do {
            $packageCode .= "
                <Package>
                    <PackagingType><Code>02</Code></PackagingType>
                    <PackageWeight>
                        <UnitOfMeasurement><Code>LBS</Code></UnitOfMeasurement>
                        <Weight>$indPackWeight</Weight>
                    </PackageWeight>
                </Package>
            ";
            $i++;
        }while($i < $number_of_packages);
    }
    else
    {
        $packageCode = "
            <Package>
                <PackagingType><Code>02</Code></PackagingType>
                <PackageWeight>
                    <UnitOfMeasurement><Code>LBS</Code></UnitOfMeasurement>
                    <Weight>".$weight."</Weight>
                </PackageWeight>
            </Package>
        ";
    }

    $data ="
        &lt;?xml version=\"1.0\"?&gt;
        <AccessRequest xml:lang=\"en-US\">
            <AccessLicenseNumber>" . $this->access_key . "</AccessLicenseNumber>
            <UserId>" . $this->ups_account_username . "</UserId>
            <Password>" . $this->ups_account_password . "</Password>
        </AccessRequest>
        &lt;?xml version=\"1.0\"?&gt;
        <RatingServiceSelectionRequest xml:lang=\"en-US\">
            <Request>
                <TransactionReference>
                    <CustomerContext>Rate Request From " . $_SERVER['HTTP_HOST'] . "</CustomerContext>
                    <XpciVersion>1.0001</XpciVersion>
                </TransactionReference>
                <RequestAction>Rate</RequestAction>
                <RequestOption>$request_option</RequestOption>
            </Request>
            <PickupType> <Code>01</Code> </PickupType>
            <Shipment>
                <Shipper>
                    <Address>
                        <PostalCode>" . $this->zip_code . "</PostalCode>
                        <CountryCode>US</CountryCode>
                    </Address>
                    <ShipperNumber>" . $this->ups_account_number . "</ShipperNumber>
                </Shipper>
                <ShipTo>
                    <Address>
                    <PostalCode>$destination_zip</PostalCode>
                    <CountryCode>US</CountryCode>
                    $resStr
                    </Address>
                </ShipTo>
                <ShipFrom>
                    <Address>
                    <PostalCode>" . $this->zip_code . "</PostalCode>
                    <CountryCode>US</CountryCode>
                    </Address>
                </ShipFrom>
                <Service>
                    <Code>$service_type</Code>
                </Service>
                <ShipmentServiceOptions>
                    <OnCallAir>
                        <Schedule>
                            <PickupDay>$shipDate</PickupDay>
                        </Schedule>
                    </OnCallAir>
                </ShipmentServiceOptions>
                $packageCode
                <RateInformation>
                    <NegotiatedRatesIndicator/>
                </RateInformation>
            </Shipment>
        </RatingServiceSelectionRequest>
    ";
    
    $ch = curl_init("https://www.ups.com/ups.app/xml/Rate");
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_POST, 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);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result=curl_exec&#40;$ch&#41;;
    //echo '&lt;!-- '. $result. ' --&gt;'; // uncomment to debug
    $data = strstr($result, '&lt;?');
    $shipping_types = array(
        '01' => 'UPS Next Day Air',
        '02' => 'UPS Second Day Air',
        '03' => 'UPS Ground',
        '07' => 'UPS Worldwide Express',
        '08' => 'UPS Worldwide Expedited',
        '11' => 'UPS Standard',
        '12' => 'UPS Three-Day Select',
        '13' => 'Next Day Air Saver',
        '14' => 'UPS Next Day Air Early AM',
        '54' => 'UPS Worldwide Express Plus',
        '59' => 'UPS Second Day Air AM',
        '65' => 'UPS Saver'
    );
    $xml = new SimpleXMLElement($data);
    if ($xml->Response->ResponseStatusCode == '1')
    {
        foreach ($xml->RatedShipment as $shipping_choice)
        {
            $k = $shipping_types[(string) $shipping_choice->Service->Code];
            $shipping_choices[$k] = (string) $shipping_choice->TotalCharges->MonetaryValue;
        }
        return $shipping_choices;
    }
    else
    {
        return FALSE;
    }
}

} [/code]

[h3]Wiki Categories[/h3]

Category:Libraries::Shipping Category:Contributions::Libraries::Shipping

Clone this wiki locally