-
Notifications
You must be signed in to change notification settings - Fork 0
/
uc_fedex.module
1620 lines (1461 loc) · 59.6 KB
/
uc_fedex.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* FedEx Web Services Rate / Available Services Quote.
*
* Shipping quote module that interfaces with the FedEx Web Services API
* to get rates for small package shipments. Implements a SOAP Web Service
* client.
*
* @author Tim Rohaly. <http://drupal.org/user/202830>
*/
// Maximum shipping weight for FedEx (non-Freight services).
// 150lbs.
define('PACKAGE_WEIGHT_LIMIT_LBS', 150.0);
// Maximum shipping length for FedEx (non-Freight services).
// 108in.
define('PACKAGE_LENGTH_LIMIT_IN', 108);
// PACKAGE Max Height and Width is not accounted for here.
// Maximum package girth for FedEx (non-Freight services).
// 165in
define('PACKAGE_GIRTH_LIMIT_IN', 165);
// Maximum shipping weight for FedEx (Freight services).
// 2,200lbs.
define('SKID_WEIGHT_LIMIT_LBS', 2200.0);
// Maximum shipping length for FedEx (Freight services).
// 288in = 24ft.
define('SKID_LENGTH_LIMIT_IN', 288);
// Maximum shipping length for FedEx (non-Freight services).
// 106in.
define('SKID_HEIGHT_LIMIT_IN', 106);
// Maximum shipping width for FedEx (Freight services).
// 93in.
define('SKID_WIDTH_LIMIT_IN', 93);
// Freight EXTREME_LENGTH value.
define('EXTREME_LENGTH_VALUE', variable_get('uc_fedex_freight_extreme_length'));
define('EXTREME_LENGTH_VALUE_UNITS', variable_get('uc_fedex_freight_extreme_length_units'));
// Minimum shipment length that enables Freight Quote request and display.
define('FREIGHT_MIN_LENGTH_VALUE', variable_get('uc_fedex_freight_min_length'));
define('FREIGHT_MIN_LENGTH_VALUE_UNITS', variable_get('uc_fedex_freight_min_length_units'));
// Freight MIN_PKG_NUM value - defines when to display Freight quotes
// based on number of packages.
define('FREIGHT_MIN_PKG_NUM', variable_get('uc_fedex_freight_min_pkg_num'));
// FedEx Freight Account Number.
define('FREIGHT_ACCOUNT_NUMBER', variable_get('uc_fedex_freight_account_number', 0));
// Server Role.
define('SERVER_ROLE', variable_get('uc_fedex_server_role'));
$length_conversion_factor = _uc_length_conversion_multiplier();
define('LENGTH_CONV_FACTOR', $length_conversion_factor);
// Set to 0 to disable caching of SOAP WSDL when developing your WSDL.
ini_set("soap.wsdl_cache_enabled", "0");
/******************************************************************************
* Drupal Hooks *
******************************************************************************/
/**
* Implements hook_menu().
*/
function uc_fedex_menu() {
$items = array();
$items['admin/store/settings/quotes/fedex'] = array(
'title' => 'FedEx',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_fedex_admin_settings'),
'access arguments' => array('configure quotes'),
'type' => MENU_LOCAL_TASK,
'file' => 'uc_fedex.admin.inc',
'weight' => 10,
);
$items['admin/store/orders/%uc_order/shipments/fedex'] = array(
'title' => 'FedEx shipment',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_fedex_confirm_shipment', 3),
'access arguments' => array('fulfill orders'),
'type' => MENU_CALLBACK,
'file' => 'uc_fedex.ship.inc',
);
$items['admin/store/orders/%uc_order/shipments/labels/fedex'] = array(
'page callback' => 'uc_fedex_label_image',
'access arguments' => array('fulfill orders'),
'type' => MENU_CALLBACK,
'file' => 'uc_fedex.ship.inc',
);
return $items;
}
/**
* Implements hook_init().
*/
function uc_fedex_init() {
// Can we conditionally load the address validation code based on
// variable_get('uc_fedex_address_validation', FALSE).
// Address Validation routines.
module_load_include('inc', 'uc_fedex', 'uc_fedex.aval');
}
/**
* Implements hook_cron().
*
* Deletes FedEx shipping labels from the file system automatically
* on a periodic basis. Cron must be enabled for automatic deletion.
* Default lifetime is 1 week (604800 seconds).
*/
function uc_fedex_cron() {
$cutoff = REQUEST_TIME - variable_get('uc_fedex_label_lifetime', 604800);
if ($cutoff == REQUEST_TIME) {
// Label lifetime is set to 0, meaning never delete.
return;
}
// Loop over label files in public://fedex_labels and test
// creation date against 'uc_fedex_label_lifetime'.
$files = file_scan_directory('public://fedex_labels', '/^label-/');
foreach ($files as $file) {
if ($cutoff > filectime($file->uri)) {
drupal_unlink($file->uri);
watchdog('uc_fedex', 'Removed uc_fedex label file @file.', array('@file' => $file->uri), WATCHDOG_NOTICE);
}
}
}
/**
* Implements hook_theme().
*/
function uc_fedex_theme() {
return array(
'uc_fedex_option_label' => array(
'file' => 'uc_fedex.module',
'variables' => array(
'service' => NULL,
'packages' => NULL,
'skids' => NULL,
),
),
'uc_fedex_confirm_shipment' => array(
'render element' => 'form',
'file' => 'uc_fedex.ship.inc',
),
);
}
/******************************************************************************
* Ubercart Hooks *
******************************************************************************/
/**
* Implements Ubercart's hook_uc_shipping_type().
*
* @return array
* Array of package types for FedEx shipping method.
*/
function uc_fedex_uc_shipping_type() {
$weight = variable_get('uc_quote_type_weight', array('small_package' => 0));
$types = array(
'small_package' => array(
'id' => 'small_package',
'title' => t('Small Package'),
'weight' => $weight['small_package'],
),
);
return $types;
}
/**
* Implements Ubercart's hook_uc_shipping_method().
*
* @return array
* Array of FedEx shipping services.
*/
function uc_fedex_uc_shipping_method() {
$enabled = variable_get('uc_quote_enabled', array()) + array(
'fedex_ground' => FALSE,
'fedex' => FALSE,
'fedex_freight' => FALSE,
);
$weight = variable_get('uc_quote_method_weight', array()) + array(
'fedex_ground' => 0,
'fedex' => 1,
'fedex_freight' => 2,
);
$methods = array(
'fedex_ground' => array(
'id' => 'fedex_ground',
'module' => 'uc_fedex',
'title' => t('FedEx (Ground)'),
'quote' => array(
'type' => 'small_package',
'callback' => 'uc_fedex_quote',
'accessorials' => _uc_fedex_ground_services(),
),
'ship' => array(
'type' => 'small_package',
'callback' => 'uc_fedex_fulfill_order',
'file' => 'uc_fedex.ship.inc',
'pkg_types' => _uc_fedex_package_types(),
),
'enabled' => $enabled['fedex_ground'],
'weight' => $weight['fedex_ground'],
),
'fedex' => array(
'id' => 'fedex',
'module' => 'uc_fedex',
'title' => t('FedEx (Express)'),
'quote' => array(
'type' => 'small_package',
'callback' => 'uc_fedex_quote',
'accessorials' => _uc_fedex_express_services(),
),
'ship' => array(
'type' => 'small_package',
'callback' => 'uc_fedex_fulfill_order',
'file' => 'uc_fedex.ship.inc',
'pkg_types' => _uc_fedex_package_types(),
),
'enabled' => $enabled['fedex'],
'weight' => $weight['fedex'],
),
'fedex_freight' => array(
'id' => 'fedex_freight',
'module' => 'uc_fedex',
'title' => t('FedEx (Freight)'),
'quote' => array(
'type' => 'small_package',
'callback' => 'uc_fedex_quote',
'accessorials' => _uc_fedex_freight_services(),
),
'enabled' => $enabled['fedex_freight'],
'weight' => $weight['fedex_freight'],
),
);
return $methods;
}
/**
* Implements Ubercart's hook_uc_store_status().
*
* Lets the administrator know if the FedEx account information has not been
* filled out.
* Returns an array of error or status messages from configuration of FedEx
* module.
*/
function uc_fedex_uc_store_status() {
$messages = array();
$key = variable_get('uc_fedex_user_credential_key', 0);
$password = variable_get('uc_fedex_user_credential_password', 0);
$account = variable_get('uc_fedex_account_number', 0);
$meter = variable_get('uc_fedex_meter_number', 0);
if ($key && $password && $account && $meter) {
$messages[] = array(
'status' => 'ok',
'title' => t('FedEx Ship Manager'),
'desc' => t('Information needed to access FedEx Ship Manager has been entered.'),
);
}
else {
$messages[] = array(
'status' => 'error',
'title' => t('FedEx Ship Manager'),
'desc' => t('More information is needed to access FedEx Ship Manager. Please enter it !link.', array('!link' => l(t('here'), 'admin/store/settings/quotes/fedex'))),
);
}
return $messages;
}
/******************************************************************************
* Module Functions *
******************************************************************************/
/**
* Callback for retrieving a FedEx shipping quote.
*
* Requests a quote of all available FedEx services. Quote returned
* from the FedEx server is parsed and only the selected services are
* presented to the user.
*
* @param $products
* Array of cart contents.
* @param $details
* Order details other than product information.
*
* @return
* JSON object containing rate, error, and debugging information.
*/
function uc_fedex_quote($products, $details, $method) {
// The uc_quote AJAX query can fire before the customer has completely
// filled out the destination address, so check to see whether the address
// is complete. If not, abort.
$destination = (object) $details;
if (empty($destination->zone) ||
empty($destination->postal_code) ||
empty($destination->country)) {
// Skip this shipping method.
return array();
}
// Assign products to one or more packages for quoting.
$packages = _uc_fedex_package_products($products);
$skids = _uc_fedex_freight_package_products($products);
if (!count($packages) && !count($skids)) {
// If _uc_fedex_package_products() returned no packages,
// then at least one item must be too heavy to ship via FedEx.
// Skip this shipping method.
return array();
}
// Create and fill object with info needed about origin.
$origin = variable_get('uc_quote_store_default_address', new UcAddress());
$country = db_query("SELECT * FROM {uc_countries} WHERE country_id = :id", array(':id' => $origin->country));
$country_data = $country->fetchObject();
$origin->country_iso_code_2 = $country_data->country_iso_code_2;
// Create and fill object with info needed about destination.
$destination = (object) $details;
if ($origin->country == $destination->country) {
// Try to save a DB query.
$destination->country_iso_code_2 = $origin->country_iso_code_2;
}
else {
$country = db_query("SELECT * FROM {uc_countries} WHERE country_id = :id", array(':id' => $destination->country));
$country_data = $country->fetchObject();
$destination->country_iso_code_2 = $country_data->country_iso_code_2;
}
$debug = user_access('configure quotes') &&
variable_get('uc_quote_display_debug', FALSE);
// Determine if address is Residential or Commercial
// If Address Validation API is not used or fails, default to store default.
$destination->residential = uc_fedex_address_is_residential($destination, variable_get('uc_fedex_residential_quotes', 1), $debug);
// Call the method that does the actual SOAP request to the FedEx Server
// Response contains all available fedex_ground and fedex services and rates.
if (count($packages)) {
$response = uc_fedex_rate_request($packages, $origin, $destination);
}
// Freight response contains all available fedex_freight services and rates.
if (count($skids)) {
$freight_response = uc_fedex_freight_rate_request($skids, $origin, $destination);
}
// Merge both response objects.
$aggregated_response = (object) array_merge_recursive((array) $response, (array) $freight_response);
// Construct an array containing only those services that the
// store admin has allowed in admin/store/settings/quotes/edit.
$fedex_services = array();
switch ($method['id']) {
case 'fedex_ground':
$fedex_services = array_filter(variable_get('uc_fedex_ground_services', _uc_fedex_ground_services()));
break;
case 'fedex':
$fedex_services = array_filter(variable_get('uc_fedex_express_services', _uc_fedex_express_services()));
break;
case 'fedex_freight':
$fedex_services = array_filter(variable_get('uc_fedex_freight_services', _uc_fedex_freight_services()));
break;
}
// Initialize return array.
$quotes = array();
if (!isset($aggregated_response->RateReplyDetails)) {
// Memphis, we have a problem ...
// Error returned from FedEx server - will print in $message box.
// Don't even try to extract a quote from the response, just return
// empty quote array.
return $quotes;
}
// Test responses to see if we are interested in that service.
foreach ($aggregated_response->RateReplyDetails as $options) {
$service = $options->ServiceType;
if (in_array($service, $fedex_services)) {
$return_quote_based_on_length = $return_quote_based_on_pkg_num = TRUE;
$is_freight = stripos($service, 'FREIGHT');
if ($is_freight !== FALSE) {
// If shipping method is one of Freight methods
// Check conditions that enable display of Freight quotes.
if ((!empty(FREIGHT_MIN_PKG_NUM) && is_numeric(FREIGHT_MIN_PKG_NUM)) && count($packages) >= FREIGHT_MIN_PKG_NUM) {
// Continue getting the quote.
}
else {
// Skip this shipping method.
$return_quote_based_on_pkg_num = FALSE;
}
// Calculate FREIGHT_MIN_LENGTH value.
$freight_min_length_value = FREIGHT_MIN_LENGTH_VALUE * uc_length_conversion(FREIGHT_MIN_LENGTH_VALUE_UNITS, variable_get('uc_length_unit', 'IN'));
foreach ($packages as $package) {
if ($package->length >= $freight_min_length_value) {
// Continue processing the quote.
}
else {
// If the length of at least one package >= min package
// length for Freight quotes to kick in -
// Skip this shipping method.
$return_quote_based_on_length = FALSE;
}
}
if (!$return_quote_based_on_pkg_num && !$return_quote_based_on_length) {
return array();
}
}
// Check to see if we're quoting ACCOUNT or LIST rates.
if (variable_get('uc_fedex_quote_type', 'list') == 'list') {
// LIST rate.
// LIST quotes return both ACCOUNT rates and LIST rates:
// Order not guaranteed.
// RatedShipmentDetails[0] = PAYOR_ACCOUNT
// RatedShipmentDetails[1] = RATED_ACCOUNT
// RatedShipmentDetails[2] = PAYOR_LIST
// RatedShipmentDetails[3] = RATED_LIST.
foreach ($options->RatedShipmentDetails as $ratedetail) {
if ($ratedetail->ShipmentRateDetail->RateType == 'PAYOR_LIST') {
break;
}
}
}
else {
// ACCOUNT rate.
// ACCOUNT quotes may return either ACCOUNT rates only OR
// ACCOUNT rates and LIST rates. Check.
if (is_array($options->RatedShipmentDetails)) {
foreach ($options->RatedShipmentDetails as $ratedetail) {
if ($ratedetail->ShipmentRateDetail->RateType == 'PAYOR_ACCOUNT') {
break;
}
}
}
else {
$ratedetail = $options->RatedShipmentDetails;
}
}
// Need to handle dimensional rates, other modifiers.
// Markup rate before customer sees it.
$rate = uc_fedex_rate_markup($ratedetail->ShipmentRateDetail->TotalNetCharge->Amount);
$quotes[$service] = array(
'rate' => $rate,
'format' => uc_currency_format($rate),
// Cart pane.
'option_label' => theme('uc_fedex_option_label', array('service' => $method['quote']['accessorials'][$service], 'packages' => $packages, 'skids' => $skids)),
);
}
}
if ($debug) {
$quotes['data']['debug'] = htmlentities($response).'<br />';
}
// Sort rate quotes in order of increasing price.
uasort($quotes, 'uc_quote_price_sort');
return $quotes;
}
/**
* Constructs and executes a SOAP RateAvailabilityService request.
*
* Obtains Rate and Available Services information needed for
* shipping quote.
*
* SOAP call parameters are set in the order they appear in the WSDL file
* Associative array of DOM returned.
*
* @param $packages
* Array of packages received from the cart.
* @param $origin
* Delivery origin address information.
* @param $destination
* Delivery destination address information.
*
* @return
* Associative array mirroring contents of SOAP object returned from server.
*/
function uc_fedex_rate_request($packages, $origin, $destination) {
// Set up SOAP call.
// Allow tracing so details of request can be retrieved for error logging.
$client = new SoapClient(drupal_get_path('module', 'uc_fedex')
. '/wsdl-' . variable_get('uc_fedex_server_role', 'testing')
. '/RateService_v20.wsdl', array('trace' => 1));
// FedEx user key and password filled in by user on admin form.
$request['WebAuthenticationDetail'] = array(
'UserCredential' => array(
'Key' => variable_get('uc_fedex_user_credential_key', 0),
'Password' => variable_get('uc_fedex_user_credential_password', 0),
),
);
// FedEx account and meter number filled in by user on admin form.
$request['ClientDetail'] = array(
'AccountNumber' => variable_get('uc_fedex_account_number', 0),
'MeterNumber' => variable_get('uc_fedex_meter_number', 0),
);
// Optional parameter, contains anything.
$request['TransactionDetail'] = array(
'CustomerTransactionId' => '*** Rate/Available Services Request v20 from Ubercart ***',
);
// Rate Services Availability Request v20.0.0.
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '20',
'Intermediate' => '0',
'Minor' => '0',
);
// Grab details of sender origin - not necessarily package origin.
$request['RequestedShipment']['Shipper'] = array(
'Address' => array(
'StreetLines' => array(
$origin->street1,
$origin->street2,
),
'City' => $origin->city,
'StateOrProvinceCode' => uc_get_zone_code($origin->zone),
'PostalCode' => $origin->postal_code,
'CountryCode' => $origin->country_iso_code_2,
),
);
// Grab details of package destination.
$request['RequestedShipment']['Recipient'] = array(
'Address' => array(
'StreetLines' => array(
$destination->street1,
$destination->street2,
),
'City' => $destination->city,
'StateOrProvinceCode' => uc_get_zone_code($destination->zone),
'PostalCode' => $destination->postal_code,
'CountryCode' => $destination->country_iso_code_2,
'Residential' => $destination->residential,
),
);
// Currency for quote.
$request['RequestedShipment']['CurrencyType'] = variable_get('uc_currency_code', 'USD');
// Set Pickup/Dropoff type.
$request['RequestedShipment']['DropoffType'] = variable_get('uc_fedex_dropoff_type', 'REGULAR_PICKUP');
// Note that ACCOUNT rates *require* a valid account number
// and return accurate answers on the production server.
$request['RequestedShipment']['RateRequestTypes'] = strtoupper(variable_get('uc_fedex_quote_type', 'list'));
// When the package is going to ship
// have to think about this -
// cutoff times, commits store owner to exact ship date, etc.
// Probably have to make an admin menu option with cutoff time, after
// which ShipDate becomes "tomorrow" unless of course tomorrow is a
// weekend when you're closed... But this shouldn't affect the rate.
// Drupal 6.x version of format_date() doesn't support 'c', so until
// then we use date() directly. date() doesn't take care of site
// timezone, though.
$request['RequestedShipment']['ShipTimestamp'] = date('c');
// Packaging type - need this to be settable for each package rather
// than one site-wide setting?
$request['RequestedShipment']['PackagingType'] = variable_get('uc_fedex_package_type', 'YOUR_PACKAGING');
$request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES';
$request['RequestedShipment']['PackageCount'] = count($packages);
$request['RequestedShipment']['RequestedPackageLineItems'] = array();
// Determine weight and length units to send to FedEx.
// FedEx supports only LB and KG; if store units are set to
// something else then determine conversion factor to apply
// to package weights.
$weight_units = strtoupper(variable_get('uc_weight_unit', 'LB'));
$weight_conversion_factor = 1;
if ($weight_units != 'LB' && $weight_units != 'KG') {
$weight_conversion_factor = uc_weight_conversion($weight_units, 'LB');
$weight_units = 'LB';
}
$group_package_count = count($packages);
// Iterate over $packages to account for multi-package shipments.
$sequence = 0;
foreach ($packages as $package) {
$sequence++;
$package_properties = array(
'GroupPackageCount' => $sequence,
'SequenceNumber' => $sequence,
// Weights must be rounded up to nearest integer value.
'Weight' => array(
'Value' => ceil($package->shipweight * $weight_conversion_factor),
'Units' => $weight_units,
),
);
// Add Insurance if requested.
if (variable_get('uc_fedex_insurance', FALSE)) {
$package_properties['InsuredValue'] = array(
'Amount' => $package->price,
'Currency' => variable_get('uc_currency_code', 'USD'),
);
}
$request['RequestedShipment']['RequestedPackageLineItems'][] = $package_properties;
}
// Send the SOAP request to the FedEx server.
try {
$response = $client->getRates($request);
if ($response->HighestSeverity != 'FAILURE' &&
$response->HighestSeverity != 'ERROR') {
print_request_response($client);
}
else {
drupal_set_message(t('Error in processing FedEx Shipping Quote transaction.'), 'error');
if (!empty($response->Notifications->LocalizedMessage)) {
drupal_set_message(filter_xss($response->Notifications->LocalizedMessage), 'error');
}
elseif (!empty($response->Notifications->Message)) {
drupal_set_message(filter_xss($response->Notifications->Message), 'error');
}
else {
foreach ($response->Notifications as $notification) {
if (is_array($response->Notifications)) {
drupal_set_message($notification->Severity . ': ' .
$notification->Message, 'error');
}
elseif (is_string($notification)) {
drupal_set_message($notification, 'error');
}
}
}
}
return $response;
}
catch (SoapFault $exception) {
drupal_set_message('<h2>Fault</h2><br /><b>Code:</b>' . $exception->faultcode . '<br /><b>String:</b>' . $exception->faultstring . '<br />' . '<h2>Request</h2>' . '<br/>' . '<pre>' . htmlspecialchars($client->__getLastRequest()). '</pre>', 'error');
// What else needs to be done here if FedEx quote fails? Define what to
// display to customer.
}
}
/**
* Freight Rate request.
*
* Constructs and executes a SOAP RateAvailabilityService request.
* Obtains Freight Rate and Available Services information needed for
* shipping quote.
*
* SOAP call parameters are set in the order they appear in the WSDL file
* Associative array of DOM returned.
*
* @param array $skids
* Array of packages received from the cart.
* @param array $origin
* Delivery origin address information.
* @param array $destination
* Delivery destination address information.
*
* @return array
* Associative array mirroring contents of SOAP object returned from server.
*/
function uc_fedex_freight_rate_request($skids, $origin, $destination) {
$freight_account_number = FREIGHT_ACCOUNT_NUMBER;
$server_role = SERVER_ROLE;
$freight_billing_contact = array();
// Set up SOAP call.
// Allow tracing so details of request can be retrieved for error logging.
$client = new SoapClient(drupal_get_path('module', 'uc_fedex')
. '/wsdl-' . variable_get('uc_fedex_server_role', 'testing')
. '/RateService_v20.wsdl', array('trace' => 1));
$request['WebAuthenticationDetail'] = array(
'UserCredential' => array(
'Key' => variable_get('uc_fedex_user_credential_key', 0),
'Password' => variable_get('uc_fedex_user_credential_password', 0),
),
);
// FedEx account and meter number filled in by user on admin form.
$request['ClientDetail'] = array(
'AccountNumber' => variable_get('uc_fedex_account_number', 0),
'MeterNumber' => variable_get('uc_fedex_meter_number', 0),
);
// Optional parameter, contains anything.
$request['TransactionDetail'] = array(
'CustomerTransactionId' => '*** Rate/Available Services Request v20 from Ubercart ***',
);
// Rate Services Availability Request v20.0.0.
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '20',
'Intermediate' => '0',
'Minor' => '0',
);
// Grab details of sender origin - not necessarily package origin
// Shipper address is custom for testing Freight shipments.
if ($server_role == 'testing' && !empty($freight_account_number)) {
$request['RequestedShipment']['Shipper'] = array(
'Contact' => array(
'PersonName' => 'Big Shipper',
'Title' => 'Manager',
'CompanyName' => 'Freight Shipper Co',
'PhoneNumber' => '1234567890',
),
'Address' => array(
'StreetLines' => array(
'1202 Chalet Ln',
'Do Not Delete - Test Account',
),
'City' => 'Harrison',
'StateOrProvinceCode' => 'AR',
'PostalCode' => '72601-6353',
'CountryCode' => 'US',
),
);
$freight_billing_contact = array(
'Contact' => array(
'PersonName' => 'Big Shipper',
'Title' => 'Manager',
'CompanyName' => 'Freight Shipper Co',
'PhoneNumber' => '1234567890',
),
'Address' => array(
'StreetLines' => array(
'1202 Chalet Ln',
'Do Not Delete - Test Account',
),
'City' => 'Harrison',
'StateOrProvinceCode' => 'AR',
'PostalCode' => '72601-6353',
'CountryCode' => 'US',
),
);
}
else {
$freight_billing_contact = array(
'Contact' => array(
'PersonName' => $origin->first_name . ' ' . $origin->last_name,
'CompanyName' => $origin->company,
'PhoneNumber' => $origin->phone,
),
'Address' => array(
'StreetLines' => array(
$origin->street1,
$origin->street2,
),
'City' => $origin->city,
'StateOrProvinceCode' => uc_get_zone_code($origin->zone),
'PostalCode' => $origin->postal_code,
'CountryCode' => $origin->country_iso_code_2,
),
);
$request['RequestedShipment']['Shipper'] = array(
'Contact' => array(
'PersonName' => $origin->first_name . ' ' . $origin->last_name,
'CompanyName' => $origin->company,
'PhoneNumber' => $origin->phone,
),
'Address' => array(
'StreetLines' => array(
$origin->street1,
$origin->street2,
),
'City' => $origin->city,
'StateOrProvinceCode' => uc_get_zone_code($origin->zone),
'PostalCode' => $origin->postal_code,
'CountryCode' => $origin->country_iso_code_2,
),
);
}
// Grab details of package destination.
$request['RequestedShipment']['Recipient'] = array(
'Address' => array(
'City' => $destination->city,
'StateOrProvinceCode' => uc_get_zone_code($destination->zone),
'PostalCode' => $destination->postal_code,
'CountryCode' => $destination->country_iso_code_2,
'Residential' => $destination->residential,
),
);
$request['RequestedShipment']['ShippingChargesPayment'] = array(
// Valid values RECIPIENT, SENDER and THIRD_PARTY.
'PaymentType' => 'SENDER',
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => $freight_account_number,
'CountryCode' => $origin->country_iso_code_2,
),
),
);
// Currency for quote.
$request['RequestedShipment']['CurrencyType'] = variable_get('uc_currency_code', 'USD');
// Set Pickup/Dropoff type.
$request['RequestedShipment']['DropoffType'] = variable_get('uc_fedex_dropoff_type', 'REGULAR_PICKUP');
// Note that ACCOUNT rates *require* a valid account number
// and return accurate answers on the production server.
$request['RequestedShipment']['RateRequestTypes'] = strtoupper(variable_get('uc_fedex_quote_type', 'list'));
// When the package is going to ship
// have to think about this -
// cutoff times, commits store owner to exact ship date, etc.
// Probably have to make an admin menu option with cutoff time, after
// which ShipDate becomes "tomorrow" unless of course tomorrow is a
// weekend when you're closed... But this shouldn't affect the rate.
// Drupal 6.x version of format_date() doesn't support 'c', so until
// then we use date() directly. date() doesn't take care of site
// timezone, though.
$request['RequestedShipment']['ShipTimestamp'] = date('c');
// Packaging type for LTL Freight has only one option - 'YOUR_PACKAGING'.
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING';
$request['RequestedShipment']['PackageCount'] = count($skids);
// Determine weight and length units to send to FedEx
// FedEx supports only LB and KG; if store units are set to
// something else then determine conversion factor to apply
// to package weights.
$weight_units = strtoupper(variable_get('uc_weight_unit', 'LB'));
$weight_conversion_factor = 1;
if ($weight_units != 'LB' && $weight_units != 'KG') {
$weight_conversion_factor = uc_weight_conversion($weight_units, 'LB');
$weight_units = 'LB';
}
// Iterate over $packages to account for multi-package shipments.
$skid_qty = 0;
$skid_total_value = 0;
$skid_total_volume = 0;
foreach ($skids as $skid) {
$skid_qty++;
$skid_total_value += $skid->price;
$skid_total_volume += $skid->volume;
}
$request['RequestedShipment']['FreightShipmentDetail'] = array(
// Freight Account Number.
'FedExFreightAccountNumber' => $freight_account_number,
'FedExFreightBillingContactAndAddress' => $freight_billing_contact,
'PrintedReferences' => array(
'Type' => 'SHIPPER_ID_NUMBER',
'Value' => 'RBB1057',
),
'Role' => 'SHIPPER',
'PaymentType' => 'PREPAID',
'CollectTermsType' => 'STANDARD',
'TotalHandlingUnits' => $skid_qty,
'DeclaredValuePerUnit' => array(
'Currency' => variable_get('uc_currency_code', 'USD'),
'Amount' => $skid_total_value,
),
'LineItems' => array(
'FreightClass' => 'CLASS_070',
'ClassProvidedByCustomer' => FALSE,
'Weight' => array(
'Value' => ceil($skid->shipweight * $weight_conversion_factor),
'Units' => $weight_units,
),
),
'Volume' => array(
'Units' => 'CUBIC_FT',
'Value' => ceil($skid_total_volume / 1728),
),
);
// Add Extreme Length elements only for skids that are > 12ft (2017).
if ($skid->extreme_length) {
$request['RequestedShipment']['SpecialServicesRequested'] = array(
'SpecialServiceTypes' => 'EXTREME_LENGTH',
);
}
// Send the SOAP request to the FedEx server.
try {
$response = $client->getRates($request);
if ($response->HighestSeverity != 'FAILURE' &&
$response->HighestSeverity != 'ERROR'
) {
print_request_response($client);
}
else {
drupal_set_message(t('Error in processing FedEx Shipping Quote transaction.'), 'error');
if (!empty($response->Notifications->LocalizedMessage)) {
drupal_set_message(filter_xss($response->Notifications->LocalizedMessage), 'error');
}
elseif (!empty($response->Notifications->Message)) {
drupal_set_message(filter_xss($response->Notifications->Message), 'error');
}
else {
foreach ($response->Notifications as $notification) {
if (is_array($response->Notifications)) {
drupal_set_message($notification->Severity . ': ' .
$notification->Message, 'error');
}
elseif (is_string($notification)) {
drupal_set_message($notification, 'error');
}
}
}
}
return $response;
}
catch (SoapFault $exception) {
drupal_set_message('<h2>Fault</h2><br /><b>Code:</b>' . $exception->faultcode . '<br /><b>String:</b>' . $exception->faultstring . '<br />' . '<h2>Request</h2>' . '<br/>' . '<pre>' . htmlspecialchars($client->__getLastRequest()) . '</pre>', 'error');
// What else needs to be done here if FedEx quote fails? Define what to
// display to customer.
}
}
/**
* Modifies the rate received from FedEx before displaying to the customer.
*
* @param $rate
* Shipping rate without any rate markup.
*
* @return
* Shipping rate after markup.
*/
function uc_fedex_rate_markup($rate) {
$markup = trim(variable_get('uc_fedex_rate_markup', '0'));
$type = variable_get('uc_fedex_rate_markup_type', 'percentage');
if (is_numeric($markup)) {
switch ($type) {
case 'percentage':
return $rate + $rate * floatval($markup) / 100;
case 'multiplier':
return $rate * floatval($markup);
case 'currency':
return $rate + floatval($markup);
}
}
else {
return $rate;
}
}
/**
* Modifies the weight of shipment before sending to FedEx for a quote.
*
* @param $weight
* Shipping weight without any weight markup.
*
* @return
* Shipping weight after markup.
*/
function uc_fedex_weight_markup($weight) {
$markup = trim(variable_get('uc_fedex_weight_markup', '0'));
$type = variable_get('uc_fedex_weight_markup_type', 'percentage');
if (is_numeric($markup)) {
switch ($type) {
case 'percentage':
return $weight + $weight * floatval($markup) / 100;