ASP.NET {Article027}

説明文の表示 ライブデモを見る▶
ようこそ「ASP.NET」へ...

Amazon MWSのGetLowestOfferListingsForASIN APIを使用してamazon.co.jp(日本)の商品価格(最安値)を取得してブラウザに表示するには?

ここではAmazon MWSのGetLowestOfferListingsForASIN APIを使用して日本のAmazonで販売している商品の価格(最安値を含む)を取得してブラウザに表示する方法を解説します。 GetLowestOfferListingsForASIN() APIは、商品のASIN(Amazon Standard Identification Number)を指定して出品者の販売価格を取得することができます。 商品のASINは1回のコール(呼び出し)で最大20個まで指定できます。 また、商品は新品(New)のみ、中古(Used)のみ、全て(All)の中から選択することができます。 GetLowestOfferListingsForASIN() APIで取得した各種情報はトレース情報としてWebフォームに表示します。 なのでこのAPIでどんな情報が取得できるか理解するのに便利です。

Amazonの販売サイトから価格情報を取得するにはPythonのライブラリを使用する方法もありますが、 Amazon APIを使用するともっと詳細なデータが取得できるといったメリットがあります。 このAPIを使用すると、ある一定の価格より販売価格が下がったらアラーム音を鳴らしたり、メールで通知するといったことが可能になります。 また、最安値と2番目に安いセラーの価格差が30%以上ならメールで通知するといったことも可能です。 ちなみに、著者はこの機能を使用してAmazonに出品している商品の価格を独自のアルゴリズムで調整しています。

商品の価格を取得するには、もっと高度な情報を取得できるGetLowestPriceOffersForASIN APIもありますが、このAPIを使用した記事について後日掲載します。 なお、Amazon MWS APIを使用するにはAmazonの出品者用のアカウントが必要になります。

