Skip to content

Commit

Permalink
Feat (tracking): Track your shipment by tracking number
Browse files Browse the repository at this point in the history
- Create tracking page for displaying your shipment
see #3
  • Loading branch information
hunghbmGG committed Oct 1, 2020
1 parent 04179f3 commit 533ff58
Show file tree
Hide file tree
Showing 9 changed files with 1,017 additions and 35 deletions.
30 changes: 14 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,18 @@
# Bagisto FeDex
This extension used for calculating shipping rate with the FedEx services.

## Features
- Calculate shipping rate with FedEx services.
- Track your shipment by tracking number.
## Requirements
- [Bagisto](https://github.com/bagisto/bagisto)
- [Bagisto v1.2](https://github.com/bagisto/bagisto)
- [jeremy-dunn/php-fedex-api-wrapper](https://packagist.org/packages/jeremy-dunn/php-fedex-api-wrapper)

## Installation

### Install with composer
1. Run the following command
```php
composer require hunghbm/bagisto-fedex
```
2. Open config/app.php and add **Hunghbm\FedEx\Providers\FedExServiceProvider::class**.
3. Run the following command
```php
composer dump-autoload
```
4. Go to `https://<your-site>/admin/configuration/sales/carriers`.
5. Make sure that **Marketplace FedEx** is active and press save.

### Install with package folder
1. Unzip all the files to **packages/GGPHP/Shipping**.
2. Open `config/app.php` and add **GGPHP\Shipping\Providers\ShippingServiceProvider::class**.
3. Open `composer.json` of root project and add **GGPHP\Shipping\Providers\ShippingServiceProvider::class**.
3. Open `composer.json` of root project and add **"GGPHP\\Shipping\\": "packages/GGPHP/Shipping/src"**.
4. Run the following command
```php
composer dump-autoload
Expand Down Expand Up @@ -54,3 +44,11 @@ Your customers are now able to select the new shipping method.
- Zip: 20171
- City: Herndon
- Country: US

## Guide

### Track your shipment by tracking number.
- Go to `https://<your-site>/admin/sales/tracking/{tracking-number}`.

### Get shipment infomations
- Use `fedExTrackById($trackingIds)` method to get shipment infomations with `trackingIds` are tracking number array.
2 changes: 1 addition & 1 deletion src/Carriers/Fedex.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public function calculate()
}

// Get shipping rates
$rateDetails = calculateShippingRates($shippingInfo);
$rateDetails = fedexCalculateShippingRates($shippingInfo);

if (isset($rateDetails['status']) && !$rateDetails['status'])
return $rateDetails;
Expand Down
40 changes: 40 additions & 0 deletions src/Http/Controllers/Tracking/TrackingController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace GGPHP\Shipping\Http\Controllers\Tracking;

use Webkul\Admin\Http\Controllers\Controller;

class TrackingController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
protected $_config;

/**
* Create a new controller instance
*
* @return void
*/
public function __construct()
{
$this->middleware('admin');

$this->_config = request('_config');
}

/**
* Show the view for the specified resource.
*
* @param int $id
* @return \Illuminate\View\View
*/
public function view($trackingId)
{
$trackings = fedExTrackById([$trackingId]);

return view($this->_config['view'], compact('trackings', 'trackingId'));
}
}
115 changes: 99 additions & 16 deletions src/Http/helpers.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
<?php

use FedEx\RateService\Request;
use FedEx\RateService\ComplexType;
use FedEx\RateService\SimpleType;

if (! function_exists('calculateShippingRates')) {
function calculateShippingRates($data)
if (! function_exists('fedExCalculateShippingRates')) {
function fedExCalculateShippingRates($data)
{
$rateRequest = new ComplexType\RateRequest();
$rateRequest = new FedEx\RateService\ComplexType\RateRequest();

// Authentication & client details
$rateRequest->WebAuthenticationDetail->UserCredential->Key = core()->getConfigData('sales.carriers.fedexrate.key') ?? '';
Expand All @@ -23,7 +18,7 @@ function calculateShippingRates($data)
$rateRequest->ReturnTransitAndCommit = false;

// Service type
$rateRequest->RequestedShipment->PackagingType = $data['packaging_type'] ?? SimpleType\PackagingType::_YOUR_PACKAGING;
$rateRequest->RequestedShipment->PackagingType = $data['packaging_type'] ?? FedEx\RateService\SimpleType\PackagingType::_YOUR_PACKAGING;

// Preferred currency
$rateRequest->RequestedShipment->PreferredCurrency = core()->getBaseCurrencyCode() ?? 'USD';
Expand All @@ -43,31 +38,31 @@ function calculateShippingRates($data)
$rateRequest->RequestedShipment->Recipient->Address->CountryCode = $data['recipient']['country_code'];

// Shipping charges payment
$rateRequest->RequestedShipment->ShippingChargesPayment->PaymentType = SimpleType\PaymentType::_SENDER;
$rateRequest->RequestedShipment->ShippingChargesPayment->PaymentType = FedEx\RateService\SimpleType\PaymentType::_SENDER;

// Rate request types
$rateRequest->RequestedShipment->RateRequestTypes = [SimpleType\RateRequestType::_LIST];
$rateRequest->RequestedShipment->RateRequestTypes = [FedEx\RateService\SimpleType\RateRequestType::_LIST];
$rateRequest->RequestedShipment->PackageCount = 1;

// Create package line items
$rateRequest->RequestedShipment->RequestedPackageLineItems = [new ComplexType\RequestedPackageLineItem()];
$rateRequest->RequestedShipment->RequestedPackageLineItems = [new FedEx\RateService\ComplexType\RequestedPackageLineItem()];

// Package 1
$rateRequest->RequestedShipment->RequestedPackageLineItems[0]->Weight->Value = $data['package']['weight'];
$rateRequest->RequestedShipment->RequestedPackageLineItems[0]->Weight->Units =
core()->getConfigData('sales.carriers.fedexrate.weight_unit') ?? SimpleType\WeightUnits::_LB;
core()->getConfigData('sales.carriers.fedexrate.weight_unit') ?? FedEx\RateService\SimpleType\WeightUnits::_LB;
$rateRequest->RequestedShipment->RequestedPackageLineItems[0]->Dimensions->Length = $data['package']['length'];
$rateRequest->RequestedShipment->RequestedPackageLineItems[0]->Dimensions->Width = $data['package']['width'];
$rateRequest->RequestedShipment->RequestedPackageLineItems[0]->Dimensions->Height = $data['package']['height'];
$rateRequest->RequestedShipment->RequestedPackageLineItems[0]->Dimensions->Units =
core()->getConfigData('sales.carriers.fedexrate.length_class') ?? SimpleType\LinearUnits::_IN;
core()->getConfigData('sales.carriers.fedexrate.length_class') ?? FedEx\RateService\SimpleType\LinearUnits::_IN;
$rateRequest->RequestedShipment->RequestedPackageLineItems[0]->GroupPackageCount = 1;

$rateServiceRequest = new Request();
$rateServiceRequest = new FedEx\RateService\Request();

// Use production URL
if (core()->getConfigData('sales.carriers.fedexrate.production_mode'))
$rateServiceRequest->getSoapClient()->__setLocation(Request::PRODUCTION_URL);
$rateServiceRequest->getSoapClient()->__setLocation(FedEx\RateService\Request::PRODUCTION_URL);

$response = $rateServiceRequest->getGetRatesReply($rateRequest);
$rateDetails = [];
Expand Down Expand Up @@ -101,4 +96,92 @@ function calculateShippingRates($data)
return $rateDetails;
}
}

if (! function_exists('fedExTrackById')) {
function fedExTrackById($trackingIds)
{
$trackRequest = new FedEx\TrackService\ComplexType\TrackRequest();

// User credential
$trackRequest->WebAuthenticationDetail->UserCredential->Key = core()->getConfigData('sales.carriers.fedexrate.key') ?? '';
$trackRequest->WebAuthenticationDetail->UserCredential->Password = core()->getConfigData('sales.carriers.fedexrate.password') ?? '';

// Client detail
$trackRequest->ClientDetail->AccountNumber = core()->getConfigData('sales.carriers.fedexrate.account_ID') ?? '';
$trackRequest->ClientDetail->MeterNumber = core()->getConfigData('sales.carriers.fedexrate.meter_number') ?? '';

// Version
$trackRequest->Version->ServiceId = 'trck';
$trackRequest->Version->Major = 19;
$trackRequest->Version->Intermediate = 0;
$trackRequest->Version->Minor = 0;

// For get all events
$trackRequest->ProcessingOptions = [FedEx\TrackService\SimpleType\TrackRequestProcessingOptionType::_INCLUDE_DETAILED_SCANS];

// Track shipments
$trackRequest->SelectionDetails = [];
foreach ($trackingIds as $key => $trackingId) {
$trackRequest->SelectionDetails[] = new FedEx\TrackService\ComplexType\TrackSelectionDetail();
$trackRequest->SelectionDetails[$key]->PackageIdentifier->Value = $trackingId;
$trackRequest->SelectionDetails[$key]->PackageIdentifier->Type =
FedEx\TrackService\SimpleType\TrackIdentifierType::_TRACKING_NUMBER_OR_DOORTAG;
}

$request = new FedEx\TrackService\Request();
$response = $request->getTrackReply($trackRequest);

$trackReplyDetails = [];
if (! empty($response) && $response->HighestSeverity == 'SUCCESS' && ! empty($response->CompletedTrackDetails)) {
foreach ($response->CompletedTrackDetails as $trackReplyDetail) {
if (! empty($notification = $trackReplyDetail->TrackDetails[0]->Notification->Severity) && $notification == 'SUCCESS') {
foreach ($trackReplyDetail->TrackDetails as $key => $trackDetail) {
$trackReplyDetails[$key]['trackingId'] = $trackDetail->TrackingNumber ?? '';
$trackReplyDetails[$key]['trackingNumberUniqueIdentifier'] =
$trackDetail->TrackingNumberUniqueIdentifier ?? '';
$trackReplyDetails[$key]['statusDetail'] = $trackDetail->StatusDetail ?? '';
$trackReplyDetails[$key]['serviceCommitMessage'] = $trackDetail->ServiceCommitMessage ?? '';
$trackReplyDetails[$key]['destinationServiceArea'] = $trackDetail->DestinationServiceArea ?? '';
$trackReplyDetails[$key]['carrierCode'] = $trackDetail->CarrierCode ?? '';
$trackReplyDetails[$key]['operatingCompanyOrCarrierDescription'] =
$trackDetail->OperatingCompanyOrCarrierDescription ?? '';
$trackReplyDetails[$key]['otherIdentifiers'] = $trackDetail->OtherIdentifiers ?? [];
$trackReplyDetails[$key]['service'] = $trackDetail->Service ?? '';
$trackReplyDetails[$key]['packageWeight'] = $trackDetail->PackageWeight ?? '';
$trackReplyDetails[$key]['packaging'] = $trackDetail->Packaging ?? '';
$trackReplyDetails[$key]['physicalPackagingType'] = $trackDetail->PhysicalPackagingType ?? '';
$trackReplyDetails[$key]['packageSequenceNumber'] = $trackDetail->PackageSequenceNumber ?? '';
$trackReplyDetails[$key]['packageCount'] = $trackDetail->PackageCount ?? '';
$trackReplyDetails[$key]['shipmentContentPieceCount'] = $trackDetail->ShipmentContentPieceCount ?? '';
$trackReplyDetails[$key]['packageContentPieceCount'] = $trackDetail->PackageContentPieceCount ?? '';
$trackReplyDetails[$key]['payments'] = $trackDetail->Payments ?? [];
$trackReplyDetails[$key]['shipperAddress'] = $trackDetail->ShipperAddress ?? '';
$trackReplyDetails[$key]['originLocationAddress'] = $trackDetail->OriginLocationAddress ?? '';
$trackReplyDetails[$key]['datesOrTimes'] = $trackDetail->DatesOrTimes ?? [];
$trackReplyDetails[$key]['lastUpdatedDestinationAddress'] = $trackDetail->LastUpdatedDestinationAddress ?? '';
$trackReplyDetails[$key]['destinationAddress'] = $trackDetail->DestinationAddress ?? '';
$trackReplyDetails[$key]['deliveryAttempts'] = $trackDetail->DeliveryAttempts ?? '';
$trackReplyDetails[$key]['totalUniqueAddressCountInConsolidation'] =
$trackDetail->TotalUniqueAddressCountInConsolidation ?? '';
$trackReplyDetails[$key]['deliveryOptionEligibilityDetails'] =
$trackDetail->DeliveryOptionEligibilityDetails ?? [];
$trackReplyDetails[$key]['events'] = $trackDetail->Events ?? [];
}
} else {
$trackReplyDetails = [
'message' => $trackReplyDetail->TrackDetails[0]->Notification->Message ?? '',
'status' => FALSE,
];
}
}
} else {
$trackReplyDetails = [
'message' => $response->Notifications[0]->Message ?? '',
'status' => FALSE,
];
}

return $trackReplyDetails;
}
}
?>
16 changes: 16 additions & 0 deletions src/Http/routes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

Route::group(['middleware' => ['web']], function () {
Route::prefix(config('app.admin_url'))->group(function () {
// Admin Routes
Route::group(['middleware' => ['admin']], function () {
// Sales Routes
Route::prefix('sales')->group(function () {
// Tracking Routes
Route::get('tracking/{id}', 'GGPHP\Shipping\Http\Controllers\Tracking\TrackingController@view')->defaults('_config', [
'view' => 'ggphp-shipping::tracking.view',
]);
});
});
});
});
4 changes: 4 additions & 0 deletions src/Providers/ShippingServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ class ShippingServiceProvider extends ServiceProvider
*/
public function boot()
{
$this->loadRoutesFrom(__DIR__ . '/../Http/routes.php');

$this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'ggphp');

$this->loadViewsFrom(__DIR__ . '/../Resources/views', 'ggphp-shipping');

$this->app->register(FedExServiceProvider::class);
}
}
54 changes: 54 additions & 0 deletions src/Resources/lang/en/fedex.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,60 @@
'services' => 'Services',
'length-class' => 'Length Class',
'production-mode' => 'Production Mode',
'tracking-title' => 'Tracking',
'tracking-info' => 'Tracking Information',
'tracking-id' => 'Tracking number',
'tracking-number-unique-identifier' => 'Tracking number unique identifier',
'service-commit-message' => 'Service commit message',
'destination-service-area' => 'Destination service area',
'company-or-carrier' => 'Operating company or carrier',
'shipment-content-piece-count' => 'Shipment content piece count',
'delivery-attempts' => 'Delivery attempts',
'package-weight' => 'Package weight',
'packaging' => 'Packaging',
'physical-packaging-type' => 'Physical packaging type',
'package-count' => 'Package count',
'package-content-piece-count' => 'Package content piece count',
'total-consolidation' => 'Total unique address count',
'status-detail' => 'Status detail',
'creation-time' => 'Creation time',
'code' => 'Code',
'location' => 'Location',
'residential' => 'Residential',
'service' => 'Service',
'payments' => 'Payments',
'payment' => 'Payment',
'type' => 'Type',
'classification' => 'Classification',
'description' => 'Description',
'shipper-address' => 'Shipper address',
'state-or-province-code' => 'State or province code',
'country-code' => 'Country code',
'country-name' => 'Country name',
'origin-location-address' => 'Origin location address',
'last-updated-destination-address' => 'Last updated destination address',
'destination-address' => 'Destination address',
'address' => 'Address',
'events' => 'Events',
'event' => 'Event',
'timestamp' => 'Timestamp',
'event-type' => 'Event type',
'event-description' => 'Event description',
'postal-code' => 'Postal code',
'dates-or-times' => 'Dates or Times',
'date-or-time' => 'Date or time',
'date-or-timestamp' => 'Date or timestamp',
'other-identifiers' => 'Other Identifiers',
'identifier' => 'Identifier',
'value' => 'Value',
'package-sequence-number' => 'Package sequence number',
'delivery-option-eligibility-details' => 'Delivery Option Eligibility Details',
'option-eligibility' => 'Option eligibility',
'option' => 'Option',
'eligibility' => 'Eligibility',
'status-detail-and-service' => 'Status Detail and Service',
'no-data' => 'No data',
'city' => 'City',
]
]
];
Loading

0 comments on commit 533ff58

Please sign in to comment.