Amazon MWS

Calculate Amazon FBA Fee Using Amazon MWS API In C#

In this article, we will learn about getting Amazon FBA Fee using the Amazon MWS API in C#. As every seller required to know their FBA fee in order to improve himself/herself regarding selling products on Amazon. Amazon provides us the GetMyFeeEstimate API call in products API.

Prerequisites

  • Knowledge of C#
  • You must have the Amazon credentials like SellerId, Access Key, etc.

So let’s get started.

Firstly, install the NuGet package for products API.

Install-Package MWSProductsCSharpClientLibrary -Version 2017.3.22

Starting from _Layout.cshtml file.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    <style>

        #loading {
            position: fixed;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: rgba(241, 241, 241, 0.48);
            z-index: 2000;
            overflow: hidden;
        }

            #loading img {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                margin: auto;
            }
    </style>
</head>
<body>
    <div id="loading">
        <img src="~/Content/spinner.gif" />
    </div>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Amazon FBA Fees", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @RenderSection("scripts", required: false)
</body>
</html>
<script>
    function showLoader() {
        $('#loading').show();
    }
    function hideLoader() {
        $('#loading').fadeOut();
    }
    function getUrl() {
        var getUrl = window.location;
        var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[0];
        return baseUrl;
    }
    $(document).ready(function () {
        hideLoader();
    });
</script>

Navigate to View -> Home -> Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<div class="row" style="margin-top:5%">
    <div class="form-group col-md-4">
        <label>Enter ASIN</label>
        <input type="text" class="form-control" id="asin" />
    </div>
</div>
<div class="row">
    <div class="form-group col-md-4">
        <input type="button" class="btn btn-success" id="calculate" value="Calculate Fees" />
    </div>
</div>
<hr />
<script>
    $(document).on("click", "#calculate", function () {
        if ($('#asin').val() == "") {
            alert("ASIN is required");
            $('#asin').focus();
            return;
        }
        else {
            showLoader();
            $.ajax({
                url: getUrl() + '/Home/GetFeeEstimateData',
                type: 'POST',
                data: { 'ASIN': $('#asin').val() },
                success: function (res) {
                    hideLoader();
                    if (res.result)
                        alert("FBA Fee is " + res.fee + " " + res.currency);
                    else
                        alert("Something went wrong. Please contact administrator");
                },
                error: function (err) {
                    hideLoader();
                    alert(err);
                }
            });
        }
    });
</script>

We have to add the Credentials in Web.Config file present in the root directory.

<add key="ServiceURL" value="https://mws.amazonservices.com" />
<add key="SellerId" value="seller-id" />
<add key="MarketplaceID" value="marketplace-id" />
<add key="AccessKeyID" value="access-key" />
<add key="SecretKey" value="secret-key" />

Finally, the code which makes us possible to call through the API

using MarketplaceWebServiceProducts;
using MarketplaceWebServiceProducts.Model;
using System;
using System.Configuration;
using System.IO;
using System.Web.Mvc;
using System.Xml;

namespace GetMyFeeEstimateForAmazonMWS.Controllers
{
    public class HomeController : Controller
    {
        public MarketplaceWebServiceProductsConfig _productConfig;
        public MarketplaceWebServiceProducts.MarketplaceWebServiceProducts _productClient;
        public static string sellerId = "";
        public static string marketplaceID = "";
        public static string accessKeyID = "";
        public static string secretKey = "";
        public static string serviceURL = "";
        public HomeController()
        {
            sellerId = ConfigurationManager.AppSettings["SellerId"];
            marketplaceID = ConfigurationManager.AppSettings["MarketplaceID"];
            accessKeyID = ConfigurationManager.AppSettings["AccessKeyID"];
            secretKey = ConfigurationManager.AppSettings["SecretKey"];
            serviceURL = ConfigurationManager.AppSettings["ServiceURL"];
            _productConfig = new MarketplaceWebServiceProductsConfig { ServiceURL = serviceURL };
            _productClient = new MarketplaceWebServiceProductsClient("MWS", "1.0", accessKeyID, secretKey, _productConfig);
        }
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetFeeEstimateData(string ASIN)
        {
            try
            {
                StreamWriter BaseTag;
                var uploadRootFolder = AppDomain.CurrentDomain.BaseDirectory + "\\Reports";
                Directory.CreateDirectory(uploadRootFolder);
                var directoryFullPath = uploadRootFolder;
                string targetFile = Path.Combine(directoryFullPath, "FeeEstimateResponse_" + Guid.NewGuid() + ".xml");
                var response = InvokeGetMyFeesEstimate(ASIN);
                BaseTag = System.IO.File.CreateText(targetFile);
                BaseTag.Write(response.ToXML());
                BaseTag.Close();
                XmlDocument root = new XmlDocument();
                root.Load(targetFile);
                XmlNodeList elemList1 = root.GetElementsByTagName("FeeAmount");
                var data = elemList1[3].InnerText;
                var currency = data.Substring(0, 3);
                var fee = data.Substring(3);
                return Json(new { result = true, currency = currency, fee = fee }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { result = false }, JsonRequestBehavior.AllowGet);
            }
        }
        public GetMyFeesEstimateResponse InvokeGetMyFeesEstimate(string ASIN)
        {
            try
            {
                GetMyFeesEstimateRequest request = new GetMyFeesEstimateRequest();
                request.SellerId = sellerId;
                request.MWSAuthToken = "example";
                FeesEstimateRequestList feesEstimateRequestList = new FeesEstimateRequestList();
                feesEstimateRequestList.FeesEstimateRequest.Add(new FeesEstimateRequest
                {
                    MarketplaceId = marketplaceID,
                    IdType = "ASIN",
                    IdValue = ASIN,
                    PriceToEstimateFees = new PriceToEstimateFees { ListingPrice = new MoneyType { Amount = 0M, CurrencyCode = "USD" } },
                    Identifier = "request_" + Guid.NewGuid().ToString(),
                    IsAmazonFulfilled = true
                });
                request.FeesEstimateRequestList = feesEstimateRequestList;
                return _productClient.GetMyFeesEstimate(request);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}

Output:

You can download the source code from here

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago