Class: McFedex::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/mc-fedex.rb

Constant Summary collapse

REQUIRED_OPTIONS =

Defines the required parameters for various methods

{
  :base        => [ :auth_key, :security_code, :account_number, :meter_number ],
  :price       => [ :shipper, :recipient, :weight ],
  :label       => [ :shipper, :recipient, :weight, :service_type ],
  :contact     => [ :name, :phone_number ],
  :address     => [ :country, :street, :city, :state, :zip ],
  :ship_cancel => [ :tracking_number ]
}
WSDL_PATHS =

Defines the relative path to the WSDL files. Defaults assume lib/wsdl under plugin directory.

{
  :ship => @wsdl_path,
}
WS_VERSION =

Defines the Web Services version implemented.

{ :Major => 9, :Intermediate => 0, :Minor => 0, :ServiceId => 'ship' }
SUCCESSFUL_RESPONSES =

:nodoc:

['SUCCESS', 'WARNING', 'NOTE']

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Base

Initializes the Fedex::Base class, setting defaults where necessary.

fedex = Fedex::Base.new(options = {})

Example:

fedex = Fedex::Base.new(:auth_key       => AUTH_KEY,
                        :security_code  => SECURITY_CODE
                        :account_number => ACCOUNT_NUMBER,
                        :meter_number   => METER_NUMBER)

Required options for new

:auth_key       - Your Fedex Authorization Key
:security_code  - Your Fedex Security Code
:account_number - Your Fedex Account Number
:meter_number   - Your Fedex Meter Number

Additional options

:dropoff_type       - One of Fedex::DropoffTypes.  Defaults to DropoffTypes::REGULAR_PICKUP
:packaging_type     - One of Fedex::PackagingTypes.  Defaults to PackagingTypes::YOUR_PACKAGING
:label_type         - One of Fedex::LabelFormatTypes.  Defaults to LabelFormatTypes::COMMON2D.  You'll only need to change this
                      if you're generating completely custom labels with a format of your own design.  If printing to Fedex stock
                      leave this alone.
:label_image_type   - One of Fedex::LabelSpecificationImageTypes.  Defaults to LabelSpecificationImageTypes::PDF.
:rate_request_type  - One of Fedex::RateRequestTypes.  Defaults to RateRequestTypes::ACCOUNT
:payment            - One of Fedex::PaymentTypes.  Defaults to PaymentTypes::SENDER
:units              - One of Fedex::WeightUnits.  Defaults to WeightUnits::LB
:currency           - One of Fedex::CurrencyTypes.  Defaults to CurrencyTypes::USD
:debug              - Enable or disable debug (wiredump) output.  Defaults to false.


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/mc-fedex.rb', line 60

def initialize(options = {})
  check_required_options(:base, options)

  @auth_key           = options[:auth_key]
  @security_code      = options[:security_code]
  @account_number     = options[:account_number]
  @meter_number       = options[:meter_number]

  @wsdl_path          = options[:wsdl_path]
  @use_smart_post     = options[:use_smart_post]
  @smart_post_hub     = options[:smart_post_hub]

  @dropoff_type       = options[:dropoff_type]      || DropoffTypes::REGULAR_PICKUP
  @packaging_type     = options[:packaging_type]    || PackagingTypes::YOUR_PACKAGING
  @label_type         = options[:label_type]        || LabelFormatTypes::COMMON2D
  @label_image_type   = options[:label_image_type]  || LabelSpecificationImageTypes::PDF
  @rate_request_type  = options[:rate_request_type] || RateRequestTypes::LIST
  @payment_type       = options[:payment]           || PaymentTypes::SENDER
  @units              = options[:units]             || WeightUnits::LB
  @currency           = options[:currency]          || 'USD'
  @debug              = options[:debug]             || false
end

Instance Method Details

#label(options = {}) ⇒ Object

Generate a new shipment and return associated data, including price, tracking number, and the label itself.

fedex = Fedex::Base.new(options)
price, label, tracking_number = fedex.label(fields)

Returns the actual price for the label, the Base64-decoded label in the format specified in Fedex::Base, and the tracking_number for the shipment.

Required options for label

:shipper      - A hash containing contact information and an address for the shipper.  (See below.)
:recipient    - A hash containing contact information and an address for the recipient.  (See below.)
:weight       - The total weight of the shipped package.
:service_type - One of Fedex::ServiceTypes

Address format

The ‘shipper’ and ‘recipient’ address values should be hashes. Like this:

