├── Nop.Plugin.Shipping.Fedex ├── logo.png ├── Views │ ├── _ViewImports.cshtml │ └── Configure.cshtml ├── plugin.json ├── PackingType.cs ├── FedexShippingDefaults.cs ├── API │ ├── Rates │ │ └── NopRateClient.cs │ ├── OAuth │ │ ├── NopOAuthClient.cs │ │ └── OAuthClient.cs │ ├── Track │ │ └── NopTrackClient.cs │ └── HttpClientExtensions.cs ├── Infrastructure │ └── PluginNopStartup.cs ├── Notes.txt ├── Models │ └── FedexShippingModel.cs ├── FedexSettings.cs ├── Nop.Plugin.Shipping.Fedex.csproj ├── FedexShipmentTracker.cs ├── Migrations │ └── UpgradeTo470.cs ├── Controllers │ └── ShippingFedexController.cs ├── FedexComputationMethod.cs └── Services │ └── FedexService.cs ├── README.md ├── .gitignore └── LICENSE.md /Nop.Plugin.Shipping.Fedex/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nopSolutions/FedEx-plugin-for-nopcommerce/HEAD/Nop.Plugin.Shipping.Fedex/logo.png -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Views/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @inherits Nop.Web.Framework.Mvc.Razor.NopRazorPage 2 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 3 | @addTagHelper *, Nop.Web.Framework 4 | 5 | @using Microsoft.AspNetCore.Mvc.ViewFeatures 6 | @using Nop.Web.Framework.UI 7 | @using Nop.Web.Framework.Extensions 8 | @using System.Text.Encodings.Web -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "Group": "Shipping rate computation", 3 | "FriendlyName": "FedEx", 4 | "SystemName": "Shipping.FedEx", 5 | "Version": "4.90.1", 6 | "SupportedVersions": [ "4.90" ], 7 | "Author": "nopCommerce team", 8 | "DisplayOrder": 1, 9 | "FileName": "Nop.Plugin.Shipping.Fedex.dll", 10 | "Description": "This plugin offers shipping rates by FedEx" 11 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/PackingType.cs: -------------------------------------------------------------------------------- 1 | namespace Nop.Plugin.Shipping.Fedex; 2 | 3 | /// 4 | /// Represents a packing type 5 | /// 6 | public enum PackingType 7 | { 8 | /// 9 | /// Pack by dimensions 10 | /// 11 | PackByDimensions = 0, 12 | /// 13 | /// Pack by one item per package 14 | /// 15 | PackByOneItemPerPackage = 1, 16 | /// 17 | /// Pack by volume 18 | /// 19 | PackByVolume = 2 20 | } 21 | -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/FedexShippingDefaults.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core; 2 | 3 | namespace Nop.Plugin.Shipping.Fedex; 4 | 5 | public class FedexShippingDefaults 6 | { 7 | public const decimal MAX_PACKAGE_WEIGHT = 150; 8 | 9 | public const string MEASURE_WEIGHT_SYSTEM_KEYWORD = "lb"; 10 | 11 | public const string MEASURE_DIMENSION_SYSTEM_KEYWORD = "inches"; 12 | 13 | /// 14 | /// Gets a default period (in seconds) before the request times out 15 | /// 16 | public static int RequestTimeout => 15; 17 | 18 | /// 19 | /// Gets the user agent used to request third-party services 20 | /// 21 | public static string UserAgent => $"nopCommerce-{NopVersion.CURRENT_VERSION}"; 22 | 23 | /// 24 | /// Gets the production API URL 25 | /// 26 | public static string ApiUrl => "https://apis.fedex.com"; 27 | } 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | nopCommerce FedEx plugin 2 | =========== 3 | 4 | 5 | [FedEx](https://www.fedex.com/) customers count on our diverse portfolio of transportation, e-commerce, and business solutions. Their air, ground and sea networks cover more than 220 countries and territories, linking more than 99 percent of the world’s GDP. 6 | 7 | More than 300,000 FedEx team members are absolutely, positively focused on safety, the highest ethical and professional standards, and the needs of our customers and communities. 8 | 9 | 10 | ### Features: 11 | 12 | * FedEx shipping, returns, tracking, rating and transit-time estimates 13 | * Direct links to your order management systems for quicker, more accurate shipments 14 | * 24/7 order processing 15 | 16 | 17 | nopCommerce site: [https://www.nopcommerce.com](https://www.nopcommerce.com) 18 | 19 | Listing on nopCommerce "Extensions" catalog: [https://www.nopcommerce.com/shipping-plugin-for-fedex](https://www.nopcommerce.com/shipping-plugin-for-fedex) 20 | 21 | FedEx site: [https://www.fedex.com/](https://www.fedex.com/) 22 | -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/API/Rates/NopRateClient.cs: -------------------------------------------------------------------------------- 1 | namespace Nop.Plugin.Shipping.Fedex.API.Rates; 2 | 3 | public partial class RateClient 4 | { 5 | private readonly FedexSettings _fedexSettings; 6 | private readonly string _accessToken; 7 | 8 | public RateClient(HttpClient httpClient, FedexSettings fedexSettings, string accessToken) : this(httpClient) 9 | { 10 | _fedexSettings = fedexSettings; 11 | _accessToken = accessToken; 12 | 13 | if (!_fedexSettings.UseSandbox) 14 | BaseUrl = FedexShippingDefaults.ApiUrl; 15 | } 16 | 17 | partial void PrepareRequest(HttpClient client, HttpRequestMessage request, string url) 18 | { 19 | client.PrepareRequest(request, _fedexSettings, _accessToken); 20 | } 21 | 22 | public async Task ProcessRateAsync(Full_Schema_Quote_Rate request, string accessToken) 23 | { 24 | var rez = await Rate_and_Transit_timesAsync(request, Guid.NewGuid().ToString(), "application/json", "en_US", $"Bearer {accessToken}"); 25 | 26 | return rez.Output; 27 | } 28 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/API/OAuth/NopOAuthClient.cs: -------------------------------------------------------------------------------- 1 | namespace Nop.Plugin.Shipping.Fedex.API.OAuth; 2 | 3 | public partial class OAuthClient 4 | { 5 | private readonly FedexSettings _fedexSettings; 6 | 7 | public OAuthClient(HttpClient httpClient, FedexSettings fedexSettings) : this(httpClient) 8 | { 9 | _fedexSettings = fedexSettings; 10 | 11 | if (!_fedexSettings.UseSandbox) 12 | BaseUrl = FedexShippingDefaults.ApiUrl; 13 | } 14 | 15 | partial void PrepareRequest(HttpClient client, HttpRequestMessage request, string url) 16 | { 17 | client.PrepareRequest(request, _fedexSettings); 18 | } 19 | 20 | public virtual Task GenerateTokenAsync() 21 | { 22 | return API_AuthorizationAsync("application/x-www-form-urlencoded", new FullSchema 23 | { 24 | Grant_type = "client_credentials", 25 | Client_id = _fedexSettings.ClientId, 26 | Client_secret = _fedexSettings.ClientSecret 27 | }); 28 | } 29 | 30 | partial void ProcessResponse(HttpClient client, HttpResponseMessage response) 31 | { 32 | client.ProcessResponse(response, _fedexSettings); 33 | } 34 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Infrastructure/PluginNopStartup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Nop.Core.Infrastructure; 5 | using Nop.Plugin.Shipping.Fedex.Services; 6 | 7 | namespace Nop.Plugin.Shipping.Fedex.Infrastructure; 8 | 9 | /// 10 | /// Represents object for the configuring services on application startup 11 | /// 12 | public class PluginNopStartup : INopStartup 13 | { 14 | /// 15 | /// Add and configure any of the middleware 16 | /// 17 | /// Collection of service descriptors 18 | /// Configuration of the application 19 | public void ConfigureServices(IServiceCollection services, IConfiguration configuration) 20 | { 21 | services.AddScoped(); 22 | } 23 | 24 | /// 25 | /// Configure the using of added middleware 26 | /// 27 | /// Builder for configuring an application's request pipeline 28 | public void Configure(IApplicationBuilder application) 29 | { 30 | } 31 | 32 | /// 33 | /// Gets order of this startup configuration implementation 34 | /// 35 | public int Order => 1; 36 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Notes.txt: -------------------------------------------------------------------------------- 1 | Important points when developing plugins 2 | 3 | 4 | - All views (cshtml files) and web.config file should have "Build action" set to "Content" and "Copy to output directory" set to "Copy if newer" 5 | 6 | - When you develop a new plugin from scratch, and when a new class library is added to the solution, open its .csproj file (a main project file) in any text editor and replace its content with the following one 7 | 8 | 9 | 10 | net9.0 11 | $(SolutionDir)\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY 12 | $(OutputPath) 13 | 16 | false 17 | enable 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | Replace “PLUGIN_OUTPUT_DIRECTORY” in the code above with your real plugin output directory name. 32 | 33 | It’s not required. But this way we can use a new ASP.NET approach to add third-party references. It was introduced in .NET Core. Furthermore, references from already referenced libraries will be loaded automatically. It’s very convenient. -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/API/Track/NopTrackClient.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Nop.Plugin.Shipping.Fedex.API.Track; 4 | 5 | public partial class TrackClient 6 | { 7 | private FedexSettings _fedexSettings; 8 | private string _accessToken; 9 | 10 | public TrackClient(HttpClient httpClient, FedexSettings fedexSettings, string accessToken) : this(httpClient) 11 | { 12 | _fedexSettings = fedexSettings; 13 | _accessToken = accessToken; 14 | 15 | if (!_fedexSettings.UseSandbox) 16 | BaseUrl = FedexShippingDefaults.ApiUrl; 17 | } 18 | 19 | partial void PrepareRequest(HttpClient client, HttpRequestMessage request, 20 | string url) 21 | { 22 | client.PrepareRequest(request, _fedexSettings, _accessToken); 23 | } 24 | 25 | /// 26 | /// Get tracking info 27 | /// 28 | /// The tracking number 29 | /// 30 | /// A task that represents the asynchronous operation 31 | /// The task result contains the tracking info 32 | /// 33 | public virtual async Task TrackAsync(string trackingNumber, string accessToken) 34 | { 35 | var rez = await Track_by_Tracking_NumberAsync(new Full_Schema_Tracking_Numbers 36 | { 37 | IncludeDetailedScans = true, 38 | TrackingInfo = new List 39 | { 40 | new() 41 | { 42 | TrackingNumberInfo = new TrackingNumberInfo 43 | { 44 | TrackingNumber = trackingNumber 45 | } 46 | } 47 | } 48 | }, Guid.NewGuid().ToString(), "application/json", 49 | "en_US", $"Bearer {accessToken}"); 50 | 51 | return rez.Output; 52 | } 53 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/API/HttpClientExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Net.Http.Headers; 2 | using Nop.Core.Infrastructure; 3 | using Nop.Services.Logging; 4 | 5 | namespace Nop.Plugin.Shipping.Fedex.API; 6 | 7 | public static class HttpClientExtensions 8 | { 9 | public static void PrepareRequest(this HttpClient httpClient, 10 | HttpRequestMessage request, FedexSettings fedexSettings, string accessToken = null) 11 | { 12 | ArgumentNullException.ThrowIfNull(httpClient); 13 | ArgumentNullException.ThrowIfNull(request); 14 | ArgumentNullException.ThrowIfNull(fedexSettings); 15 | 16 | httpClient.Timeout = TimeSpan.FromSeconds(fedexSettings.RequestTimeout ?? FedexShippingDefaults.RequestTimeout); 17 | httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, FedexShippingDefaults.UserAgent); 18 | 19 | if (!string.IsNullOrEmpty(accessToken) && !request.Headers.Contains(HeaderNames.Authorization)) 20 | request.Headers.Add(HeaderNames.Authorization, $"Bearer {accessToken}"); 21 | 22 | //save debug info 23 | if (!fedexSettings.Tracing) 24 | return; 25 | 26 | var logger = EngineContext.Current.Resolve(); 27 | logger.Information($"FedEx rates. Request: {request}{Environment.NewLine}Content: {request.Content?.ReadAsStringAsync().Result}"); 28 | } 29 | 30 | public static void ProcessResponse(this HttpClient httpClient, HttpResponseMessage response, FedexSettings fedexSettings) 31 | { 32 | //save debug info 33 | if (!fedexSettings.Tracing) 34 | return; 35 | 36 | ArgumentNullException.ThrowIfNull(httpClient); 37 | ArgumentNullException.ThrowIfNull(response); 38 | ArgumentNullException.ThrowIfNull(fedexSettings); 39 | 40 | var logger = EngineContext.Current.Resolve(); 41 | logger.Information($"FedEx rates. Response: {response}{Environment.NewLine}Content: {response.Content.ReadAsStringAsync().Result}"); 42 | } 43 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Models/FedexShippingModel.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Rendering; 2 | using Nop.Web.Framework.Models; 3 | using Nop.Web.Framework.Mvc.ModelBinding; 4 | 5 | namespace Nop.Plugin.Shipping.Fedex.Models; 6 | 7 | public record FedexShippingModel : BaseNopModel 8 | { 9 | public FedexShippingModel() 10 | { 11 | CarrierServicesOffered = new List(); 12 | AvailableCarrierServices = new List(); 13 | } 14 | 15 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.AccountNumber")] 16 | public string AccountNumber { get; set; } 17 | 18 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.UseResidentialRates")] 19 | public bool UseResidentialRates { get; set; } 20 | 21 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.ApplyDiscounts")] 22 | public bool ApplyDiscounts { get; set; } 23 | 24 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.AdditionalHandlingCharge")] 25 | public decimal AdditionalHandlingCharge { get; set; } 26 | 27 | public IList CarrierServicesOffered { get; set; } 28 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.CarrierServices")] 29 | public IList AvailableCarrierServices { get; set; } 30 | public string[] CheckedCarrierServices { get; set; } 31 | 32 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.PassDimensions")] 33 | public bool PassDimensions { get; set; } 34 | 35 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.PackingPackageVolume")] 36 | public int PackingPackageVolume { get; set; } 37 | 38 | public int PackingType { get; set; } 39 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.PackingType")] 40 | public SelectList PackingTypeValues { get; set; } 41 | 42 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.ClientId")] 43 | public string ClientId { get; set; } 44 | 45 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.ClientSecret")] 46 | public string ClientSecret { get; set; } 47 | 48 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.UseSandbox")] 49 | public bool UseSandbox { get; set; } 50 | 51 | [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.Tracing")] 52 | public bool Tracing { get; set; } 53 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/FedexSettings.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core.Configuration; 2 | 3 | namespace Nop.Plugin.Shipping.Fedex; 4 | 5 | public class FedexSettings : ISettings 6 | { 7 | /// 8 | /// Gets or sets the account number 9 | /// 10 | public string AccountNumber { get; set; } 11 | 12 | /// 13 | /// Gets or sets a value indicating whether to use residential rates 14 | /// 15 | public bool UseResidentialRates { get; set; } 16 | 17 | /// 18 | /// Gets or sets a value indicating whether to use discounted rates (instead of list rates) 19 | /// 20 | public bool ApplyDiscounts { get; set; } 21 | 22 | /// 23 | /// Gets or sets an amount of the additional handling charge 24 | /// 25 | public decimal AdditionalHandlingCharge { get; set; } 26 | 27 | /// 28 | /// Gets or sets offered carrier services 29 | /// 30 | public string CarrierServicesOffered { get; set; } 31 | 32 | /// 33 | /// Gets or sets a value indicating whether to pass package dimensions 34 | /// 35 | public bool PassDimensions { get; set; } 36 | 37 | /// 38 | /// Gets or sets the packing package volume 39 | /// 40 | public int PackingPackageVolume { get; set; } 41 | 42 | /// 43 | /// Gets or sets packing type 44 | /// 45 | public PackingType PackingType { get; set; } 46 | 47 | /// 48 | /// Gets or sets the client ID 49 | /// 50 | public string ClientId { get; set; } 51 | 52 | /// 53 | /// Gets or sets the client secret 54 | /// 55 | public string ClientSecret { get; set; } 56 | 57 | /// 58 | /// Gets or sets a value indicating whether to use sandbox environment 59 | /// 60 | public bool UseSandbox { get; set; } 61 | 62 | /// 63 | /// Gets or sets a value indicating whether to record plugin tracing in log 64 | /// 65 | public bool Tracing { get; set; } 66 | 67 | /// 68 | /// Gets or sets a period (in seconds) before the request times out 69 | /// 70 | public int? RequestTimeout { get; set; } 71 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Nop.Plugin.Shipping.Fedex.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | Copyright © Nop Solutions, Ltd 6 | Nop Solutions, Ltd 7 | Nop Solutions, Ltd 8 | 9 | https://www.nopcommerce.com/shipping-plugin-for-fedex 10 | https://github.com/nopSolutions/FedEx-plugin-for-nopcommerce 11 | Git 12 | $(SolutionDir)\Presentation\Nop.Web\Plugins\Shipping.Fedex 13 | $(OutputPath) 14 | 17 | false 18 | enable 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | PreserveNewest 31 | 32 | 33 | PreserveNewest 34 | 35 | 36 | PreserveNewest 37 | 38 | 39 | PreserveNewest 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/FedexShipmentTracker.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core.Domain.Shipping; 2 | using Nop.Plugin.Shipping.Fedex.Services; 3 | using Nop.Services.Shipping.Tracking; 4 | 5 | namespace Nop.Plugin.Shipping.Fedex; 6 | 7 | public class FedexShipmentTracker : IShipmentTracker 8 | { 9 | #region Fields 10 | 11 | private readonly FedexService _fedexService; 12 | 13 | #endregion 14 | 15 | #region Ctor 16 | 17 | public FedexShipmentTracker(FedexService fedexService) 18 | { 19 | _fedexService = fedexService; 20 | } 21 | 22 | #endregion 23 | 24 | #region Methods 25 | 26 | /// 27 | /// Gets if the current tracker can track the tracking number. 28 | /// 29 | /// The tracking number to track. 30 | /// 31 | /// A task that represents the asynchronous operation 32 | /// The task result contains the rue if the tracker can track, otherwise false. 33 | /// 34 | public virtual Task IsMatchAsync(string trackingNumber) 35 | { 36 | if (string.IsNullOrWhiteSpace(trackingNumber)) 37 | return Task.FromResult(false); 38 | 39 | //What is a FedEx tracking number format? 40 | return Task.FromResult(false); 41 | } 42 | 43 | /// 44 | /// Get URL for a page to show tracking info (third party tracking page) 45 | /// 46 | /// The tracking number to track 47 | /// Shipment; pass null if the tracking number is not associated with a specific shipment 48 | /// 49 | /// A task that represents the asynchronous operation 50 | /// The task result contains the URL of a tracking page 51 | /// 52 | public virtual Task GetUrlAsync(string trackingNumber, Shipment shipment = null) 53 | { 54 | return Task.FromResult($"https://www.fedex.com/apps/fedextrack/?action=track&tracknumbers={trackingNumber}"); 55 | } 56 | 57 | /// 58 | /// Get all shipment events 59 | /// 60 | /// The tracking number to track 61 | /// Shipment; pass null if the tracking number is not associated with a specific shipment 62 | /// 63 | /// A task that represents the asynchronous operation 64 | /// The task result contains the list of shipment events 65 | /// 66 | public virtual async Task> GetShipmentEventsAsync(string trackingNumber, Shipment shipment = null) 67 | { 68 | if (string.IsNullOrEmpty(trackingNumber)) 69 | return new List(); 70 | 71 | return await _fedexService.GetShipmentEventsAsync(trackingNumber); 72 | } 73 | 74 | #endregion 75 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Visual Studio 3 | ################# 4 | 5 | ## Ignore Visual Studio temporary files, build results, and 6 | ## files generated by popular Visual Studio add-ons. 7 | 8 | # User-specific files 9 | *.suo 10 | *.user 11 | *.sln.docstates 12 | 13 | # Build results 14 | 15 | .vs/ 16 | [Dd]ebug/ 17 | [Rr]elease/ 18 | x64/ 19 | [Bb]in/ 20 | [Oo]bj/ 21 | 22 | # MSTest test Results 23 | [Tt]est[Rr]esult*/ 24 | [Bb]uild[Ll]og.* 25 | 26 | *_i.c 27 | *_p.c 28 | *.ilk 29 | *.meta 30 | *.obj 31 | *.pch 32 | *.pdb 33 | *.pgc 34 | *.pgd 35 | *.rsp 36 | *.sbr 37 | *.tlb 38 | *.tli 39 | *.tlh 40 | *.tmp 41 | *.tmp_proj 42 | *.log 43 | *.vspscc 44 | *.vssscc 45 | .builds 46 | *.pidb 47 | *.log 48 | *.scc 49 | 50 | # Visual C++ cache files 51 | ipch/ 52 | *.aps 53 | *.ncb 54 | *.opensdf 55 | *.sdf 56 | *.cachefile 57 | 58 | # Visual Studio profiler 59 | *.psess 60 | *.vsp 61 | *.vspx 62 | 63 | # Guidance Automation Toolkit 64 | *.gpState 65 | 66 | # ReSharper is a .NET coding add-in 67 | _ReSharper*/ 68 | *.[Rr]e[Ss]harper 69 | 70 | # TeamCity is a build add-in 71 | _TeamCity* 72 | 73 | # DotCover is a Code Coverage Tool 74 | *.dotCover 75 | 76 | # NCrunch 77 | *.ncrunch* 78 | .*crunch*.local.xml 79 | 80 | # Installshield output folder 81 | [Ee]xpress/ 82 | 83 | # DocProject is a documentation generator add-in 84 | DocProject/buildhelp/ 85 | DocProject/Help/*.HxT 86 | DocProject/Help/*.HxC 87 | DocProject/Help/*.hhc 88 | DocProject/Help/*.hhk 89 | DocProject/Help/*.hhp 90 | DocProject/Help/Html2 91 | DocProject/Help/html 92 | 93 | # Click-Once directory 94 | publish/ 95 | 96 | # Publish Web Output 97 | *.Publish.xml 98 | *.pubxml 99 | 100 | # NuGet Packages Directory 101 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 102 | #packages/ 103 | 104 | # Windows Azure Build Output 105 | csx 106 | *.build.csdef 107 | 108 | # Windows Store app package directory 109 | AppPackages/ 110 | 111 | # Others 112 | sql/ 113 | *.Cache 114 | ClientBin/ 115 | [Ss]tyle[Cc]op.* 116 | ~$* 117 | *~ 118 | *.dbmdl 119 | *.[Pp]ublish.xml 120 | *.pfx 121 | *.publishsettings 122 | 123 | # RIA/Silverlight projects 124 | Generated_Code/ 125 | 126 | # Backup & report files from converting an old project file to a newer 127 | # Visual Studio version. Backup files are not needed, because we have git ;-) 128 | _UpgradeReport_Files/ 129 | Backup*/ 130 | UpgradeLog*.XML 131 | UpgradeLog*.htm 132 | 133 | # SQL Server files 134 | App_Data/*.mdf 135 | App_Data/*.ldf 136 | 137 | ############# 138 | ## Windows detritus 139 | ############# 140 | 141 | # Windows image file caches 142 | Thumbs.db 143 | ehthumbs.db 144 | 145 | # Folder config file 146 | Desktop.ini 147 | 148 | # Recycle Bin used on file shares 149 | $RECYCLE.BIN/ 150 | 151 | # Mac crap 152 | .DS_Store 153 | 154 | 155 | ####################### 156 | ## nopCommerce specific 157 | ########### 158 | glob:*.user 159 | *.patch 160 | *.hg 161 | src/Presentation/Nop.Web/Plugins/* 162 | src/Presentation/Nop.Web/Content/Images/Thumbs/* 163 | src/Presentation/Nop.Web/App_Data/InstalledPlugins.txt 164 | src/Presentation/Nop.Web/App_Data/Settings.txt -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Migrations/UpgradeTo470.cs: -------------------------------------------------------------------------------- 1 | using FluentMigrator; 2 | using Nop.Data.Migrations; 3 | using Nop.Services.Configuration; 4 | using Nop.Services.Localization; 5 | 6 | namespace Nop.Plugin.Shipping.Fedex.Migrations; 7 | 8 | [NopMigration("2024-07-11 20:00:00", "Shipping.Fedex Update to v4.70.2 (migrate to RestFull API)", MigrationProcessType.Update)] 9 | public class UpgradeTo470 : Migration 10 | { 11 | private readonly ILocalizationService _localizationService; 12 | private readonly ISettingService _settingService; 13 | 14 | public UpgradeTo470(ILocalizationService localizationService, 15 | ISettingService settingService) 16 | { 17 | _localizationService = localizationService; 18 | _settingService = settingService; 19 | } 20 | 21 | public override void Up() 22 | { 23 | _localizationService.DeleteLocaleResources(new[] 24 | { 25 | "Plugins.Shipping.Fedex.Fields.Password", 26 | "Plugins.Shipping.Fedex.Fields.Password.Hint", 27 | "Plugins.Shipping.Fedex.Fields.Key", 28 | "Plugins.Shipping.Fedex.Fields.Key.Hint", 29 | "Plugins.Shipping.Fedex.Fields.MeterNumber", 30 | "Plugins.Shipping.Fedex.Fields.MeterNumber.Hint", 31 | "Plugins.Shipping.Fedex.Fields.Url", 32 | "Plugins.Shipping.Fedex.Fields.Url.Hint", 33 | "Plugins.Shipping.Fedex.Fields.DropoffType", 34 | "Plugins.Shipping.Fedex.Fields.DropoffType.Hint", 35 | "Enums.Nop.Plugin.Shipping.Fedex.DropoffType.BusinessServiceCenter", 36 | "Enums.Nop.Plugin.Shipping.Fedex.DropoffType.DropBox", 37 | "Enums.Nop.Plugin.Shipping.Fedex.DropoffType.RegularPickup", 38 | "Enums.Nop.Plugin.Shipping.Fedex.DropoffType.RequestCourier", 39 | "Enums.Nop.Plugin.Shipping.Fedex.DropoffType.Station", 40 | "Enums.Nop.Plugin.Shipping.Fedex.PackingType.PackByDimensions", 41 | "Enums.Nop.Plugin.Shipping.Fedex.PackingType.PackByOneItemPerPackage", 42 | "Enums.Nop.Plugin.Shipping.Fedex.PackingType.PackByVolume" 43 | }); 44 | 45 | _localizationService.AddOrUpdateLocaleResource(new Dictionary 46 | { 47 | ["Plugins.Shipping.Fedex.Fields.ClientId"] = "Client ID", 48 | ["Plugins.Shipping.Fedex.Fields.ClientId.Hint"] = "Specify FedEx client ID.", 49 | ["Plugins.Shipping.Fedex.Fields.ClientSecret"] = "Client secret", 50 | ["Plugins.Shipping.Fedex.Fields.ClientSecret.Hint"] = "Specify FedEx client secret.", 51 | ["Plugins.Shipping.Fedex.Fields.Tracing"] = "Tracing", 52 | ["Plugins.Shipping.Fedex.Fields.Tracing.Hint"] = "Check if you want to record plugin tracing in System Log. Warning: The entire request and response will be logged (including Client Id/secret, AccountNumber). Do not leave this enabled in a production environment.", 53 | ["Plugins.Shipping.Fedex.Fields.UseSandbox"] = "Use sandbox", 54 | ["Plugins.Shipping.Fedex.Fields.UseSandbox.Hint"] = "Check to use sandbox (testing environment).", 55 | }); 56 | 57 | var setting = _settingService.LoadSetting(); 58 | 59 | if (!_settingService.SettingExists(setting, settings => settings.RequestTimeout)) 60 | { 61 | setting.RequestTimeout = FedexShippingDefaults.RequestTimeout; 62 | _settingService.SaveSetting(setting, settings => settings.RequestTimeout); 63 | } 64 | 65 | var key = _settingService.GetSetting("fedexsettings.key"); 66 | 67 | if (key is not null) 68 | _settingService.DeleteSetting(key); 69 | 70 | var password = _settingService.GetSetting("fedexsettings.password"); 71 | 72 | if (password is not null) 73 | _settingService.DeleteSetting(password); 74 | 75 | var meterNumber = _settingService.GetSetting("fedexsettings.meternumber"); 76 | 77 | if (meterNumber is not null) 78 | _settingService.DeleteSetting(meterNumber); 79 | 80 | var url = _settingService.GetSetting("fedexsettings.url"); 81 | 82 | if (url is not null) 83 | _settingService.DeleteSetting(url); 84 | 85 | var dropoffType = _settingService.GetSetting("fedexsettings.dropofftype"); 86 | 87 | if (dropoffType is not null) 88 | _settingService.DeleteSetting(dropoffType); 89 | } 90 | 91 | public override void Down() 92 | { 93 | //add the downgrade logic if necessary 94 | } 95 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Controllers/ShippingFedexController.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Nop.Plugin.Shipping.Fedex.Models; 4 | using Nop.Plugin.Shipping.Fedex.Services; 5 | using Nop.Services; 6 | using Nop.Services.Configuration; 7 | using Nop.Services.Localization; 8 | using Nop.Services.Messages; 9 | using Nop.Services.Security; 10 | using Nop.Web.Framework; 11 | using Nop.Web.Framework.Controllers; 12 | using Nop.Web.Framework.Mvc.Filters; 13 | 14 | namespace Nop.Plugin.Shipping.Fedex.Controllers; 15 | 16 | [Area(AreaNames.ADMIN)] 17 | [AuthorizeAdmin] 18 | [AutoValidateAntiforgeryToken] 19 | public class ShippingFedexController : BasePluginController 20 | { 21 | #region Fields 22 | 23 | private readonly FedexSettings _fedexSettings; 24 | private readonly ILocalizationService _localizationService; 25 | private readonly INotificationService _notificationService; 26 | private readonly ISettingService _settingService; 27 | 28 | #endregion 29 | 30 | #region Ctor 31 | 32 | public ShippingFedexController(FedexSettings fedexSettings, 33 | ILocalizationService localizationService, 34 | INotificationService notificationService, 35 | ISettingService settingService) 36 | { 37 | _fedexSettings = fedexSettings; 38 | _localizationService = localizationService; 39 | _notificationService = notificationService; 40 | _settingService = settingService; 41 | } 42 | 43 | #endregion 44 | 45 | #region Methods 46 | 47 | [CheckPermission(StandardPermission.Orders.SHIPMENTS_VIEW)] 48 | public async Task Configure() 49 | { 50 | var model = new FedexShippingModel 51 | { 52 | UseSandbox = _fedexSettings.UseSandbox, 53 | ClientId = _fedexSettings.ClientId, 54 | ClientSecret = _fedexSettings.ClientSecret, 55 | AccountNumber = _fedexSettings.AccountNumber, 56 | Tracing = _fedexSettings.Tracing, 57 | UseResidentialRates = _fedexSettings.UseResidentialRates, 58 | ApplyDiscounts = _fedexSettings.ApplyDiscounts, 59 | AdditionalHandlingCharge = _fedexSettings.AdditionalHandlingCharge, 60 | PackingPackageVolume = _fedexSettings.PackingPackageVolume, 61 | PackingType = Convert.ToInt32(_fedexSettings.PackingType), 62 | PackingTypeValues = await _fedexSettings.PackingType.ToSelectListAsync(), 63 | PassDimensions = _fedexSettings.PassDimensions 64 | }; 65 | 66 | // Load service names 67 | var availableServices = FedexService.GetAllFedExServicesName(); 68 | model.AvailableCarrierServices = availableServices; 69 | 70 | if (!string.IsNullOrEmpty(_fedexSettings.CarrierServicesOffered)) 71 | foreach (var service in availableServices) 72 | { 73 | var serviceId = FedexService.GetFedExServiceId(service); 74 | 75 | if (!string.IsNullOrEmpty(serviceId) && _fedexSettings.CarrierServicesOffered.Contains(serviceId)) 76 | model.CarrierServicesOffered.Add(service); 77 | } 78 | 79 | return View("~/Plugins/Shipping.Fedex/Views/Configure.cshtml", model); 80 | } 81 | 82 | [HttpPost] 83 | [CheckPermission(StandardPermission.Orders.SHIPMENTS_CREATE_EDIT_DELETE)] 84 | public async Task Configure(FedexShippingModel model) 85 | { 86 | if (!ModelState.IsValid) 87 | return await Configure(); 88 | 89 | //save settings 90 | _fedexSettings.ClientId = model.ClientId; 91 | _fedexSettings.ClientSecret = model.ClientSecret; 92 | _fedexSettings.UseSandbox = model.UseSandbox; 93 | _fedexSettings.AccountNumber = model.AccountNumber; 94 | _fedexSettings.Tracing = model.Tracing; 95 | _fedexSettings.UseResidentialRates = model.UseResidentialRates; 96 | _fedexSettings.ApplyDiscounts = model.ApplyDiscounts; 97 | _fedexSettings.AdditionalHandlingCharge = model.AdditionalHandlingCharge; 98 | _fedexSettings.PackingPackageVolume = model.PackingPackageVolume; 99 | _fedexSettings.PackingType = (PackingType)model.PackingType; 100 | _fedexSettings.PassDimensions = model.PassDimensions; 101 | 102 | // Save selected services 103 | var carrierServicesOfferedDomestic = new StringBuilder(); 104 | var carrierServicesDomesticSelectedCount = 0; 105 | 106 | if (model.CheckedCarrierServices != null) 107 | foreach (var cs in model.CheckedCarrierServices) 108 | { 109 | carrierServicesDomesticSelectedCount++; 110 | var serviceId = FedexService.GetFedExServiceId(cs); 111 | 112 | if (!string.IsNullOrEmpty(serviceId)) 113 | carrierServicesOfferedDomestic.AppendFormat("{0}:", serviceId); 114 | } 115 | 116 | // Add default options if no services were selected 117 | _fedexSettings.CarrierServicesOffered = carrierServicesDomesticSelectedCount == 0 ? "FEDEX_2_DAY:PRIORITY_OVERNIGHT:FEDEX_GROUND:GROUND_HOME_DELIVERY:INTERNATIONAL_ECONOMY" : carrierServicesOfferedDomestic.ToString(); 118 | 119 | await _settingService.SaveSettingAsync(_fedexSettings); 120 | 121 | _notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.Plugins.Saved")); 122 | 123 | return await Configure(); 124 | } 125 | 126 | #endregion 127 | } 128 | -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Views/Configure.cshtml: -------------------------------------------------------------------------------- 1 | @model FedexShippingModel; 2 | 3 | @using Nop.Plugin.Shipping.Fedex.Models; 4 | @using Nop.Plugin.Shipping.Fedex; 5 | 6 | @{ 7 | Layout = "_ConfigurePlugin"; 8 | } 9 | 10 |
11 | 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 | @foreach (var csd in Model.AvailableCarrierServices) 106 | { 107 |
108 | 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 |
-------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/FedexComputationMethod.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // Contributor(s): mb, New York. 3 | //------------------------------------------------------------------------------ 4 | 5 | using Nop.Core; 6 | using Nop.Plugin.Shipping.Fedex.Services; 7 | using Nop.Services.Configuration; 8 | using Nop.Services.Localization; 9 | using Nop.Services.Plugins; 10 | using Nop.Services.Shipping; 11 | using Nop.Services.Shipping.Tracking; 12 | 13 | namespace Nop.Plugin.Shipping.Fedex; 14 | 15 | /// 16 | /// Fedex computation method 17 | /// 18 | public class FedexComputationMethod : BasePlugin, IShippingRateComputationMethod 19 | { 20 | #region Fields 21 | 22 | private readonly FedexService _fedexService; 23 | private readonly ILocalizationService _localizationService; 24 | private readonly ISettingService _settingService; 25 | private readonly IWebHelper _webHelper; 26 | 27 | #endregion 28 | 29 | #region Ctor 30 | 31 | public FedexComputationMethod(FedexService fedexService, 32 | ILocalizationService localizationService, 33 | ISettingService settingService, 34 | IWebHelper webHelper) 35 | { 36 | _fedexService = fedexService; 37 | _localizationService = localizationService; 38 | _settingService = settingService; 39 | _webHelper = webHelper; 40 | } 41 | 42 | #endregion 43 | 44 | #region Methods 45 | 46 | /// 47 | /// Gets available shipping options 48 | /// 49 | /// A request for getting shipping options 50 | /// 51 | /// A task that represents the asynchronous operation 52 | /// The task result contains the represents a response of getting shipping rate options 53 | /// 54 | public async Task GetShippingOptionsAsync(GetShippingOptionRequest getShippingOptionRequest) 55 | { 56 | ArgumentNullException.ThrowIfNull(getShippingOptionRequest); 57 | 58 | if (!getShippingOptionRequest.Items?.Any() ?? true) 59 | return new GetShippingOptionResponse { Errors = new[] { "No shipment items" } }; 60 | 61 | if (getShippingOptionRequest.ShippingAddress?.CountryId is null) 62 | return new GetShippingOptionResponse { Errors = new[] { "Shipping address is not set" } }; 63 | 64 | return await _fedexService.GetRatesAsync(getShippingOptionRequest); 65 | } 66 | 67 | /// 68 | /// Gets fixed shipping rate (if shipping rate computation method allows it and the rate can be calculated before checkout). 69 | /// 70 | /// A request for getting shipping options 71 | /// 72 | /// A task that represents the asynchronous operation 73 | /// The task result contains the fixed shipping rate; or null in case there's no fixed shipping rate 74 | /// 75 | public Task GetFixedRateAsync(GetShippingOptionRequest getShippingOptionRequest) 76 | { 77 | return Task.FromResult(null); 78 | } 79 | 80 | /// 81 | /// Gets a configuration page URL 82 | /// 83 | public override string GetConfigurationPageUrl() 84 | { 85 | return $"{_webHelper.GetStoreLocation()}Admin/ShippingFedex/Configure"; 86 | } 87 | 88 | /// 89 | /// Install plugin 90 | /// 91 | /// A task that represents the asynchronous operation 92 | public override async Task InstallAsync() 93 | { 94 | //settings 95 | var settings = new FedexSettings 96 | { 97 | PackingPackageVolume = 5184 98 | }; 99 | await _settingService.SaveSettingAsync(settings); 100 | 101 | //locales 102 | await _localizationService.AddOrUpdateLocaleResourceAsync(new Dictionary 103 | { 104 | ["Plugins.Shipping.Fedex.Fields.ClientId"] = "Client ID", 105 | ["Plugins.Shipping.Fedex.Fields.ClientId.Hint"] = "Specify FedEx client ID.", 106 | ["Plugins.Shipping.Fedex.Fields.ClientSecret"] = "Client secret", 107 | ["Plugins.Shipping.Fedex.Fields.ClientSecret.Hint"] = "Specify FedEx client secret.", 108 | ["Plugins.Shipping.Fedex.Fields.Tracing"] = "Tracing", 109 | ["Plugins.Shipping.Fedex.Fields.Tracing.Hint"] = "Check if you want to record plugin tracing in System Log. Warning: The entire request and response will be logged (including Client Id/secret, AccountNumber). Do not leave this enabled in a production environment.", 110 | ["Plugins.Shipping.Fedex.Fields.UseSandbox"] = "Use sandbox", 111 | ["Plugins.Shipping.Fedex.Fields.UseSandbox.Hint"] = "Check to use sandbox (testing environment).", 112 | ["Plugins.Shipping.Fedex.Fields.AccountNumber"] = "Account number", 113 | ["Plugins.Shipping.Fedex.Fields.AccountNumber.Hint"] = "Specify FedEx account number.", 114 | ["Plugins.Shipping.Fedex.Fields.UseResidentialRates"] = "Use residential rates", 115 | ["Plugins.Shipping.Fedex.Fields.UseResidentialRates.Hint"] = "Check to use residential rates.", 116 | ["Plugins.Shipping.Fedex.Fields.ApplyDiscounts"] = "Use discounted rates", 117 | ["Plugins.Shipping.Fedex.Fields.ApplyDiscounts.Hint"] = "Check to use discounted rates (instead of list rates).", 118 | ["Plugins.Shipping.Fedex.Fields.AdditionalHandlingCharge"] = "Additional handling charge", 119 | ["Plugins.Shipping.Fedex.Fields.AdditionalHandlingCharge.Hint"] = "Enter additional handling fee to charge your customers.", 120 | ["Plugins.Shipping.Fedex.Fields.CarrierServices"] = "Carrier Services Offered", 121 | ["Plugins.Shipping.Fedex.Fields.CarrierServices.Hint"] = "Select the services you want to offer to customers.", 122 | ["Plugins.Shipping.Fedex.Fields.PassDimensions"] = "Pass dimensions", 123 | ["Plugins.Shipping.Fedex.Fields.PassDimensions.Hint"] = "Check if you want to pass package dimensions when requesting rates.", 124 | ["Plugins.Shipping.Fedex.Fields.PackingType"] = "Packing type", 125 | ["Plugins.Shipping.Fedex.Fields.PackingType.Hint"] = "Choose preferred packing type.", 126 | ["Plugins.Shipping.Fedex.Fields.PackingPackageVolume"] = "Package volume", 127 | ["Plugins.Shipping.Fedex.Fields.PackingPackageVolume.Hint"] = "Enter your package volume.", 128 | }); 129 | 130 | await base.InstallAsync(); 131 | } 132 | 133 | /// 134 | /// Uninstall plugin 135 | /// 136 | /// A task that represents the asynchronous operation 137 | public override async Task UninstallAsync() 138 | { 139 | //settings 140 | await _settingService.DeleteSettingAsync(); 141 | 142 | //locales 143 | await _localizationService.DeleteLocaleResourcesAsync("Plugins.Shipping.Fedex.Fields"); 144 | await _localizationService.DeleteLocaleResourcesAsync("Enums.Nop.Plugin.Shipping.Fedex"); 145 | 146 | await base.UninstallAsync(); 147 | } 148 | 149 | /// 150 | /// Get associated shipment tracker 151 | /// 152 | /// 153 | /// A task that represents the asynchronous operation 154 | /// The task result contains the shipment tracker 155 | /// 156 | public Task GetShipmentTrackerAsync() 157 | { 158 | return Task.FromResult(new FedexShipmentTracker(_fedexService)); 159 | } 160 | 161 | #endregion 162 | } -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/API/OAuth/OAuthClient.cs: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // Generated using the NSwag toolchain v14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) 4 | // 5 | //---------------------- 6 | 7 | #pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." 8 | #pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." 9 | #pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' 10 | #pragma warning disable 612 // Disable "CS0612 '...' is obsolete" 11 | #pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... 12 | #pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." 13 | #pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" 14 | #pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" 15 | #pragma warning disable 8603 // Disable "CS8603 Possible null reference return" 16 | #pragma warning disable 8604 // Disable "CS8604 Possible null reference argument for parameter" 17 | #pragma warning disable 8625 // Disable "CS8625 Cannot convert null literal to non-nullable reference type" 18 | #pragma warning disable CS8765 // Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes). 19 | 20 | namespace Nop.Plugin.Shipping.Fedex.API.OAuth 21 | { 22 | using System = global::System; 23 | 24 | [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 25 | public partial class OAuthClient 26 | { 27 | #pragma warning disable 8618 28 | private string _baseUrl; 29 | #pragma warning restore 8618 30 | 31 | private System.Net.Http.HttpClient _httpClient; 32 | private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true); 33 | 34 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 35 | public OAuthClient(System.Net.Http.HttpClient httpClient) 36 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 37 | { 38 | BaseUrl = "https://apis-sandbox.fedex.com"; 39 | _httpClient = httpClient; 40 | } 41 | 42 | private static Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings() 43 | { 44 | var settings = new Newtonsoft.Json.JsonSerializerSettings(); 45 | UpdateJsonSerializerSettings(settings); 46 | return settings; 47 | } 48 | 49 | public string BaseUrl 50 | { 51 | get { return _baseUrl; } 52 | set 53 | { 54 | _baseUrl = value; 55 | if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/")) 56 | _baseUrl += '/'; 57 | } 58 | } 59 | 60 | protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _settings.Value; } } 61 | 62 | static partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings); 63 | 64 | partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); 65 | partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); 66 | partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); 67 | 68 | /// 69 | /// API Authorization 70 | /// 71 | /// 72 | /// Use this endpoint to request the OAuth token (bearer token) to authorize your application to access FedEx resources. You can pass this bearer token in your subsequent individual FedEx API endpoint requests.<br/><i>Note: FedEx APIs do not support Cross-Origin Resource Sharing (CORS) mechanism.</i> 73 | /// 74 | /// This is used to indicate the media type of the resource. The media type is a string sent along with the file indicating format of the file.<br> Example: application/x-www-form-urlencoded 75 | /// Success 76 | /// A server side error occurred. 77 | public virtual System.Threading.Tasks.Task API_AuthorizationAsync(string content_type, FullSchema body) 78 | { 79 | return API_AuthorizationAsync(content_type, body, System.Threading.CancellationToken.None); 80 | } 81 | 82 | /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. 83 | /// 84 | /// API Authorization 85 | /// 86 | /// 87 | /// Use this endpoint to request the OAuth token (bearer token) to authorize your application to access FedEx resources. You can pass this bearer token in your subsequent individual FedEx API endpoint requests.<br/><i>Note: FedEx APIs do not support Cross-Origin Resource Sharing (CORS) mechanism.</i> 88 | /// 89 | /// This is used to indicate the media type of the resource. The media type is a string sent along with the file indicating format of the file.<br> Example: application/x-www-form-urlencoded 90 | /// Success 91 | /// A server side error occurred. 92 | public virtual async System.Threading.Tasks.Task API_AuthorizationAsync(string content_type, FullSchema body, System.Threading.CancellationToken cancellationToken) 93 | { 94 | if (body == null) 95 | throw new System.ArgumentNullException("body"); 96 | 97 | var client_ = _httpClient; 98 | var disposeClient_ = false; 99 | try 100 | { 101 | using (var request_ = new System.Net.Http.HttpRequestMessage()) 102 | { 103 | 104 | if (content_type == null) 105 | throw new System.ArgumentNullException("content_type"); 106 | request_.Headers.TryAddWithoutValidation("content-type", ConvertToString(content_type, System.Globalization.CultureInfo.InvariantCulture)); 107 | var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value); 108 | var dictionary_ = Newtonsoft.Json.JsonConvert.DeserializeObject>(json_, _settings.Value); 109 | var content_ = new System.Net.Http.FormUrlEncodedContent(dictionary_); 110 | content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); 111 | request_.Content = content_; 112 | request_.Method = new System.Net.Http.HttpMethod("POST"); 113 | request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); 114 | 115 | var urlBuilder_ = new System.Text.StringBuilder(); 116 | if (!string.IsNullOrEmpty(_baseUrl)) 117 | urlBuilder_.Append(_baseUrl); 118 | // Operation Path: "oauth/token" 119 | urlBuilder_.Append("oauth/token"); 120 | 121 | PrepareRequest(client_, request_, urlBuilder_); 122 | 123 | var url_ = urlBuilder_.ToString(); 124 | request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); 125 | 126 | PrepareRequest(client_, request_, url_); 127 | 128 | var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); 129 | var disposeResponse_ = true; 130 | try 131 | { 132 | var headers_ = new System.Collections.Generic.Dictionary>(); 133 | foreach (var item_ in response_.Headers) 134 | headers_[item_.Key] = item_.Value; 135 | if (response_.Content != null && response_.Content.Headers != null) 136 | { 137 | foreach (var item_ in response_.Content.Headers) 138 | headers_[item_.Key] = item_.Value; 139 | } 140 | 141 | ProcessResponse(client_, response_); 142 | 143 | var status_ = (int)response_.StatusCode; 144 | if (status_ == 200) 145 | { 146 | var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); 147 | if (objectResponse_.Object == null) 148 | { 149 | throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); 150 | } 151 | return objectResponse_.Object; 152 | } 153 | else 154 | if (status_ == 401) 155 | { 156 | var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); 157 | if (objectResponse_.Object == null) 158 | { 159 | throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); 160 | } 161 | throw new ApiException("Unauthorized", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); 162 | } 163 | else 164 | if (status_ == 500) 165 | { 166 | var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); 167 | if (objectResponse_.Object == null) 168 | { 169 | throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); 170 | } 171 | throw new ApiException("Failure", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); 172 | } 173 | else 174 | if (status_ == 503) 175 | { 176 | var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); 177 | if (objectResponse_.Object == null) 178 | { 179 | throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); 180 | } 181 | throw new ApiException("Service Unavailable", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); 182 | } 183 | else 184 | { 185 | var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); 186 | throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); 187 | } 188 | } 189 | finally 190 | { 191 | if (disposeResponse_) 192 | response_.Dispose(); 193 | } 194 | } 195 | } 196 | finally 197 | { 198 | if (disposeClient_) 199 | client_.Dispose(); 200 | } 201 | } 202 | 203 | protected struct ObjectResponseResult 204 | { 205 | public ObjectResponseResult(T responseObject, string responseText) 206 | { 207 | this.Object = responseObject; 208 | this.Text = responseText; 209 | } 210 | 211 | public T Object { get; } 212 | 213 | public string Text { get; } 214 | } 215 | 216 | public bool ReadResponseAsString { get; set; } 217 | 218 | protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) 219 | { 220 | if (response == null || response.Content == null) 221 | { 222 | return new ObjectResponseResult(default(T), string.Empty); 223 | } 224 | 225 | if (ReadResponseAsString) 226 | { 227 | var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); 228 | try 229 | { 230 | var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); 231 | return new ObjectResponseResult(typedBody, responseText); 232 | } 233 | catch (Newtonsoft.Json.JsonException exception) 234 | { 235 | var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; 236 | throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception); 237 | } 238 | } 239 | else 240 | { 241 | try 242 | { 243 | using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) 244 | using (var streamReader = new System.IO.StreamReader(responseStream)) 245 | using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) 246 | { 247 | var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); 248 | var typedBody = serializer.Deserialize(jsonTextReader); 249 | return new ObjectResponseResult(typedBody, string.Empty); 250 | } 251 | } 252 | catch (Newtonsoft.Json.JsonException exception) 253 | { 254 | var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; 255 | throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception); 256 | } 257 | } 258 | } 259 | 260 | private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) 261 | { 262 | if (value == null) 263 | { 264 | return ""; 265 | } 266 | 267 | if (value is System.Enum) 268 | { 269 | var name = System.Enum.GetName(value.GetType(), value); 270 | if (name != null) 271 | { 272 | var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); 273 | if (field != null) 274 | { 275 | var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) 276 | as System.Runtime.Serialization.EnumMemberAttribute; 277 | if (attribute != null) 278 | { 279 | return attribute.Value != null ? attribute.Value : name; 280 | } 281 | } 282 | 283 | var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); 284 | return converted == null ? string.Empty : converted; 285 | } 286 | } 287 | else if (value is bool) 288 | { 289 | return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); 290 | } 291 | else if (value is byte[]) 292 | { 293 | return System.Convert.ToBase64String((byte[])value); 294 | } 295 | else if (value is string[]) 296 | { 297 | return string.Join(",", (string[])value); 298 | } 299 | else if (value.GetType().IsArray) 300 | { 301 | var valueArray = (System.Array)value; 302 | var valueTextArray = new string[valueArray.Length]; 303 | for (var i = 0; i < valueArray.Length; i++) 304 | { 305 | valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); 306 | } 307 | return string.Join(",", valueTextArray); 308 | } 309 | 310 | var result = System.Convert.ToString(value, cultureInfo); 311 | return result == null ? "" : result; 312 | } 313 | } 314 | 315 | /// 316 | /// The request elements for OAuth API. 317 | /// 318 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 319 | public partial class FullSchema 320 | { 321 | /// 322 | /// Specify Type of customer requesting the Oauth token.<br>Valid Values: client_credentials, csp_credentials, client_pc_credentials<br>Note:<br>client_credentials - should be used for customers and brand new Compatible Provider customers who are yet to unboard child accounts.<br>csp_credentials - should be used for Compatible Provider customers with existing child accounts.<br>client_pc_credentials – should be used for Proprietary Parent Child customers. 323 | /// 324 | [Newtonsoft.Json.JsonProperty("grant_type", Required = Newtonsoft.Json.Required.Always)] 325 | [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] 326 | public string Grant_type { get; set; } 327 | 328 | /// 329 | /// Specify the Client ID also known as API Key received during FedEx Developer portal registration.<br>Example: XXXX-XXX-XXXX-XXX 330 | /// 331 | [Newtonsoft.Json.JsonProperty("client_id", Required = Newtonsoft.Json.Required.Always)] 332 | [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] 333 | public string Client_id { get; set; } 334 | 335 | /// 336 | /// Specify the Client secret also known as Secret Key received during FedEx Developer portal registration.<br>Example: XXXX-XXX-XXXX-XXX 337 | /// 338 | [Newtonsoft.Json.JsonProperty("client_secret", Required = Newtonsoft.Json.Required.Always)] 339 | [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] 340 | public string Client_secret { get; set; } 341 | 342 | /// 343 | /// Specify the Client ID also known as Customer Key. This element is used as a login credential for a Compatible customer or a Proprietary Parent Child customer to access the application on behalf of their customer.<br>Example: XXXX-XXX-XXXX-XXX<br>Note: This element should be used by Compatible and Proprietary Parent Child customers. 344 | /// 345 | [Newtonsoft.Json.JsonProperty("child_Key", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 346 | public string Child_Key { get; set; } 347 | 348 | /// 349 | /// Specify the Client secret also known as Customer Secret. This element is used as a login credential for a Compatible customer or a Proprietary Parent Child customer to access the application on behalf of their customer.<br>Example: XXXX-XXX-XXXX-XXX<br>Note: This element should be used by Compatible and Proprietary Parent Child customers. 350 | /// 351 | [Newtonsoft.Json.JsonProperty("child_secret", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 352 | public string Child_secret { get; set; } 353 | } 354 | 355 | /// 356 | /// This is the response of OAuth token and having access token details. 357 | /// 358 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 359 | public partial class Response 360 | { 361 | /// 362 | /// This is an encrypted OAuth token used to authenticate your API requests. Use it in the authorization header of your API requests.<br>Example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX…… 363 | /// 364 | [Newtonsoft.Json.JsonProperty("access_token", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 365 | public string Access_token { get; set; } 366 | 367 | /// 368 | /// This is a token type. In this case, it is 'bearer authentication'. 369 | /// 370 | [Newtonsoft.Json.JsonProperty("token_type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 371 | public string Token_type { get; set; } 372 | 373 | /// 374 | /// Indicates the token expiration time in seconds. The standard token expiration time is one hour. <br>Example: 3600 375 | /// 376 | [Newtonsoft.Json.JsonProperty("expires_in", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 377 | public int Expires_in { get; set; } 378 | 379 | /// 380 | /// Indicates the scope of authorization provided to the consumer.<br> Example: CXS 381 | /// 382 | [Newtonsoft.Json.JsonProperty("scope", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 383 | public string Scope { get; set; } 384 | } 385 | 386 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 387 | public partial class ErrorResponseVO 388 | { 389 | /// 390 | /// The transaction ID is a special set of numbers that defines each transaction.<br>Example: bc95c0e4-b33e-42a2-80d2-334282b5d37a 391 | /// 392 | [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 393 | public string TransactionId { get; set; } 394 | 395 | /// 396 | /// Indicates error details when suspicious files, potential exploits and viruses are found while scanning files, directories and user accounts. This includes code, message and error parameters. 397 | /// 398 | [Newtonsoft.Json.JsonProperty("errors", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 399 | public System.Collections.Generic.ICollection Errors { get; set; } 400 | } 401 | 402 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 403 | public partial class CXSError 404 | { 405 | /// 406 | /// Indicates the error code.<br>Example: NOT.FOUND.ERROR 407 | /// 408 | [Newtonsoft.Json.JsonProperty("code", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 409 | public string Code { get; set; } 410 | 411 | /// 412 | /// List of parameters which indicates the properties of the alert message. 413 | /// 414 | [Newtonsoft.Json.JsonProperty("parameterList", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 415 | public System.Collections.Generic.ICollection ParameterList { get; set; } 416 | 417 | /// 418 | /// Indicates the API error alert message.<br>Example: We are unable to process this request. Please try again later or contact FedEx Customer Service. 419 | /// 420 | [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 421 | public string Message { get; set; } 422 | } 423 | 424 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 425 | public partial class Parameter 426 | { 427 | /// 428 | /// Indicates the error option to be applied. 429 | /// 430 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 431 | public string Value { get; set; } 432 | 433 | /// 434 | /// Indicates the value associated with the key. 435 | /// 436 | [Newtonsoft.Json.JsonProperty("key", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 437 | public string Key { get; set; } 438 | } 439 | 440 | 441 | 442 | [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 443 | public partial class ApiException : System.Exception 444 | { 445 | public int StatusCode { get; private set; } 446 | 447 | public string Response { get; private set; } 448 | 449 | public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } 450 | 451 | public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) 452 | : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) 453 | { 454 | StatusCode = statusCode; 455 | Response = response; 456 | Headers = headers; 457 | } 458 | 459 | public override string ToString() 460 | { 461 | return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); 462 | } 463 | } 464 | 465 | [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")] 466 | public partial class ApiException : ApiException 467 | { 468 | public TResult Result { get; private set; } 469 | 470 | public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) 471 | : base(message, statusCode, response, headers, innerException) 472 | { 473 | Result = result; 474 | } 475 | } 476 | 477 | } 478 | 479 | #pragma warning restore 108 480 | #pragma warning restore 114 481 | #pragma warning restore 472 482 | #pragma warning restore 612 483 | #pragma warning restore 1573 484 | #pragma warning restore 1591 485 | #pragma warning restore 8073 486 | #pragma warning restore 3016 487 | #pragma warning restore 8603 488 | #pragma warning restore 8604 489 | #pragma warning restore 8625 -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Nop.Plugin.Shipping.Fedex/Services/FedexService.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Globalization; 3 | using System.Net; 4 | using Nop.Core; 5 | using Nop.Core.Domain.Directory; 6 | using Nop.Core.Domain.Orders; 7 | using Nop.Core.Domain.Shipping; 8 | using Nop.Core.Http; 9 | using Nop.Plugin.Shipping.Fedex.API.OAuth; 10 | using Nop.Plugin.Shipping.Fedex.API.Rates; 11 | using Nop.Plugin.Shipping.Fedex.API.Track; 12 | using Nop.Services.Catalog; 13 | using Nop.Services.Customers; 14 | using Nop.Services.Directory; 15 | using Nop.Services.Logging; 16 | using Nop.Services.Orders; 17 | using Nop.Services.Shipping; 18 | using Nop.Services.Shipping.Tracking; 19 | 20 | namespace Nop.Plugin.Shipping.Fedex.Services; 21 | 22 | public class FedexService 23 | { 24 | #region Fields 25 | 26 | private static readonly Dictionary _fedexServices; 27 | 28 | private readonly CurrencySettings _currencySettings; 29 | private readonly FedexSettings _fedexSettings; 30 | private readonly ICountryService _countryService; 31 | private readonly ICurrencyService _currencyService; 32 | private readonly ICustomerService _customerService; 33 | private readonly IHttpClientFactory _httpClientFactory; 34 | private readonly ILogger _logger; 35 | private readonly IMeasureService _measureService; 36 | private readonly IOrderTotalCalculationService _orderTotalCalculationService; 37 | private readonly IProductService _productService; 38 | private readonly IShippingService _shippingService; 39 | private readonly IStateProvinceService _stateProvinceService; 40 | private readonly IWorkContext _workContext; 41 | 42 | private string _accessToken; 43 | 44 | #endregion 45 | 46 | #region Ctor 47 | 48 | static FedexService() 49 | { 50 | _fedexServices = new Dictionary(comparer: StringComparer.InvariantCultureIgnoreCase) 51 | { 52 | ["EUROPE_FIRST_INTERNATIONAL_PRIORITY"] = "FedEx Europe First International Priority", 53 | ["FEDEX_1_DAY_FREIGHT"] = "FedEx 1Day Freight", 54 | ["FEDEX_2_DAY"] = "FedEx 2Day", 55 | ["FEDEX_2_DAY_FREIGHT"] = "FedEx 2Day Freight", 56 | ["FEDEX_3_DAY_FREIGHT"] = "FedEx 3Day Freight", 57 | ["FEDEX_EXPRESS_SAVER"] = "FedEx Express Saver", 58 | ["FEDEX_GROUND"] = "FedEx Ground", 59 | ["FIRST_OVERNIGHT"] = "FedEx First Overnight", 60 | ["GROUND_HOME_DELIVERY"] = "FedEx Ground Home Delivery", 61 | ["FEDEX_INTERNATIONAL_CONNECT_PLUS"] = "FedEx International Connect Plus", 62 | ["INTERNATIONAL_DISTRIBUTION_FREIGHT"] = "FedEx International Distribution Freight", 63 | ["INTERNATIONAL_ECONOMY"] = "FedEx International Economy", 64 | ["INTERNATIONAL_ECONOMY_DISTRIBUTION"] = "FedEx International Economy Distribution", 65 | ["INTERNATIONAL_ECONOMY_FREIGHT"] = "FedEx International Economy Freight", 66 | ["INTERNATIONAL_FIRST"] = "FedEx International First", 67 | ["INTERNATIONAL_PRIORITY"] = "FedEx International Priority", 68 | ["INTERNATIONAL_PRIORITY_FREIGHT"] = "FedEx International Priority Freight", 69 | ["PRIORITY_OVERNIGHT"] = "FedEx Priority Overnight", 70 | ["SMART_POST"] = "FedEx Ground Economy (SmartPost)", 71 | ["STANDARD_OVERNIGHT"] = "FedEx Standard Overnight", 72 | ["FEDEX_FREIGHT"] = "FedEx Freight", 73 | ["FEDEX_NATIONAL_FREIGHT"] = "FedEx National Freight" 74 | }; 75 | } 76 | public FedexService(CurrencySettings currencySettings, 77 | FedexSettings fedexSettings, 78 | ICountryService countryService, 79 | ICurrencyService currencyService, 80 | ICustomerService customerService, 81 | IHttpClientFactory httpClientFactory, 82 | ILogger logger, 83 | IMeasureService measureService, 84 | IOrderTotalCalculationService orderTotalCalculationService, 85 | IProductService productService, 86 | IShippingService shippingService, 87 | IStateProvinceService stateProvinceService, 88 | IWorkContext workContext) 89 | { 90 | _currencySettings = currencySettings; 91 | _fedexSettings = fedexSettings; 92 | _countryService = countryService; 93 | _currencyService = currencyService; 94 | _customerService = customerService; 95 | _httpClientFactory = httpClientFactory; 96 | _logger = logger; 97 | _measureService = measureService; 98 | _orderTotalCalculationService = orderTotalCalculationService; 99 | _productService = productService; 100 | _shippingService = shippingService; 101 | _stateProvinceService = stateProvinceService; 102 | _workContext = workContext; 103 | } 104 | 105 | #endregion 106 | 107 | #region Utilities 108 | 109 | private async Task ConvertChargeToPrimaryCurrencyAsync(double chargeAmount, string chargeCurrency, Currency requestedShipmentCurrency) 110 | { 111 | var primaryStoreCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId); 112 | 113 | var amount = new decimal(chargeAmount); 114 | 115 | if (primaryStoreCurrency.CurrencyCode.Equals(chargeCurrency, StringComparison.InvariantCultureIgnoreCase)) 116 | return amount; 117 | 118 | var amountCurrency = chargeCurrency == requestedShipmentCurrency.CurrencyCode ? requestedShipmentCurrency : await _currencyService.GetCurrencyByCodeAsync(chargeCurrency); 119 | 120 | //ensure the currency exists; otherwise, presume that it was primary store currency 121 | amountCurrency ??= primaryStoreCurrency; 122 | 123 | amount = await _currencyService.ConvertToPrimaryStoreCurrencyAsync(amount, amountCurrency); 124 | 125 | Debug.WriteLine($"ConvertChargeToPrimaryCurrency - from {chargeAmount} ({chargeCurrency}) to {amount} ({primaryStoreCurrency.CurrencyCode})"); 126 | 127 | return amount; 128 | } 129 | 130 | /// 131 | /// Get dimensions values of the package 132 | /// 133 | /// Package items 134 | /// Minimal rate 135 | /// 136 | /// A task that represents the asynchronous operation 137 | /// The task result contains the dimensions values 138 | /// 139 | private async Task<(int width, int length, int height)> GetDimensionsAsync(IList items, int minRate = 1) 140 | { 141 | var measureDimension = await _measureService.GetMeasureDimensionBySystemKeywordAsync(FedexShippingDefaults.MEASURE_DIMENSION_SYSTEM_KEYWORD) ?? 142 | throw new NopException($"FedEx shipping service. Could not load \"{FedexShippingDefaults.MEASURE_DIMENSION_SYSTEM_KEYWORD}\" measure dimension"); 143 | 144 | var (width, length, height) = await _shippingService.GetDimensionsAsync(items, true); 145 | var rezWidth = await convertAndRoundDimension(width); 146 | var rezLength = await convertAndRoundDimension(length); 147 | var rezHeight = await convertAndRoundDimension(height); 148 | 149 | return (rezWidth, rezLength, rezHeight); 150 | 151 | #region Local functions 152 | 153 | async Task convertAndRoundDimension(decimal dimension) 154 | { 155 | dimension = await _measureService.ConvertFromPrimaryMeasureDimensionAsync(dimension, measureDimension); 156 | var rezDimension = Convert.ToInt32(Math.Ceiling(dimension)); 157 | 158 | return Math.Max(rezDimension, minRate); 159 | } 160 | 161 | #endregion 162 | } 163 | 164 | /// 165 | /// Get dimensions values of the single shopping cart item 166 | /// 167 | /// Shopping cart item 168 | /// 169 | /// A task that represents the asynchronous operation 170 | /// The task result contains the dimensions values 171 | /// 172 | private async Task<(int width, int length, int height)> GetDimensionsForSingleItemAsync(ShoppingCartItem item) 173 | { 174 | var product = await _productService.GetProductByIdAsync(item.ProductId); 175 | 176 | var items = new[] { new GetShippingOptionRequest.PackageItem(item, product, 1) }; 177 | 178 | return await GetDimensionsAsync(items); 179 | } 180 | 181 | /// 182 | /// Get weight value of the package 183 | /// 184 | /// Shipping option request 185 | /// Minimal rate 186 | /// 187 | /// A task that represents the asynchronous operation 188 | /// The task result contains the weight value 189 | /// 190 | private async Task GetWeightAsync(GetShippingOptionRequest shippingOptionRequest, int minRate = 1) 191 | { 192 | var measureWeight = await _measureService.GetMeasureWeightBySystemKeywordAsync(FedexShippingDefaults.MEASURE_WEIGHT_SYSTEM_KEYWORD) ?? 193 | throw new NopException($"FedEx shipping service. Could not load \"{FedexShippingDefaults.MEASURE_WEIGHT_SYSTEM_KEYWORD}\" measure weight"); 194 | 195 | var weight = await _shippingService.GetTotalWeightAsync(shippingOptionRequest, ignoreFreeShippedItems: true); 196 | weight = await _measureService.ConvertFromPrimaryMeasureWeightAsync(weight, measureWeight); 197 | weight = Convert.ToInt32(Math.Ceiling(weight)); 198 | return Math.Max(weight, minRate); 199 | } 200 | 201 | /// 202 | /// Get weight value of the single shopping cart item 203 | /// 204 | /// Shopping cart item 205 | /// 206 | /// A task that represents the asynchronous operation 207 | /// The task result contains the weight value 208 | /// 209 | private async Task GetWeightForSingleItemAsync(ShoppingCartItem item) 210 | { 211 | var customer = await _customerService.GetCustomerByIdAsync(item.CustomerId); 212 | var product = await _productService.GetProductByIdAsync(item.ProductId); 213 | 214 | var shippingOptionRequest = new GetShippingOptionRequest 215 | { 216 | Customer = customer, 217 | Items = new[] { new GetShippingOptionRequest.PackageItem(item, product, 1) } 218 | }; 219 | 220 | return await GetWeightAsync(shippingOptionRequest); 221 | } 222 | 223 | /// 224 | /// Get access token 225 | /// 226 | /// The asynchronous task whose result contains access token 227 | private async Task GetAccessTokenAsync() 228 | { 229 | if (!string.IsNullOrEmpty(_accessToken)) 230 | return _accessToken; 231 | 232 | if (string.IsNullOrEmpty(_fedexSettings.ClientId)) 233 | throw new NopException("Client ID is not set"); 234 | 235 | if (string.IsNullOrEmpty(_fedexSettings.ClientSecret)) 236 | throw new NopException("Client secret is not set"); 237 | 238 | var client = new OAuthClient(_httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient), _fedexSettings); 239 | 240 | var response = await client.GenerateTokenAsync(); 241 | _accessToken = response.Access_token; 242 | 243 | return _accessToken; 244 | } 245 | 246 | /// 247 | /// Create request details to track shipment 248 | /// 249 | /// Tracking number 250 | /// Track request details 251 | private async Task CreateTrackRequestAsync(string trackingNumber) 252 | { 253 | var client = new TrackClient(_httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient), _fedexSettings, await GetAccessTokenAsync()); 254 | 255 | var trackResponse = await client.TrackAsync(trackingNumber, await GetAccessTokenAsync()); 256 | 257 | return trackResponse; 258 | } 259 | 260 | /// 261 | /// Create package details 262 | /// 263 | /// Width 264 | /// Length 265 | /// Height 266 | /// Weight 267 | /// 268 | /// Currency code 269 | /// Package details 270 | private RequestedPackageLineItem CreatePackage(int width, int length, int height, decimal weight, decimal orderSubTotal, string currencyCode) 271 | { 272 | return new RequestedPackageLineItem 273 | { 274 | GroupPackageCount = 1, 275 | Weight = new() 276 | { 277 | Units = "LB", 278 | Value = (double)weight, 279 | }, // package weight 280 | 281 | Dimensions = new() 282 | { 283 | Length = _fedexSettings.PassDimensions ? length : 0, 284 | Width = _fedexSettings.PassDimensions ? width : 0, 285 | Height = _fedexSettings.PassDimensions ? height : 0, 286 | Units = "IN", 287 | }, // package dimensions 288 | DeclaredValue = new Money 289 | { 290 | Amount = (double)orderSubTotal, 291 | Currency = currencyCode 292 | } // insured value 293 | }; 294 | } 295 | 296 | /// 297 | /// Create request details to get shipping rates 298 | /// 299 | /// Shipping option request 300 | /// 301 | /// A task that represents the asynchronous operation 302 | /// The task result contains the rate request details 303 | /// 304 | private async Task<(Full_Schema_Quote_Rate rateRequest, Currency requestedShipmentCurrency)> CreateRateRequestAsync(GetShippingOptionRequest shippingOptionRequest) 305 | { 306 | // Build the RateRequest 307 | var request = new Full_Schema_Quote_Rate 308 | { 309 | AccountNumber = new AccountNumber { Value = _fedexSettings.AccountNumber }, 310 | RateRequestControlParameters = new() { ReturnTransitTimes = true }, 311 | CarrierCodes = new List { "FDXE", "FDXG", "FXSP" } 312 | }; 313 | 314 | var (_, _, _, subTotalWithDiscountBase, _) = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync( 315 | shippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(), 316 | false); 317 | 318 | request.RequestedShipment = new RequestedShipment 319 | { 320 | RateRequestType = new List 321 | { 322 | RateRequestType.LIST, 323 | RateRequestType.PREFERRED 324 | } 325 | }; 326 | 327 | SetOrigin(request, shippingOptionRequest); 328 | await SetDestinationAsync(request, shippingOptionRequest); 329 | 330 | var requestedShipmentCurrency = await GetRequestedShipmentCurrencyAsync( 331 | request.RequestedShipment.Shipper.Address.CountryCode, // origin 332 | request.RequestedShipment.Recipient.Address.CountryCode); // destination 333 | 334 | decimal subTotalShipmentCurrency; 335 | var primaryStoreCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId); 336 | 337 | if (requestedShipmentCurrency.CurrencyCode == primaryStoreCurrency.CurrencyCode) 338 | subTotalShipmentCurrency = subTotalWithDiscountBase; 339 | else 340 | subTotalShipmentCurrency = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(subTotalWithDiscountBase, requestedShipmentCurrency); 341 | 342 | Debug.WriteLine($"SubTotal (Primary Currency) : {subTotalWithDiscountBase} ({primaryStoreCurrency.CurrencyCode})"); 343 | Debug.WriteLine($"SubTotal (Shipment Currency): {subTotalShipmentCurrency} ({requestedShipmentCurrency.CurrencyCode})"); 344 | 345 | SetShipmentDetails(request, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode); 346 | SetPayment(request); 347 | 348 | //set packages details 349 | switch (_fedexSettings.PackingType) 350 | { 351 | case PackingType.PackByOneItemPerPackage: 352 | await SetIndividualPackageLineItemsOneItemPerPackageAsync(request, shippingOptionRequest, requestedShipmentCurrency.CurrencyCode); 353 | break; 354 | case PackingType.PackByVolume: 355 | await SetIndividualPackageLineItemsCubicRootDimensionsAsync(request, shippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode); 356 | break; 357 | case PackingType.PackByDimensions: 358 | default: 359 | await SetIndividualPackageLineItemsAsync(request, shippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode); 360 | break; 361 | } 362 | return (request, requestedShipmentCurrency); 363 | } 364 | 365 | private async Task GetRequestedShipmentCurrencyAsync(string originCountryCode, string destinCountryCode) 366 | { 367 | var primaryStoreCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId); 368 | 369 | //The solution coded here might be considered a bit of a hack 370 | //it only supports the scenario for US / Canada / India shipping 371 | //because nopCommerce does not have a concept of a designated currency for a Country. 372 | var originCurrencyCode = getCurrencyCode(originCountryCode); 373 | var destinCurrencyCode = getCurrencyCode(destinCountryCode); 374 | 375 | //when neither the shipping origin's currency or the destinations currency is the same as the store primary currency, 376 | //FedEx would complain that "There are no valid services available. (code: 556)". 377 | if (originCurrencyCode == primaryStoreCurrency.CurrencyCode || destinCurrencyCode == primaryStoreCurrency.CurrencyCode) 378 | return primaryStoreCurrency; 379 | 380 | //ensure that this currency exists 381 | return await _currencyService.GetCurrencyByCodeAsync(originCurrencyCode) ?? primaryStoreCurrency; 382 | 383 | #region Local functions 384 | 385 | string getCurrencyCode(string countryCode) 386 | { 387 | return countryCode switch 388 | { 389 | "US" => "USD", 390 | "CA" => "CAD", 391 | "IN" => "INR", 392 | _ => primaryStoreCurrency.CurrencyCode 393 | }; 394 | } 395 | 396 | #endregion 397 | } 398 | 399 | private async Task> ParseResponseAsync(BaseProcessOutputVO reply, Currency requestedShipmentCurrency) 400 | { 401 | var result = new List(); 402 | 403 | Debug.WriteLine("RateReply details:"); 404 | Debug.WriteLine("**********************************************************"); 405 | foreach (var rateDetail in reply.RateReplyDetails) 406 | { 407 | var shippingOption = new ShippingOption(); 408 | var serviceName = GetFedExServiceName(rateDetail.ServiceType); 409 | 410 | // Skip the current service if services are selected and this service hasn't been selected 411 | if (!string.IsNullOrEmpty(_fedexSettings.CarrierServicesOffered) && !_fedexSettings.CarrierServicesOffered.Contains(rateDetail.ServiceType)) 412 | continue; 413 | 414 | Debug.WriteLine("ServiceType: " + rateDetail.ServiceType); 415 | if (!serviceName.Equals("UNKNOWN")) 416 | { 417 | shippingOption.Name = serviceName; 418 | 419 | foreach (var shipmentDetail in rateDetail.RatedShipmentDetails) 420 | { 421 | Debug.WriteLine("RateType : " + shipmentDetail.RateType); 422 | Debug.WriteLine("Total Billing Weight : " + shipmentDetail.ShipmentRateDetail.TotalBillingWeight.Value); 423 | Debug.WriteLine("Total Base Charge : " + shipmentDetail.TotalBaseCharge); 424 | Debug.WriteLine("Total Discount : " + shipmentDetail.TotalDiscounts); 425 | Debug.WriteLine("Total Surcharges : " + shipmentDetail.ShipmentRateDetail.TotalSurcharges); 426 | Debug.WriteLine($"Net Charge : {shipmentDetail.TotalNetCharge}"); 427 | Debug.WriteLine("*********"); 428 | 429 | // get discounted rates if option is selected 430 | if (_fedexSettings.ApplyDiscounts & 431 | (shipmentDetail.RateType == RatedShipmentDetailRateType.ACCOUNT)) 432 | { 433 | var amount = await ConvertChargeToPrimaryCurrencyAsync(shipmentDetail.TotalNetCharge, shipmentDetail.ShipmentRateDetail.Currency, requestedShipmentCurrency); 434 | shippingOption.Rate = amount + _fedexSettings.AdditionalHandlingCharge; 435 | break; 436 | } 437 | 438 | // get List Rates (not discount rates) 439 | if (shipmentDetail.RateType == RatedShipmentDetailRateType.LIST) 440 | { 441 | var amount = await ConvertChargeToPrimaryCurrencyAsync(shipmentDetail.TotalNetCharge, shipmentDetail.ShipmentRateDetail.Currency, requestedShipmentCurrency); 442 | shippingOption.Rate = amount + _fedexSettings.AdditionalHandlingCharge; 443 | break; 444 | } 445 | } 446 | 447 | result.Add(shippingOption); 448 | } 449 | Debug.WriteLine("**********************************************************"); 450 | } 451 | 452 | return result; 453 | } 454 | 455 | private async Task SetDestinationAsync(Full_Schema_Quote_Rate request, GetShippingOptionRequest getShippingOptionRequest) 456 | { 457 | request.RequestedShipment.Recipient = new RateParty 458 | { 459 | Address = new RateAddress() 460 | }; 461 | 462 | if (_fedexSettings.UseResidentialRates) 463 | request.RequestedShipment.Recipient.Address.Residential = true; 464 | 465 | request.RequestedShipment.Recipient.Address.City = getShippingOptionRequest.ShippingAddress.City; 466 | 467 | var recipientCountryCode = (await _countryService.GetCountryByAddressAsync(getShippingOptionRequest.ShippingAddress))?.TwoLetterIsoCode ?? string.Empty; 468 | 469 | if (await _stateProvinceService.GetStateProvinceByAddressAsync(getShippingOptionRequest.ShippingAddress) is { } stateProvince && 470 | IncludeStateProvinceCode(recipientCountryCode)) 471 | request.RequestedShipment.Recipient.Address.StateOrProvinceCode = stateProvince.Abbreviation; 472 | else 473 | request.RequestedShipment.Recipient.Address.StateOrProvinceCode = string.Empty; 474 | 475 | request.RequestedShipment.Recipient.Address.PostalCode = getShippingOptionRequest.ShippingAddress.ZipPostalCode; 476 | request.RequestedShipment.Recipient.Address.CountryCode = recipientCountryCode; 477 | } 478 | 479 | /// 480 | /// Create packages (total dimensions of shopping cart items determines number of packages) 481 | /// 482 | /// Shipping request 483 | /// Shipping option request 484 | /// 485 | /// Currency code 486 | /// A task that represents the asynchronous operation 487 | private async Task SetIndividualPackageLineItemsAsync(Full_Schema_Quote_Rate request, GetShippingOptionRequest getShippingOptionRequest, decimal orderSubTotal, string currencyCode) 488 | { 489 | var (length, height, width) = await GetDimensionsAsync(getShippingOptionRequest.Items); 490 | var weight = await GetWeightAsync(getShippingOptionRequest); 491 | 492 | if (!IsPackageTooHeavy(weight) && !IsPackageTooLarge(length, height, width)) 493 | { 494 | request.RequestedShipment.TotalPackageCount = 1; 495 | 496 | var package = CreatePackage(width, length, height, weight, orderSubTotal, currencyCode); 497 | package.GroupPackageCount = 1; 498 | 499 | request.RequestedShipment.RequestedPackageLineItems = new[] { package }; 500 | } 501 | else 502 | { 503 | var totalPackagesDims = 1; 504 | var totalPackagesWeights = 1; 505 | if (IsPackageTooHeavy(weight)) 506 | totalPackagesWeights = Convert.ToInt32(Math.Ceiling(weight / FedexShippingDefaults.MAX_PACKAGE_WEIGHT)); 507 | 508 | if (IsPackageTooLarge(length, height, width)) 509 | totalPackagesDims = Convert.ToInt32(Math.Ceiling(TotalPackageSize(length, height, width) / 108M)); 510 | 511 | var totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; 512 | 513 | if (totalPackages == 0) 514 | totalPackages = 1; 515 | 516 | width = Math.Max(width / totalPackages, 1); 517 | length = Math.Max(length / totalPackages, 1); 518 | height = Math.Max(height / totalPackages, 1); 519 | weight = Math.Max(weight / totalPackages, 1); 520 | 521 | var orderSubTotal2 = orderSubTotal / totalPackages; 522 | 523 | request.RequestedShipment.TotalPackageCount = totalPackages; 524 | 525 | request.RequestedShipment.RequestedPackageLineItems = Enumerable.Range(1, totalPackages - 1) 526 | .Select(_ => CreatePackage(width, length, height, weight, orderSubTotal2, currencyCode)).ToArray(); 527 | } 528 | } 529 | 530 | /// 531 | /// Create packages (total volume of shopping cart items determines number of packages) 532 | /// 533 | /// Shipping request 534 | /// Shipping option request 535 | /// 536 | /// Currency code 537 | /// A task that represents the asynchronous operation 538 | private async Task SetIndividualPackageLineItemsCubicRootDimensionsAsync(Full_Schema_Quote_Rate request, GetShippingOptionRequest getShippingOptionRequest, decimal orderSubTotal, string currencyCode) 539 | { 540 | //From FedEx Guide (Ground): 541 | //Dimensional weight is based on volume (the amount of space a package 542 | //occupies in relation to its actual weight). If the cubic size of your FedEx 543 | //Ground package measures three cubic feet (5,184 cubic inches or 84,951 544 | //cubic centimetres) or greater, you will be charged the greater of the 545 | //dimensional weight or the actual weight. 546 | //A package weighing 150 lbs. (68 kg) or less and measuring greater than 547 | //130 inches (330 cm) in combined length and girth will be classified by 548 | //FedEx Ground as an “Oversize” package. All packages must have a 549 | //combined length and girth of no more than 165 inches (419 cm). An 550 | //oversize charge of $30 per package will also apply to any package 551 | //measuring greater than 130 inches (330 cm) in combined length and 552 | //girth. 553 | //Shipping charges for packages smaller than three cubic feet are based 554 | //on actual weight 555 | 556 | // Dimensional Weight applies to packages with volume 5,184 cubic inches or more 557 | // cube root(5184) = 17.3 558 | 559 | // Packages that exceed 130 inches in length and girth (2xHeight + 2xWidth) 560 | // are considered “oversize” packages. 561 | // Assume a cube (H=W=L) of that size: 130 = D + (2xD + 2xD) = 5xD : D = 130/5 = 26 562 | // 26x26x26 = 17,576 563 | // Avoid oversize by using 25" 564 | // 25x25x25 = 15,625 565 | 566 | // Which is less $ - multiple small packages, or one large package using dimensional weight 567 | // 15,625 / 5184 = 3.014 = 3 packages 568 | // Ground for total weight: 60lbs 15lbs 569 | // 3 packages 17x17x17 (20 lbs each) = $66.21 39.39 570 | // 1 package 25x25x25 (60 lbs) = $71.70 71.70 571 | 572 | var totalPackagesDims = 1; 573 | int length; 574 | int height; 575 | int width; 576 | 577 | if (getShippingOptionRequest.Items.Count == 1 && getShippingOptionRequest.Items[0].GetQuantity() == 1) 578 | { 579 | //get dimensions and weight of the single cubic size of package 580 | var item = getShippingOptionRequest.Items.First().ShoppingCartItem; 581 | (width, length, height) = await GetDimensionsForSingleItemAsync(item); 582 | } 583 | else 584 | { 585 | //or try to get them 586 | var dimension = 0; 587 | 588 | //get total volume of the package 589 | var totalVolume = await getShippingOptionRequest.Items.SumAwaitAsync(async item => 590 | { 591 | //get dimensions and weight of the single item 592 | var (itemWidth, itemLength, itemHeight) = await GetDimensionsForSingleItemAsync(item.ShoppingCartItem); 593 | return item.GetQuantity() * itemWidth * itemLength * itemHeight; 594 | }); 595 | 596 | if (totalVolume > decimal.Zero) 597 | { 598 | //use default value (in cubic inches) if not specified 599 | var packageVolume = _fedexSettings.PackingPackageVolume; 600 | if (packageVolume <= 0) 601 | packageVolume = 5184; 602 | 603 | //calculate cube root (floor) 604 | dimension = Convert.ToInt32(Math.Floor(Math.Pow(Convert.ToDouble(packageVolume), 1.0 / 3.0))); 605 | if (IsPackageTooLarge(dimension, dimension, dimension)) 606 | throw new NopException("fedexSettings.PackingPackageVolume exceeds max package size"); 607 | 608 | //adjust package volume for dimensions calculated 609 | packageVolume = dimension * dimension * dimension; 610 | 611 | totalPackagesDims = Convert.ToInt32(Math.Ceiling(totalVolume / packageVolume)); 612 | } 613 | 614 | width = length = height = dimension; 615 | } 616 | 617 | width = Math.Max(width, 1); 618 | length = Math.Max(length, 1); 619 | height = Math.Max(height, 1); 620 | 621 | var weight = await GetWeightAsync(getShippingOptionRequest); 622 | 623 | var totalPackagesWeights = 1; 624 | if (IsPackageTooHeavy(weight)) 625 | totalPackagesWeights = Convert.ToInt32(Math.Ceiling(weight / FedexShippingDefaults.MAX_PACKAGE_WEIGHT)); 626 | 627 | var totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; 628 | 629 | var orderSubTotalPerPackage = orderSubTotal / totalPackages; 630 | var weightPerPackage = weight / totalPackages; 631 | 632 | request.RequestedShipment.TotalPackageCount = totalPackages; 633 | 634 | request.RequestedShipment.RequestedPackageLineItems = Enumerable.Range(1, totalPackages) 635 | .Select(_ => CreatePackage(width, length, height, weightPerPackage, orderSubTotalPerPackage, currencyCode)) 636 | .ToArray(); 637 | } 638 | 639 | /// 640 | /// Create packages (each shopping cart item is a separate package) 641 | /// 642 | /// Shipping request 643 | /// Shipping option request 644 | /// Currency code 645 | /// A task that represents the asynchronous operation 646 | private async Task SetIndividualPackageLineItemsOneItemPerPackageAsync(Full_Schema_Quote_Rate request, GetShippingOptionRequest getShippingOptionRequest, string currencyCode) 647 | { 648 | // Rate request setup - each Shopping Cart Item is a separate package 649 | var i = 1; 650 | var items = getShippingOptionRequest.Items; 651 | var totalItems = items.Sum(x => x.GetQuantity()); 652 | 653 | request.RequestedShipment.TotalPackageCount = totalItems; 654 | request.RequestedShipment.RequestedPackageLineItems = await getShippingOptionRequest.Items.SelectManyAwait(async packageItem => 655 | { 656 | //get dimensions and weight of the single item 657 | var (width, length, height) = await GetDimensionsForSingleItemAsync(packageItem.ShoppingCartItem); 658 | var weight = await GetWeightForSingleItemAsync(packageItem.ShoppingCartItem); 659 | 660 | var product = await _productService.GetProductByIdAsync(packageItem.ShoppingCartItem.ProductId); 661 | var package = CreatePackage(width, length, height, weight, product.Price, currencyCode); 662 | package.GroupPackageCount = 1; 663 | 664 | var packs = Enumerable.Range(i, packageItem.GetQuantity()) 665 | .Select(_ => CreatePackage(width, length, height, weight, product.Price, currencyCode)).ToArray(); 666 | i += packageItem.GetQuantity(); 667 | 668 | return packs; 669 | }).ToArrayAsync(); 670 | } 671 | 672 | private void SetPayment(Full_Schema_Quote_Rate request) 673 | { 674 | request.RequestedShipment.CustomsClearanceDetail = new RequestedShipmentCustomsClearanceDetail 675 | { 676 | DutiesPayment = new Payment 677 | { 678 | PaymentType = PaymentType.SENDER, // Payment options are RECIPIENT, SENDER, THIRD_PARTY 679 | Payor = new Payor 680 | { 681 | ResponsibleParty = new ResponsibleParty 682 | { 683 | AccountNumber = new AccountNumber 684 | { 685 | Value = _fedexSettings.AccountNumber 686 | } 687 | } 688 | } 689 | } 690 | }; 691 | } 692 | 693 | private void SetShipmentDetails(Full_Schema_Quote_Rate request, decimal orderSubTotal, string currencyCode) 694 | { 695 | //saturday pickup is available for certain FedEx Express U.S. service types: 696 | //http://www.fedex.com/us/developer/product/WebServices/MyWebHelp/Services/Options/c_SaturdayShipAndDeliveryServiceDetails.html 697 | //if the customer orders on a Saturday, the rate calculation will use Saturday as the shipping date, and the rates will include a Saturday pickup surcharge 698 | //more info: https://www.nopcommerce.com/boards/t/27348/fedex-rate-can-be-excessive-for-express-methods-if-calculated-on-a-saturday.aspx 699 | var shipTimestamp = DateTime.Now; 700 | 701 | if (shipTimestamp.DayOfWeek == DayOfWeek.Saturday) 702 | shipTimestamp = shipTimestamp.AddDays(2); 703 | 704 | request.RequestedShipment.ShipDateStamp = shipTimestamp.ToString("yyyy-MM-dd"); // Shipping date and time 705 | 706 | //for India domestic shipping add additional details 707 | if (request.RequestedShipment.Shipper.Address.CountryCode.Equals("IN", StringComparison.InvariantCultureIgnoreCase) && 708 | request.RequestedShipment.Recipient.Address.CountryCode.Equals("IN", StringComparison.InvariantCultureIgnoreCase)) 709 | { 710 | var commodity = new Commodity 711 | { 712 | Name = "1", 713 | NumberOfPieces = 1, 714 | CustomsValue = new Money 715 | { 716 | Amount = (double)orderSubTotal, 717 | Currency = currencyCode 718 | } 719 | }; 720 | 721 | request.RequestedShipment.CustomsClearanceDetail = new RequestedShipmentCustomsClearanceDetail 722 | { 723 | CommercialInvoice = new CommercialInvoice 724 | { 725 | ShipmentPurpose = CommercialInvoiceShipmentPurpose.SOLD 726 | }, 727 | Commodities = new[] { commodity } 728 | }; 729 | } 730 | } 731 | 732 | private static bool IsPackageTooHeavy(decimal weight) 733 | { 734 | return weight > FedexShippingDefaults.MAX_PACKAGE_WEIGHT; 735 | } 736 | 737 | private static bool IsPackageTooLarge(decimal length, decimal height, decimal width) 738 | { 739 | return TotalPackageSize(length, height, width) > 165; 740 | } 741 | 742 | private static bool IncludeStateProvinceCode(string countryCode) 743 | { 744 | return (countryCode.Equals("US", StringComparison.InvariantCultureIgnoreCase) || 745 | countryCode.Equals("CA", StringComparison.InvariantCultureIgnoreCase)); 746 | } 747 | 748 | private static void SetOrigin(Full_Schema_Quote_Rate request, GetShippingOptionRequest getShippingOptionRequest) 749 | { 750 | request.RequestedShipment.Shipper = new RateParty 751 | { 752 | Address = new RateAddress() 753 | }; 754 | 755 | if (getShippingOptionRequest.CountryFrom is null) 756 | throw new Exception("FROM country is not specified"); 757 | 758 | request.RequestedShipment.Shipper.Address.City = getShippingOptionRequest.CityFrom; 759 | if (IncludeStateProvinceCode(getShippingOptionRequest.CountryFrom.TwoLetterIsoCode)) 760 | { 761 | var stateProvinceAbbreviation = getShippingOptionRequest.StateProvinceFrom?.Abbreviation ?? ""; 762 | request.RequestedShipment.Shipper.Address.StateOrProvinceCode = stateProvinceAbbreviation; 763 | } 764 | request.RequestedShipment.Shipper.Address.PostalCode = getShippingOptionRequest.ZipPostalCodeFrom; 765 | request.RequestedShipment.Shipper.Address.CountryCode = getShippingOptionRequest.CountryFrom.TwoLetterIsoCode; 766 | } 767 | 768 | private static decimal TotalPackageSize(decimal length, decimal height, decimal width) 769 | { 770 | return height * 2 + width * 2 + length; 771 | } 772 | 773 | #endregion 774 | 775 | #region Methods 776 | 777 | /// 778 | /// FedEx services string names 779 | /// 780 | public static IList GetAllFedExServicesName() 781 | { 782 | return _fedexServices.Values.ToList(); 783 | } 784 | 785 | /// 786 | /// Gets the text name based on the ServiceID (in FedEx Reply) 787 | /// 788 | /// ID of the carrier service -from FedEx 789 | /// String representation of the carrier service 790 | public static string GetFedExServiceName(string serviceId) 791 | { 792 | return !_fedexServices.ContainsKey(serviceId) ? "UNKNOWN" : _fedexServices[serviceId]; 793 | } 794 | 795 | /// 796 | /// Gets the ServiceId based on the text name 797 | /// 798 | /// Name of the carrier service (based on the text name returned from GetServiceName()) 799 | /// Service ID as used by FedEx 800 | public static string GetFedExServiceId(string serviceName) 801 | { 802 | var rez = _fedexServices.FirstOrDefault(p => 803 | p.Value.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase)); 804 | 805 | return string.IsNullOrEmpty(rez.Key) ? "UNKNOWN" : rez.Key; 806 | } 807 | 808 | /// 809 | /// Gets all events for a tracking number 810 | /// 811 | /// The tracking number to track 812 | /// 813 | /// A task that represents the asynchronous operation 814 | /// The task result contains the shipment events 815 | /// 816 | public virtual async Task> GetShipmentEventsAsync(string trackingNumber) 817 | { 818 | try 819 | { 820 | //this is the call to the web service passing in a TrackRequest and returning a TrackReply 821 | var reply = await CreateTrackRequestAsync(trackingNumber); 822 | 823 | if (reply.Alerts?.Any(p => p.AlertType != API.Track.AlertType.NOTE) ?? false) 824 | throw new NopException(reply.Alerts.First(p => p.AlertType == API.Track.AlertType.WARNING).Message); 825 | 826 | return reply.CompleteTrackResults? 827 | .SelectMany(completedTrackDetails => completedTrackDetails.TrackResults? 828 | .Select(trackEvent => new ShipmentStatusEvent 829 | { 830 | EventName = $"{trackEvent.ReasonDetail.Description} ({trackEvent.ReasonDetail.Type})", 831 | Location = trackEvent.LastUpdatedDestinationAddress.City, 832 | CountryCode = trackEvent.LastUpdatedDestinationAddress.CountryCode, 833 | Date = trackEvent.DateAndTimes?.Select(dt => DateTime.Parse(dt.DateTime, CultureInfo.InvariantCulture)).FirstOrDefault() 834 | })) 835 | .ToList(); 836 | } 837 | catch (Exception exception) 838 | { 839 | //log errors 840 | await _logger.ErrorAsync($"Error while getting Fedex shipment tracking info - {trackingNumber}{Environment.NewLine}{exception.Message}", exception, await _workContext.GetCurrentCustomerAsync()); 841 | } 842 | 843 | return new List(); 844 | } 845 | 846 | /// 847 | /// Gets shipping rates 848 | /// 849 | /// Shipping option request details 850 | /// 851 | /// A task that represents the asynchronous operation 852 | /// The task result contains the response of getting shipping rate options 853 | /// 854 | public virtual async Task GetRatesAsync(GetShippingOptionRequest shippingOptionRequest) 855 | { 856 | var response = new GetShippingOptionResponse(); 857 | 858 | //create request details 859 | var (request, requestedShipmentCurrency) = await CreateRateRequestAsync(shippingOptionRequest); 860 | 861 | var clientHandler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; 862 | var httpClient = new HttpClient(clientHandler); 863 | 864 | var client = new RateClient(httpClient, _fedexSettings, await GetAccessTokenAsync()); 865 | 866 | try 867 | { 868 | //try to get response details 869 | 870 | var reply = await client.ProcessRateAsync(request, await GetAccessTokenAsync()); 871 | 872 | if (reply.Alerts?.Any() ?? false) 873 | throw new NopException(reply.Alerts.First().Message); 874 | 875 | if (reply.RateReplyDetails == null) 876 | return response; 877 | 878 | var shippingOptions = await ParseResponseAsync(reply, requestedShipmentCurrency); 879 | 880 | foreach (var shippingOption in shippingOptions) 881 | response.ShippingOptions.Add(shippingOption); 882 | 883 | return response; 884 | } 885 | catch (Exception e) 886 | { 887 | Debug.WriteLine(e.Message); 888 | response.AddError(e.Message); 889 | return response; 890 | } 891 | } 892 | 893 | #endregion 894 | } 895 | --------------------------------------------------------------------------------