Amazon MWS

Get ASIN Category Using Amazon MWS API In C#

In this article, we will learn about getting Amazon Asin category using the Amazon MWS API in C#. We will use the latest version of the NuGet as this functionality is provided in the latest version only.

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 using Amazon MWS API.

Install-Package MarketplaceWebService -Version 1.0.0

Install-Package MarketplaceWebServiceOrders -Version 1.0.0

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 - Amazon MWS API</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <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 MWS API", "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>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Navigate to View -> Home -> Index.cshtml

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

<div class="col-md-4">
    <div class="form-group">
        <input type="text" id="txtAsin" class="form-control" />
    </div>
</div>
<div class="col-md-4">
    <div class="form-group">
        <input type="button" id="btnGetCategory" class="btn btn-success" value="Get Category" />
    </div>
</div>

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Category Id</th>
            <th>Category Name</th>
        </tr>
    </thead>
    <tbody class="tbody"></tbody>
</table>

@section scripts{
    <script>
        $(document).on('click', '#btnGetCategory', function () {
            var asinValue = $('#txtAsin').val();
            if (asinValue.trim() == "") {
                alert("Please enter asin value");
                return;
            }
            $.ajax({
                url: '/Home/GetAsinCategory',
                data: { 'Asin': asinValue },
                success: function (res) {
                    debugger
                    if (res.status) {
                        var html = '';
                        for (var i = 0; i < res.categoryId.length; i++) {
                            html += '<tr>\
                                        <td> '+ res.categoryId[i] + '</td>\
                                        <td> '+ res.categoryName[i] + '</td>\
                                     </tr>';
                        }
                        $('.tbody').empty().append(html);
                    }
                    else {
                        alert("Something went wrong while getting category from API");
                    }
                },
                error: function (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 MarketplaceWebService;
using MarketplaceWebServiceProducts;
using MarketplaceWebServiceProducts.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using System.Xml;

namespace GetProductCategoryFromAsinInMWS.Controllers
{
    public class HomeController : Controller
    {
        public static MarketplaceWebServiceConfig _config;
        public static MarketplaceWebServiceClient _amazonClient;
        public static MarketplaceWebServiceClient _reportClient;
        public static MarketplaceWebServiceConfig _reportConfig;
        public static MarketplaceWebServiceProductsConfig _productConfig;
        public static 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"];
            _config = new MarketplaceWebServiceConfig
            {
                ServiceURL = _serviceUrl
            };
            _reportConfig = new MarketplaceWebServiceConfig
            {
                ServiceURL = _serviceUrl
            };
            _reportClient = new MarketplaceWebServiceClient(_accessKeyID, _secretKey, "MWS", "1.0", _reportConfig);
            _amazonClient = new MarketplaceWebServiceClient(_accessKeyID, _secretKey, "MWS", "1.0", _config);
            _productConfig = new MarketplaceWebServiceProductsConfig { ServiceURL = _serviceUrl };
            _productClient = new MarketplaceWebServiceProductsClient("MWS", "1.0", _accessKeyID, _secretKey, _productConfig);
        }
        public ActionResult Index() => View();
        public GetProductCategoriesForASINResponse InvokeGetProductCategoryForAsin(string ASIN)
        {
            try
            {
                GetProductCategoriesForASINRequest request = new GetProductCategoriesForASINRequest();
                request.ASIN = ASIN;
                request.MarketplaceId = _marketplaceID;
                request.MWSAuthToken = "example";
                request.SellerId = _sellerId;
                return _productClient.GetProductCategoriesForASIN(request);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public JsonResult GetAsinCategory(string Asin)
        {
            try
            {
                var response = InvokeGetProductCategoryForAsin(Asin);
                if (response == null) return Json(new { status = false }, JsonRequestBehavior.AllowGet);
                XmlDocument root = new XmlDocument();
                root.LoadXml(response.ToXML());
                XmlNodeList elemListForCategoryName = root.GetElementsByTagName("ProductCategoryName");
                XmlNodeList elemListForCategoryId = root.GetElementsByTagName("ProductCategoryId");
                List<string> categoryIdsAPI = new List<string>();
                List<string> categoryNamesAPI = new List<string>();
                for (int i = 0; i < elemListForCategoryId.Count; i++)
                {
                    categoryNamesAPI.Add(elemListForCategoryName[i]?.InnerText);
                    categoryIdsAPI.Add(elemListForCategoryId[i]?.InnerText);
                }
                return Json(new { status = true, categoryName = categoryNamesAPI, categoryId = categoryIdsAPI }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new { status = false }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

Output:

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

2 years ago