Amazon MWS

Update Price On Amazon Using Amazon MWS API In C#

In this tutorial, we will learn about updating the price for the product on Amazon using the Feeds API in C#. Amazon allows us to upload Inventory and order data using the Feeds API. The Feeds API provided by Amazon is very easy to use as we have to upload the XML file in the Feed and proper FeedType for the action we have to do.

Prerequisites

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

We should have DLL files should be installed using the Nuget package manager.

Now let’s get started…

First, create a view model for the repricer.

public class AmazonRepricerViewModel
    {
        public string Sku { get; set; }
        public decimal Price { get; set; }
        public bool isLive { get; set; }
    }

Now create a method as RepriceParticularAmazonProducts() or name it as you like.

public void RepriceParticularAmazonProducts(AmazonRepricerViewModel vm)
        {
            StreamWriter InputFile, OutputFile, InventoryFile;
            var guid = Guid.NewGuid();
            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();
            //Input files
            var uploadRootFolderInput = AppDomain.CurrentDomain.BaseDirectory + "\\RepricerLogs\\Input Files";
            Directory.CreateDirectory(uploadRootFolderInput);
            var directoryFullPathInput = uploadRootFolderInput;
            if (directoryFullPathInput == null)
            {
                CustomErrorRepricer("Can not find 'RepricerLogs' folder to save new Report!");
                return;
            }
            string path = Path.Combine(directoryFullPathInput, "PriceUpdateAmazonItem_" + guid + ".txt");
            //Output files
            var uploadRootFolderOutput = AppDomain.CurrentDomain.BaseDirectory + "\\RepricerLogs\\Output Files";
            Directory.CreateDirectory(uploadRootFolderOutput);
            var directoryFullPathOutput = uploadRootFolderOutput;
            if (directoryFullPathOutput == null)
            {
                CustomErrorRepricer("Can not find 'RepricerLogs' folder to save new Report!");
                return;
            }
            string path1 = Path.Combine(directoryFullPathOutput, "PriceUpdateAmazonItem_" + guid1 + ".txt");
            //feed files
            var uploadRootFolderFeed = AppDomain.CurrentDomain.BaseDirectory + "\\RepricerLogs\\Feed Files";
            Directory.CreateDirectory(uploadRootFolderFeed);
            var directoryFullPathFeed = uploadRootFolderFeed;
            if (directoryFullPathFeed == null)
            {
                CustomErrorRepricer("Can not find 'RepricerLogs' folder to save new Report!");
                return;
            }
            string path2 = Path.Combine(directoryFullPathFeed, "PriceUpdateAmazonItem_" + guid2 + ".txt");
            InputFile = File.CreateText(path);
            OutputFile = File.CreateText(path1);
            InventoryFile = File.CreateText(path2);
            try
            {
                StringBuilder str1 = new StringBuilder();
                str1.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\t");
                str1.AppendLine();
                str1.Append("<AmazonItemRequest xmlns=\"urn: Amazon:apis: eBLBaseComponents\">\t");
                str1.AppendLine();
                str1.Append("<AmazonUser>" + "Do Not Use" + "</AmazonUser>\t");
                str1.AppendLine();
                str1.Append("<SKU>" + vm.Sku + "</SKU>\t");
                str1.AppendLine();
                str1.Append("<Price>" + vm.Price + "</Price>\t");
                str1.AppendLine();
                str1.Append("<Date>" + DateTime.Now.ToString() + "</Date>\t");
                str1.AppendLine();
                str1.Append("</AmazonItemRequest>\t");
                str1.AppendLine();
                InputFile.Write(str1.ToString());
                InputFile.Close();

                StringBuilder str = new StringBuilder();
                str.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\t");
                str.AppendLine();
                str.Append("<AmazonEnvelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"amzn-envelope.xsd\">\t");
                str.AppendLine();
                str.Append("<Header>\t");
                str.AppendLine();
                str.Append("<DocumentVersion>1.01</DocumentVersion>\t");
                str.AppendLine();
                str.Append("<MerchantIdentifier>" + _accountId + "</MerchantIdentifier>\t");
                str.AppendLine();
                str.Append("</Header>\t");
                str.AppendLine();
                str.Append("<MessageType>Price</MessageType>\t");
                str.AppendLine();
                str.Append("<Message>\t");
                str.AppendLine();
                str.Append("<MessageID>1</MessageID>\t");
                str.AppendLine();
                str.Append("<OperationType>Update</OperationType>\t");
                str.AppendLine();
                str.Append("<Price>\t");
                str.AppendLine();
                str.Append("<SKU>" + vm.Sku + "</SKU>\t");
                str.AppendLine();
                str.Append("<StandardPrice currency=\"USD\">" + vm.Price + "</StandardPrice>\t");
                str.AppendLine();
                str.Append("</Price>\t");
                str.AppendLine();
                str.Append("</Message>\t");
                str.AppendLine();
                str.Append("</AmazonEnvelope>\t");
                str.AppendLine();
                InventoryFile.Write(str.ToString());
                InventoryFile.Close();
                var response = AmazonPriceUpdate(path2);
                OutputFile.Write("Feed Submitted Successfully, Your submission id is " + response);
                OutputFile.Close();
            }
            catch (WebException ex)
            {
                string exMessage = ex.Message;
                if (ex.Response != null)
                {
                    using (var responseReader = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        exMessage = responseReader.ReadToEnd();
                    }
                }
                OutputFile.Write(exMessage.ToString());
                OutputFile.Close();
            }
        }