shipper = {:contact => {:name => 'John Doe',
                        :phone_number => '4805551212'},
           :address => address} # See "Address" for under price.


103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/mc-fedex.rb', line 103

def label(options = {})
  puts options.inspect if @debug
  # Check overall options
  check_required_options(:label, options)

  # Check Address Options
  check_required_options(:contact, options[:shipper][:contact])
  check_required_options(:address, options[:shipper][:address])

  # Check Contact Options
  check_required_options(:contact, options[:recipient][:contact])
  check_required_options(:address, options[:recipient][:address])

  # Prepare variables
  shipper             = options[:shipper]
  recipient           = options[:recipient]

  shipper_contact     = shipper[:contact]
  shipper_address     = shipper[:address]

  recipient_contact   = recipient[:contact]
  recipient_address   = recipient[:address]

  service_type        = options[:service_type]
  count               = options[:count] || 1
  weight              = options[:weight]
  rma                 = options[:rma] || ""
  tracking_number     = options[:tracking_number] || 0

  time                = options[:time] || Time.now
  puts time.class
  time                = time.iso8601 if time.is_a?(Time)

  residential         = !!recipient_address[:residential]

  service_type        = resolve_service_type(service_type, residential)

  # Create the driver
  driver = create_driver(:ship)

  smart_post_data = {
    :SmartPostDetail          => {
        :Indicia => "PARCEL_RETURN",
        :HubId   => @smart_post_hub
    },
     :SpecialServicesRequested => {
         :SpecialServiceTypes  => "RETURN_SHIPMENT",
         :ReturnShipmentDetail => {
             :ReturnType => "PRINT_RETURN_LABEL",
             :Rma => {
                        :Number => rma
                    }
         }
     }
  } if @use_smart_post

  result = driver.processShipment(common_options.merge(
    :RequestedShipment => {
      :ShipTimestamp => time,
      :DropoffType => @dropoff_type,
      :ServiceType => service_type,
      :PackagingType => @packaging_type,
      :TotalWeight => { :Units => @units, :Value => weight },
      :PreferredCurrency => @currency,
      :Shipper => {
        :Contact => {
          :PersonName => shipper_contact[:name],
          :PhoneNumber => shipper_contact[:phone_number]
        },
        :Address => {
          :CountryCode => shipper_address[:country],
          :StreetLines => shipper_address[:street],
          :City => shipper_address[:city],
          :StateOrProvinceCode => shipper_address[:state],
          :PostalCode => shipper_address[:zip]
        }
      },
      :Recipient => {
        :Contact => {
          :PersonName => recipient_contact[:name],
          :PhoneNumber => recipient_contact[:phone_number]
        },
        :Address => {
          :CountryCode => recipient_address[:country],
          :StreetLines => recipient_address[:street],
          :City => recipient_address[:city],
          :StateOrProvinceCode => recipient_address[:state],
          :PostalCode => recipient_address[:zip],
          :Residential => residential
        }
      },
      :ShippingChargesPayment => {
        :PaymentType => @payment_type,
        :Payor => {
          :AccountNumber => @account_number,
          :CountryCode => shipper_address[:country]
        }
      },
      :LabelSpecification => {
        :LabelFormatType => @label_type,
        :ImageType => @label_image_type
      },
      :RateRequestTypes => @rate_request_type,
      :PackageCount => count,
      :RequestedPackageLineItems => [ {:SequenceNumber=>1, :Weight => {:Units => @units, :Value => weight} } ]
    }.merge(smart_post_data || {})
  ))

  successful = successful?(result)

  msg = error_msg(result, false)
  if successful && msg !~ /There are no valid services available/
    if @use_smart_post
      charge = 0
      # trackingIds[0] - this is the 22 digit tracking number, trackingIds[1] is the shorter tracking number
      tracking_number = result.completedShipmentDetail.completedPackageDetails.trackingIds[tracking_number].trackingNumber
    else
      pre = result.completedShipmentDetail.shipmentRating.shipmentRateDetails
      charge = ((pre.class == Array ? pre[0].totalNetCharge.amount.to_f : pre.totalNetCharge.amount.to_f) * 100).to_i
      tracking_number = result.completedShipmentDetail.completedPackageDetails.trackingIds.trackingNumber
    end
    label = Base64.decode64(result.completedShipmentDetail.completedPackageDetails.label.parts.image)
    [charge, label, tracking_number]
  else
    raise FedexError.new("Unable to get label from Fedex: #{msg}")
  end
end