作成手順

  1. VS2019(Visual Studio 2019 or Visual Studio 2022)を起動したら新規のWebフォーム「Article027.aspx」を作成します。

  2. VS2019のツールボックスから以下のHTML、ASP.NETコントールをドラッグ&ドロップしてWebフォームに配置します。 「GetLowestOfferListingsForASIN」ButtonのEnabledプロパティに「true」を設定してOnClickイベントに「btnGetPrice1_Click」を設定します。 その他のButtonは使用しないのでのEnabledプロパティには「false」を設定します。
    Article027.aspx:
    
    <div id="SKU">
        <h6>GetMyPriceForSKU(jp)</h6>
        SKU1: <asp:TextBox ID="txtSKU1" runat="server" Text="20210206-TOY04-B00VDRTG4A-5870-6888" Columns="40" /><br />
        SKU2: <asp:TextBox ID="txtSKU2" runat="server" Text="" Columns="40" /><br />
        SKU3: <asp:TextBox ID="txtSKU3" runat="server" Text="" Columns="40" />
        <br /><br />
        <asp:Button ID="btnGetMyPrice" runat="server" BackColor="Orange" Text="GetMyPriceForSKU !" Enabled="false" OnClick="btnGetMyPrice_Click" />
    </div>
    <hr />
    <div id="ASIN">
        <h6>GetLowestOfferListingsForASIN(jp), GetLowestPriceOffersForASIN(jp), GetMatchingProductForId(jp)</h6>
        ASIN1: <asp:TextBox ID="txtASIN1" runat="server" Text="B0964957BD" Columns="12" /><br />
        ASIN2: <asp:TextBox ID="txtASIN2" runat="server" Text="" Columns="12" /><br />
        ASIN3: <asp:TextBox ID="txtASIN3" runat="server" Text="" Columns="12" />
        <br /><br />
        <asp:Button ID="btnGetPrice1" runat="server"  BackColor="Orange" Text="GetLowestOfferListingsForASIN !" Enabled="true" OnClick="btnGetPrice1_Click" />             
        <br /><br />
        <asp:Button ID="btnGetPrice2" runat="server"  BackColor="Orange" Text="GetLowestPriceOffersForASIN !" Enabled="false" OnClick="btnGetPrice2_Click" />  
        <br /><br />
        <asp:Button ID="btnGetAttributes" runat="server"  BackColor="Orange" Text="GetMatchingProductForId !" Enabled="false" OnClick="btnGetAttributes_Click" />  
    </div>
    <hr />
    <asp:Label ID="lblTrace" runat="server" Text="" />
  3. VS2019からArticle027.aspxのコードビハインド(Article027.aspx.cs)を選択して表示したら以下のコードを入力します。

    Page_Load()イベント処理:
    Article027.aspx.cs:
    
    private const string ssPublicVariableObject = "PassingPublicVariableObject";
    private const string ssPassingTraceWriteObject = "PassingTraceWriteObject";
    
    public WebConfigArgs wc;
    public PublicVaribleArgs pv;
    public TraceWrite tw;
    
    protected void Page_Load(object sender, EventArgs e)
    {  
        wc = WebConfig.GetWebConfigAmazon();   
        pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
        Session[ssPublicVariableObject] = pv;
    
        tw = new TraceWrite(lblTrace, suppress: false, id: "Article027.aspx");
        Session[ssPassingTraceWriteObject] = tw;
        lblTrace.Text = "";
    
        tw.aspX(string.Format("Page_Load(Page.IsPostBack={0})", Page.IsPostBack));   // black
    }
    btnGetPrice1_Click()イベント処理:
    Article027.aspx.cs:
    
    protected void btnGetPrice1_Click(object sender, EventArgs e)
    {
        tw.aspX2(String.Format("btnGetPrice1_Click()"));   // blue
    
        string strASIN1 = txtASIN1.Text.Trim();
        string strASIN2 = txtASIN2.Text.Trim();
        string strASIN3 = txtASIN3.Text.Trim();
    
        // Create a configuration object
        MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig(); 
        config.ServiceURL = wc.strServiceUrlJp;        
    
        tw.aspX3(String.Format("..config = new MarketplaceWebServiceProductsConfig(ServiceURL={0})", wc.strServiceUrlJp));    // green
    
        // Create the client itself
        MarketplaceWebServiceProductsClient client = new MarketplaceWebServiceProductsClient(wc.strAppName, wc.strAppVersion, wc.strAccessKeyJp, wc.strSecretKeyJp, config);
    
        tw.aspX3(String.Format("..client = new MarketplaceWebServiceProductsClient(config)"));
    
        ASINListType asinList = new ASINListType();
        asinList.ASIN.Add(strASIN1);
    
        if (!String.IsNullOrEmpty(strASIN2))
        {
            asinList.ASIN.Add(strASIN2);
        }
    
        if (!String.IsNullOrEmpty(strASIN3))
        {
            asinList.ASIN.Add(strASIN3);
        }
    
        try
        {
            // Create a request.
            GetLowestOfferListingsForASINRequest request = new GetLowestOfferListingsForASINRequest(wc.strSellerIdJp, wc.strMarketplaceIdJp, asinList);
            request.ExcludeMe = true;
            request.ItemCondition = "New";  // New,Used,Collectible,Refurbished,Club,Default(All)
    
            GetLowestOfferListingsForASINResponse response = client.GetLowestOfferListingsForASIN(request);
    
            string strMessageRef = "";
            string strStatus = GetLowestOfferListingsForASIN_Status(response, ref strMessageRef);   // ClientError or Success    
    
            tw.aspX3(String.Format("..client.GetLowestOfferListingsForASIN(ASIN={0}, ExcludeMe={1}, ItemCondition={2}) ▶ Response.Status({3})", strASIN1, true, "New", strStatus));
    
            // GetLowestOfferListingsForASINResponse
            if (response.IsSetGetLowestOfferListingsForASINResult())
            { 
                // Successfull Call?
                if (strStatus == "Success")
                {
                    int intProdCount = 0;
    
                    // GetLowestOfferListingsForSKUResult
                    foreach (GetLowestOfferListingsForASINResult getLowestOfferListingsForASINResult in response.GetLowestOfferListingsForASINResult)
                    {
                        // Product
                        if (getLowestOfferListingsForASINResult.IsSetProduct())
                        {
                            Product product = getLowestOfferListingsForASINResult.Product;
                            intProdCount++;
    
                            // 1) Identifiers
                            if (product.IsSetIdentifiers())
                            {
                                // MarketplaceASIN
                                string strASIN = "";
    
                                // Get ASIN/SKU
                                if (product.Identifiers.IsSetMarketplaceASIN())
                                {
                                    strASIN = product.Identifiers.MarketplaceASIN.ASIN;
    
                                    tw.aspX4(String.Format("..product.Identifiers.MarketplaceASIN.ASIN={0}", product.Identifiers.MarketplaceASIN.ASIN));
                                }
    
                                // 2) LowestOfferListings
                                if (product.IsSetLowestOfferListings())
                                {
                                    int i = 0;              // 0 based index
                                    int intSellerCnt = 0;   // 1 based
                                    LowestOfferListingList lowestOfferListingList = product.LowestOfferListings;
    
                                    // 2-1) LowestOfferListing                    
                                    if (lowestOfferListingList.IsSetLowestOfferListing())
                                    {                       
                                        foreach (LowestOfferListingType lowestOfferListingType in lowestOfferListingList.LowestOfferListing)
                                        {
                                            intSellerCnt++; // 1 based counter
    
                                            // 2-1-1) Qualifiers
                                            if (lowestOfferListingType.IsSetQualifiers())
                                            {
                                                QualifiersType qualifiersType = lowestOfferListingType.Qualifiers;                   
    
                                                // 2-1-1-1) ItemCondition, ItemSubCondition, FilfillmentChannel
                                                if (qualifiersType.IsSetItemCondition())
                                                {
                                                    tw.aspX4(String.Format("..ItemCondition={0}", qualifiersType.ItemCondition));            // New, Used, Collectible, Refurbished, Club
                                                }
                                                if (qualifiersType.IsSetItemSubcondition())
                                                {
                                                    tw.aspX4(String.Format("..ItemSubCondition={0}", qualifiersType.ItemSubcondition));      // New, Mint, VeryGood, Good, Acceptable, Poor, Club, OEM, Warranty, Refurbished
                                                }
                                                if (qualifiersType.IsSetFulfillmentChannel())
                                                {
                                                    tw.aspX4(String.Format("..FulfillmentChannel={0}", qualifiersType.FulfillmentChannel));  // Amazon, Merchant
                                                }
    
                                                // 2-1-1-2) ShippingTime (14 or more days) 
                                                if (qualifiersType.IsSetShippingTime())
                                                {
                                                    tw.aspX4(String.Format("..ShippingTime.Max={0}", qualifiersType.ShippingTime.Max));       // ShippingTime (Max)  2-3 days, 8-13 days, 14 or more days,...
                                                }
    
                                                // 2-1-1-3) Seller Positive Feedback Rating (90-100%)
                                                if (qualifiersType.IsSetSellerPositiveFeedbackRating())
                                                {
                                                    tw.aspX4(String.Format("..FeedbackRating={0}", qualifiersType.SellerPositiveFeedbackRating));    // 90-94% or 90-100% or Less than 70% or Just Launched                                                                 
                                                }
                                            }             
    
                                            // 2-1-2) SellerFeedbackCount
                                            if (lowestOfferListingType.IsSetSellerFeedbackCount())
                                            {
                                                tw.aspX4(String.Format("..FeedbackCount={0}", Convert.ToInt32(lowestOfferListingType.SellerFeedbackCount)));
                                            }
    
                                            // 2-1-3) Price (Lowest Price)
                                            if (lowestOfferListingType.IsSetPrice())
                                            {
                                                PriceType priceType = lowestOfferListingType.Price;
                                                if (priceType.IsSetLandedPrice())
                                                {
                                                    tw.aspX4(String.Format("..LandedPrice.Amount={0:n0}, CurrencyCode={1}",
                                                        priceType.LandedPrice.Amount, priceType.LandedPrice.CurrencyCode));   // Price + Shipping - Points  
                                                }
                                                if (priceType.IsSetListingPrice())
                                                {
                                                    tw.aspX4(String.Format("..ListingPrice.Amount={0:n0}, CurrencyCode={1}",
                                                        priceType.ListingPrice.Amount, priceType.ListingPrice.CurrencyCode));  // Listing Price (Not Used)
                                                }
                                                if (priceType.IsSetShipping())
                                                {
                                                    tw.aspX4(String.Format("..Shipping.Amount={0:n0}, CurrencyCode={1}",
                                                        priceType.Shipping.Amount, priceType.Shipping.CurrencyCode));    // Shipping Fee (Not Used)
                                                }
                                                if (priceType.IsSetPoints())
                                                {
                                                    tw.aspX4(String.Format("..Points.PointsNumbe={0}", priceType.Points.PointsNumber));
                                                    tw.aspX4(String.Format("..Points.PointsMonetaryValue.Amount={0:n0}, CurrencyCode={1}",
                                                        priceType.Points.PointsMonetaryValue.Amount, priceType.Points.PointsMonetaryValue.CurrencyCode)); // Points (Not Used)
                                                }
                                            } 
                                            else
                                            {
                                                tw.aspX4(String.Format("..if (lowestOfferListingType.IsSetPrice()) else: No Price"));
                                            }
                                            tw.aspX3(String.Format("------------------------- end of Seller {0}", intSellerCnt));
                                            i++;   
                                        }  
                                    }
                                    else 
                                    {
                                        tw.aspX3(String.Format("..if (lowestOfferListingList.IsSetLowestOfferListing()) else:  No Sellers for ASIN={0}", strASIN));
                                    }                
                                }
                                else
                                {
                                    tw.aspX3(String.Format("..if (product.IsSetLowestOfferListings()) else: No Sellers for ASIN={0}", strASIN));
                                } 
                            }
                            else
                            {
                                tw.aspX3(String.Format("..if (product.IsSetIdentifiers()) else: No Sellers for ASIN={0}", strASIN1));
                            }  
                        }
                        else
                        {
                            tw.aspX3(String.Format("..if (getLowestOfferListingsForASINResult.IsSetProduct()) else: No Sellers for ASIN={0}", strASIN1));
                        }  
                    } 
                }
                else 
                {
                    // "NoBuyableOffers" ?
                    if (strMessageRef.IndexOf("NoBuyableOffers") != -1)
                    {
                        tw.aspX3(String.Format("..**Warning** GetLowestOfferListingsForASIN(): Status={0}, {1}", strStatus, strMessageRef));
                    }
                    else
                    {
                        tw.aspX3(String.Format("..**ERROR** GetLowestOfferListingsForASIN(): Status={0}, {1}", strStatus, strMessageRef));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = String.Format("An exception occurred while executing GetLowestOfferListingsForASIN() : {0}", ex == null ? "null" : ex.Message);
        }
    }
    GetLowestOfferListingsForASIN_Status()処理:
    Article027.aspx.cs:
    
    private string GetLowestOfferListingsForASIN_Status(GetLowestOfferListingsForASINResponse response, ref string strMessageRef)
    {
        string strStatus = "Invalid Call";  //  ClientError or Success 
    
        if (response.IsSetGetLowestOfferListingsForASINResult())
        {
            // XPath
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(response.ToXML());
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("mws", "http://mws.amazonservices.com/schema/Products/2011-10-01");
            nsmgr.AddNamespace("ns2", "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd");
    
            XmlNode node;
    
            // Get Status                
            node = doc.SelectSingleNode("/mws:GetLowestOfferListingsForASINResponse/mws:GetLowestOfferListingsForASINResult", nsmgr);
    
            if (node != null)
            {
                strStatus = node.Attributes["status"].Value; // ClientError or Success
    
                // Error ?
                if (strStatus == "ClientError")
                {
                    const string cstrErrorBasePath = "/mws:GetLowestOfferListingsForASINResponse/mws:GetLowestOfferListingsForASINResult/mws:Error";
    
                    string strType = "";
                    string strCode = "";
                    string strMessage = "";
    
                    // Get Error Type
                    node = doc.SelectSingleNode(cstrErrorBasePath + "/mws:Type", nsmgr);
                    if (node != null)
                    {
                        strType = node.InnerText;
                    }
    
                    // Get Error Code
                    node = doc.SelectSingleNode(cstrErrorBasePath + "/mws:Code", nsmgr);
                    if (node != null)
                    {
                        strCode = node.InnerText;
                    }
    
                    // Get Error Message
                    node = doc.SelectSingleNode(cstrErrorBasePath + "/mws:Message", nsmgr);
                    if (node != null)
                    {
                        strMessage = node.InnerText;
                    }
    
                    strMessageRef = String.Format("Error Info=[Type={0}, Code={1}, Message={2}]", strType, strCode, strMessage);
                }
                else // Success
                {
                    strMessageRef = String.Format("GetLowestOfferListingsForASIN() Call Successfully Completed!");
                }
            }  
        }        
        return (strStatus); //  Success or ClientError
    }
  4. VS2019から新規クラスWebConfig.csを作成したら以下のコードを入力します。
    WebConfig.cs:
        
    public class WebConfigArgs
    {
        // Basic info
        public string strAppName { get; set; }              
        public string strAppType { get; set; }              
        public string strAppVersion { get; set; }        
        public string strPoweredBy { get; set; }           
        public string strCopyRight { get; set; }           
    
        // Amazon(0) MWS API info (Current Region)
        public string strServiceUrl { get; set; }                   // Web.config
        public string strAccessKey { get; set; }                    // Web.config
        public string strSecretKey { get; set; }                    // Web.config
        public string strSellerId { get; set; }                     // Web.config
        public string strAuthToken { get; set; }                    // Web.config
        public string strMarketplaceId { get; set; }                // Web.config
        public string strMerchantId { get; set; }                   // Web.config
    
        // Amazon(1) MWS API info (US)
        public string strServiceUrlUs { get; set; }                 // Web.config
        public string strAccessKeyUs { get; set; }                  // Web.config
        public string strSecretKeyUs { get; set; }                  // Web.config
        public string strSellerIdUs { get; set; }                   // Web.config
        public string strAuthTokenUs { get; set; }                  // Web.config
        public string strMarketplaceIdUs { get; set; }              // Web.config
        public string strMerchantIdUs { get; set; }                 // Web.config
    
        // Amazon(2) MWS API info (CA)
        public string strServiceUrlCa { get; set; }                 // Web.config
        public string strAccessKeyCa { get; set; }                  // Web.config
        public string strSecretKeyCa { get; set; }                  // Web.config
        public string strSellerIdCa { get; set; }                   // Web.config
        public string strAuthTokenCa { get; set; }                  // Web.config
        public string strMarketplaceIdCa { get; set; }              // Web.config
        public string strMerchantIdCa { get; set; }                 // Web.config
    
        // Amazon(3) MWS API info (AU)
        public string strServiceUrlAu { get; set; }                 // Web.config
        public string strAccessKeyAu { get; set; }                  // Web.config
        public string strSecretKeyAu { get; set; }                  // Web.config
        public string strSellerIdAu { get; set; }                   // Web.config
        public string strAuthTokenAu { get; set; }                  // Web.config
        public string strMarketplaceIdAu { get; set; }              // Web.config
        public string strMerchantIdAu { get; set; }                 // Web.config
    
        // Amazon(4) MWS API info (JP)
        public string strServiceUrlJp { get; set; }                 // Web.config
        public string strAccessKeyJp { get; set; }                  // Web.config
        public string strSecretKeyJp { get; set; }                  // Web.config
        public string strSellerIdJp { get; set; }                   // Web.config
        public string strAuthTokenJp { get; set; }                  // Web.config
        public string strMarketplaceIdJp { get; set; }              // Web.config
        public string strMerchantIdJp { get; set; }                 // Web.config
    }
    
    public class WebConfig
    {
        // TraceWarn(): Internal Call
        private static void TraceWarn(string strMessage)
        {
            HttpContext.Current.Trace.Warn("AppLayer.WebConfig: " + strMessage);
        }
    
        public static WebConfigArgs GetWebConfig()
        {
            WebConfigArgs wc = new WebConfigArgs();
    
            // Set Basic info
            wc.strAppName = ConfigurationManager.AppSettings["appName"];          // Home, Liberal Arts,...
            wc.strAppType = ConfigurationManager.AppSettings["appType"];          // PROD or DEVL
            wc.strAppVersion = ConfigurationManager.AppSettings["appVersion"];    // V1.0.0
            wc.strPoweredBy = ConfigurationManager.AppSettings["appPoweredBy"];   // Powered by ASP.NET 4.x
            wc.strCopyRight = ConfigurationManager.AppSettings["appCopyRight"];   // (C)2021 Akio Kasai 
    
            return (wc);
        }
    
        public static WebConfigArgs GetWebConfigAmazon()
        {
            WebConfigArgs wc = new WebConfigArgs();
    
            // Set Basic info
            wc.strAppName = ConfigurationManager.AppSettings["appName"];          // Home, Liberal Arts,...
            wc.strAppType = ConfigurationManager.AppSettings["appType"];          // PROD or DEVL
            wc.strAppVersion = ConfigurationManager.AppSettings["appVersion"];    // V1.0.0
            wc.strPoweredBy = ConfigurationManager.AppSettings["appPoweredBy"];   // Powered by ASP.NET 4.x
            wc.strCopyRight = ConfigurationManager.AppSettings["appCopyRight"];   // (C)2021 Akio Kasai 
    
            // Set Amazon(0) MWS API info (Current Region: JP )
            wc.strAccessKey = ConfigurationManager.AppSettings["accessKey"];
            wc.strSecretKey = ConfigurationManager.AppSettings["secretKey"];
            wc.strServiceUrl = ConfigurationManager.AppSettings["serviceUrl"];
            wc.strSellerId = ConfigurationManager.AppSettings["sellerId"];
            wc.strAuthToken = ConfigurationManager.AppSettings["authToken"];
            wc.strMarketplaceId = ConfigurationManager.AppSettings["marketplaceId"];
            wc.strMerchantId = ConfigurationManager.AppSettings["merchantId"];
    
            // Set Amazon(1) MWS API info (US)
            wc.strAccessKeyUs = ConfigurationManager.AppSettings["accessKeyUs"];
            wc.strSecretKeyUs = ConfigurationManager.AppSettings["secretKeyUs"];
            wc.strServiceUrlUs = ConfigurationManager.AppSettings["serviceUrlUs"];
            wc.strSellerIdUs = ConfigurationManager.AppSettings["sellerIdUs"];
            wc.strAuthTokenUs = ConfigurationManager.AppSettings["authTokenUs"];
            wc.strMarketplaceIdUs = ConfigurationManager.AppSettings["marketplaceIdUs"];
            wc.strMerchantIdUs = ConfigurationManager.AppSettings["merchantIdUs"];
    
            // Set Amazon(2) MWS API info (CA)
            wc.strAccessKeyCa = ConfigurationManager.AppSettings["accessKeyCa"];
            wc.strSecretKeyCa = ConfigurationManager.AppSettings["secretKeyCa"];
            wc.strServiceUrlCa = ConfigurationManager.AppSettings["serviceUrlCa"];
            wc.strSellerIdCa = ConfigurationManager.AppSettings["sellerIdCa"];
            wc.strAuthTokenCa = ConfigurationManager.AppSettings["authTokenCa"];
            wc.strMarketplaceIdCa = ConfigurationManager.AppSettings["marketplaceIdCa"];
            wc.strMerchantIdCa = ConfigurationManager.AppSettings["merchantIdCa"];
    
            // Set Amazon(3) MWS API info (AU)
            wc.strAccessKeyAu = ConfigurationManager.AppSettings["accessKeyAu"];
            wc.strSecretKeyAu = ConfigurationManager.AppSettings["secretKeyAu"];
            wc.strServiceUrlAu = ConfigurationManager.AppSettings["serviceUrlAu"];
            wc.strSellerIdAu = ConfigurationManager.AppSettings["sellerIdAu"];
            wc.strAuthTokenAu = ConfigurationManager.AppSettings["authTokenAu"];
            wc.strMarketplaceIdAu = ConfigurationManager.AppSettings["marketplaceIdAu"];
            wc.strMerchantIdAu = ConfigurationManager.AppSettings["merchantIdAu"];
    
            // Set Amazon(4) MWS API info (JP)
            wc.strAccessKeyJp = ConfigurationManager.AppSettings["accessKeyJp"];
            wc.strSecretKeyJp = ConfigurationManager.AppSettings["secretKeyJp"];
            wc.strServiceUrlJp = ConfigurationManager.AppSettings["serviceUrlJp"];
            wc.strSellerIdJp = ConfigurationManager.AppSettings["sellerIdJp"];
            wc.strAuthTokenJp = ConfigurationManager.AppSettings["authTokenJp"];
            wc.strMarketplaceIdJp = ConfigurationManager.AppSettings["marketplaceIdJp"];
            wc.strMerchantIdJp = ConfigurationManager.AppSettings["merchantIdJp"];
    
            return (wc);
        }
    }
  5. VS2019から新規クラスPublicVariable.csを作成したら以下のコードを入力します。
    PublicVariable.cs:
        
    public class PublicVaribleArgs
    {
        // Basic Info
        public bool bolDebugMode { get; set; }
        public bool bolTraceMode { get; set; }
        public Label lblMessage { get; set; }
        public Label lblTrace { get; set; }
    }
    
    public class PublicVariable
    {
        public static PublicVaribleArgs GetPublicVarialbe(bool bolDebugMode, bool bolTraceMode, Label lblMessage, Label lblTrace)
        {
            PublicVaribleArgs pv = new PublicVaribleArgs();
    
            pv.bolDebugMode = bolDebugMode;
            pv.bolTraceMode = bolTraceMode;
            pv.lblMessage = lblMessage;
            pv.lblTrace = lblTrace;
    
            return (pv);
        }
    }
  6. VS2019から新規クラスTraceWrite.csを作成したら以下のコードを入力します。
    TraceWrite.cs:
        
    public class TraceWrite
    {
        public Label lblTrace { get; set; }     // Trace Output Label
        public bool bolSuppress { get; set; }   // True - Suppress Trace, False - Write trace
        public string strID { get; set; }       // ID - Article999.aspx, AccessDb.Stats, AccessDb.Category,...
        public string strMessage { get; set; }  // Message
    
        public TraceWrite()
        {
            this.bolSuppress = false;
            this.strID = "Article???.aspx";
        }
        public TraceWrite(Label trace)
        {
            this.lblTrace = trace;
            this.bolSuppress = false;
            this.strID = "Article???.aspx";
        }
    
        public TraceWrite(Label trace, bool suppress)
        {
            this.lblTrace = trace;
            this.bolSuppress = suppress;
            this.strID = "Article???.aspx";
        }
    
        public TraceWrite(Label trace, bool suppress, string id)
        {
            this.lblTrace = trace;
            this.bolSuppress = suppress;
            this.strID = id;                // Artice999.aspx, AccessDb.Stats, AccessDb.Category,...            
        }
    
        public void TW(string message)
        {
            if (!bolSuppress)
            {
                this.strID = "TW";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("{0}: {1} <br />", this.strID, this.strMessage);
                   
            }
        }
    
        public void TW(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("{0}: {1} <br />",  this.strID, this.strMessage);
    
            }
        }
    
        public void Stats(string message)
        {
            if (!bolSuppress)
            {
                this.strID = "AccessDb.Stats";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: red;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void Stats(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: red;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void Category(string message)
        {
            if (!bolSuppress)
            {
                this.strID = "AccessDb.Category";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: red;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void Category(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: red;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void csClass(string message)
        {
            if (!bolSuppress)
            {
                this.strID = this.strID ?? "???.cs";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: blue;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void csClass(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: blue;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void aspX(string message)
        {
            if (!bolSuppress)
            {
                this.strID = this.strID ?? "Article???.aspx";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: black;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
        public void aspX(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: black;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void aspX2(string message)
        {
            if (!bolSuppress)
            {
                this.strID = this.strID ?? "Article???.aspx";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: blue;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void aspX2(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: blue;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void aspX3(string message)
        {
            if (!bolSuppress)
            {
                this.strID = this.strID ?? "Article???.aspx";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: green;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void aspX3(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: green;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void aspX4(string message)
        {
            if (!bolSuppress)
            {
                this.strID = this.strID ?? "Article???.aspx";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: DarkViolet;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void aspX4(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: DarkViolet;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void TraceWriteX(string message)
        {
            if (!bolSuppress)
            {
                this.strID = "TraceWrite";
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: red;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
        public void TraceWriteX(string id, string message)
        {
            if (!bolSuppress)
            {
                this.strID = id;
                this.strMessage = message;
                this.lblTrace.Text += String.Format("<span style=\"color: red;\">{0}: {1} </span><br />", this.strID, this.strMessage);
            }
        }
    
    
    }
  7. VS2019からWeb.configファイルを作成したら以下のコードを入力します。
    Web.config:
    
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    	<appSettings>
    		<!--Basic info-->
    		<add key="appName" value="ASP.NET" />		
    
    		<!--Amazon(0) MWS API info (Current Region : JP)-->
    		<add key="accessKey" value="****" />
    		<add key="secretKey" value="****" />
    		<add key="serviceUrl" value="https://mws.amazonservices.jp" />
    		<add key="sellerId" value="****" />
    		<add key="marketplaceId" value="****" />
    		<add key="merchantId" value="****" />
    		<add key="mwsDeveloperId" value="****" />
    
    
    		<!--Amazon(1) MWS API info (US)-->
    		<add key="accessKeyUs" value="****" />
    		<add key="secretKeyUs" value="****" />
    		<add key="serviceUrlUs" value="https://mws.amazonservices.com" />
    		<add key="sellerIdUs" value="****" />
    		<add key="marketplaceIdUs" value="****" />
    		<add key="merchantIdUs" value="****" />
    		<add key="mwsDeveloperIdUs" value="****" />
    
    		<!--Amazon(2) MWS API info (CA)-->
    		<add key="accessKeyCa" value="****" />
    		<add key="secretKeyCa" value="****" />
    		<add key="serviceUrlCa" value="https://mws.amazonservices.ca" />
    		<add key="sellerIdCa" value="****" />
    		<add key="marketplaceIdCa" value="****" />
    		<add key="merchantIdCa" value="****" />
    		<add key="mwsDeveloperIdCa" value="****" />
    
    		<!--Amazon(3) MWS API info (AU)-->
    		<add key="accessKeyAu" value="****" />
    		<add key="secretKeyAu" value="****" />
    		<add key="serviceUrlAu" value="https://mws.amazonservices.com.au" />
    		<add key="sellerIdAu" value="****" />
    		<add key="marketplaceIdAu" value="****" />
    		<add key="merchantIdAu" value="****" />
    		<add key="mwsDeveloperIdAu" value="****" />
    
    		<!--Amazon(4) MWS API info (JP)-->
    		<add key="accessKeyJp" value="****" />
    		<add key="secretKeyJp" value="****" />
    		<add key="serviceUrlJp" value="https://mws.amazonservices.jp" />
    		<add key="sellerIdJp" value="****" />
    		<add key="marketplaceIdJp" value="****" />
    		<add key="merchantIdJp" value="****" />
    		<add key="mwsDeveloperIdJp" value="****" />
    		
    	</appSettings>
    	
    </configuration>

操作手順と解説

  1. サンプルが表示されたらASIN1-3のテキストボックスに日本のAmazonで販売している商品のASINを最大3個入力して[GetLowestOfferListingsForASIN !]ボタンをクリックします。 すると、ブラウザがWebフォームをWebサーバーにポストバックさせます。

  2. Webサーバーにコントールが移ったら、Page_Load()イベント、 btnGetPrice1_Click()イベントの順にコントールが渡ります。 Page_Load()イベントでは、WebConfigクラスのGetWebConfigAmazon()メソッドでASP.NETのweb.configファイルに格納されているAmazon MWS APIに必要な情報を取得して WebConfigクラスのプロパティに保存します。ここで保存した情報はAmazon MWS APIをコールするときに必要になります。

  3. ButtonのbtnGetPrice1_Click()イベントでは、Amazon MWS APIのGetLowestOfferListingsForASIN()をコールして商品の販売価格を取得します。 APIコールで取得した各種情報はASP.NETのLabelコントロールにトレース情報として出力してWebフォーム(Webページ)に表示します。 なお、Amazon MWS APIをコールするためのインターフェース用のライブラリーはAmazonのアカウントを作成するとダウンロードすることができます。

  4. Live DEMOを実行するときは、「説明文の表示」のトグルボタンをクリックして非表示にしてください。

Live DEMO

GetMyPriceForSKU(jp)
SKU1:
SKU2:
SKU3:


GetLowestOfferListingsForASIN(jp), GetLowestPriceOffersForASIN(jp), GetMatchingProductForId(jp)
ASIN1:
ASIN2:
ASIN3:






Article027.aspx: Page_Load(Page.IsPostBack=False)

ASP.NET PV1.0.0 ©2024 Akio Kasai
Powered by ASP.NET 4.x