As you can see we have created a CustomErrorRepricer method for catching the exception if occurs while creating the folder.

public static void CustomErrorRepricer(string message)
        {
            string lines = "Error occured at " + DateTime.Now.ToString("MM/dd/yyyy h:mm tt") + "\r\n";
            lines += "****************************************************************** \r\n";
            lines += "ErrorMessage: " + message + " \r\n";
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\RepricerLogs\\Error Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\Reports\\Logs\\" + "ReportLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!System.IO.File.Exists(filePath))
            {
                using (StreamWriter sw = System.IO.File.CreateText(filePath))
                {
                    sw.WriteLine(lines);
                }
            }
            else
            {
                using (StreamWriter sw = System.IO.File.AppendText(filePath))
                {
                    sw.WriteLine(lines);
                }
            }
        }

Now we have successfully created the XML file for the product we have to update the price on Amazon. And we have got the path for the file in path2 variable.

Now the function which will actually perform the operation for the updated price on Amazon.

public string AmazonPriceUpdate(string Path)
        {
            SubmitFeedRequest feedRequest = new SubmitFeedRequest();
            feedRequest.Merchant = _accountId;
            feedRequest.FeedContent = File.Open(Path, FileMode.Open, FileAccess.Read);
            feedRequest.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(feedRequest.FeedContent);
            MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
            config.ServiceURL = _domain;
            config.SetUserAgentHeader(_appName, _version, "C Sharp");
            feedRequest.FeedContent.Position = 0;
            feedRequest.FeedType = "_POST_PRODUCT_PRICING_DATA_";
            MarketplaceWebServiceClient client = new MarketplaceWebServiceClient(_accessKey, _secretKey, config);
            SubmitFeedResponse feedResponse = client.SubmitFeed(feedRequest);
            FeedSubmissionInfo feedInfo = feedResponse.SubmitFeedResult.FeedSubmissionInfo;
            return feedInfo.FeedSubmissionId;
        }

The SubmitFeedRequest is used while making the API call as we have previously discussed.

When the call is a success we will get the FeedSubmissionId from it and we can check the result on Amazon Scratchpad by submitting the GetFeedSubmissionResult request from the Scratchpad and passing the Feed number as we got from the previous method.

You can also refer the Blog for updating the quantity for product using Amazon MWS API 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.

View Comments

  • dear please also share MarketplaceWebServiceConfig and SubmitFeedRequest,MarketplaceWebServiceClient,
    SubmitFeedResponse classes..

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