1. 程式人生 > 實用技巧 >C# 獲取亞馬遜介面資料

C# 獲取亞馬遜介面資料

簡明扼要:就是根據需求拼接好一長串Url請求地址

首先 .http://docs.developer.amazonservices.com/zh_CN/dev_guide/ 先了解先亞馬遜介面資料獲取得大致流程

第一步:熟悉必要的請求引數,有些引數是需要買家註冊亞馬遜會員後提供的譬如AWSAccessKeyId,MWSAuthToken,SellerId 三個引數。具體對應哪個值在連結網站上有。

第二步:查詢請求籤名,也就是給你請求介面的引數進行格式轉換等。最後形成64位的字串。作為:Signature 的值。(這他娘是個重點後面有例子)。

第三步:Url請求地址的拼接

例項:我想查詢一個商品及其屬性列表ListMatchingProducts

首先得獲取Signature的值,在這解釋下,我把Url的拼接和Signature放在一起這樣節省資源。

GettUrl方法的最下面是獲取Signature的兩個呼叫。
   public static string GettUrl(MTlistModel MTlistModel)
        {
            Dictionary<string, string> conditionList = new Dictionary<string, string>();
            string Url = MTlistModel.TopUrl+ "
\n?AWSAccessKeyId=" +AmazonMethods.urlEncode(MTlistModel.AWSAccessKeyId) + "\n&Action=" + AmazonMethods.urlEncode(MTlistModel.Action); conditionList.Add("AWSAccessKeyId", AmazonMethods.urlEncode(MTlistModel.AWSAccessKeyId)); conditionList.Add("Action", AmazonMethods.urlEncode(MTlistModel.Action));
if (MTlistModel.MWSAuthToken != null) { Url += "\n&MWSAuthToken=" + AmazonMethods.urlEncode(MTlistModel.MWSAuthToken); conditionList.Add("MWSAuthToken", AmazonMethods.urlEncode(MTlistModel.MWSAuthToken)); } if (MTlistModel.MarketplaceIdList!=null) { int index = 1; foreach(string Marketplace in MTlistModel.MarketplaceIdList) { Url += "\n&MarketplaceId.Id." + index+"=" + AmazonMethods.urlEncode(Marketplace); conditionList.Add("MarketplaceId.Id." + index + "", AmazonMethods.urlEncode(Marketplace)); index += 1; } } if (MTlistModel.FulfillmentChannelList != null) { int index = 1; foreach (string FulfillmentChanne in MTlistModel.FulfillmentChannelList) { Url += "\n&FulfillmentChannel.Channel." + index + "=" + AmazonMethods.urlEncode(FulfillmentChanne); conditionList.Add("FulfillmentChannel.Channel." + index + "", AmazonMethods.urlEncode(FulfillmentChanne)); index += 1; } } if (MTlistModel.PaymentMethodList != null) { int index = 1; foreach (string PaymentMethod in MTlistModel.PaymentMethodList) { Url += "\n&PaymentMethod.Method." + index + "=" + AmazonMethods.urlEncode(PaymentMethod); conditionList.Add("PaymentMethod.Method." + index + "", AmazonMethods.urlEncode(PaymentMethod)); index += 1; } } if (MTlistModel.OrderStatusList != null) { int index = 1; foreach (string OrderStatus in MTlistModel.OrderStatusList) { Url += "\n&OrderStatus.Status." + index + "=" + AmazonMethods.urlEncode(OrderStatus); conditionList.Add("OrderStatus.Status." + index + "", AmazonMethods.urlEncode(OrderStatus)); index += 1; } } if (MTlistModel.SellerId != null) { Url += "\n&SellerId=" + AmazonMethods.urlEncode(MTlistModel.SellerId); conditionList.Add("SellerId", AmazonMethods.urlEncode(MTlistModel.SellerId)); } if (MTlistModel.AmazonOrderId != null) { Url += "\n&AmazonOrderId=" + AmazonMethods.urlEncode(MTlistModel.AmazonOrderId); conditionList.Add("AmazonOrderId", AmazonMethods.urlEncode(MTlistModel.AmazonOrderId)); } if (MTlistModel.SignatureVersion != null) { Url += "\n&SignatureVersion=" + AmazonMethods.urlEncode(MTlistModel.SignatureVersion); conditionList.Add("SignatureVersion", AmazonMethods.urlEncode(MTlistModel.SignatureVersion)); } if (MTlistModel.SignatureMethod != null) { Url += "\n&SignatureMethod=" + AmazonMethods.urlEncode(MTlistModel.SignatureMethod); conditionList.Add("SignatureMethod", AmazonMethods.urlEncode(MTlistModel.SignatureMethod)); } if (MTlistModel.MarketplaceId != null) { Url += "\n&MarketplaceId=" + AmazonMethods.urlEncode(MTlistModel.MarketplaceId); conditionList.Add("MarketplaceId", AmazonMethods.urlEncode(MTlistModel.MarketplaceId)); } if (MTlistModel.IdType != null) { Url += "\n&IdType=" + AmazonMethods.urlEncode(MTlistModel.IdType); conditionList.Add("IdType", AmazonMethods.urlEncode(MTlistModel.IdType)); } if (MTlistModel.IdList != null) { int index = 1; foreach(string str in MTlistModel.IdList) { Url += "\n&IdList.Id."+ index + "=" + AmazonMethods.urlEncode(str); conditionList.Add("IdList.Id." + index + "", AmazonMethods.urlEncode(str)); index= index + 1; } } if (MTlistModel.ASINList != null) { int index = 1; foreach(string str in MTlistModel.ASINList) { Url += "\n&ASINList.ASIN."+index+"=" + AmazonMethods.urlEncode(str); conditionList.Add("ASINList.ASIN." + index + "", AmazonMethods.urlEncode(str)); index = index + 1; } } if (MTlistModel.Query != null) { Url += "\n&Query=" + AmazonMethods.urlEncode(MTlistModel.Query); conditionList.Add("Query", AmazonMethods.urlEncode(MTlistModel.Query)); } if (MTlistModel.NextToken != null) { Url += "\n&NextToken=" + AmazonMethods.urlEncode(MTlistModel.NextToken); conditionList.Add("NextToken", AmazonMethods.urlEncode(MTlistModel.NextToken)); } if (MTlistModel.LastUpdatedAfter != null) { Url += " \n&LastUpdatedAfter=" + AmazonMethods.urlEncode(MTlistModel.LastUpdatedAfter); conditionList.Add("LastUpdatedAfter", AmazonMethods.urlEncode(MTlistModel.LastUpdatedAfter)); } if (MTlistModel.Timestamp != null) { Url += "\n&Timestamp=" + AmazonMethods.urlEncode(MTlistModel.Timestamp.ToString()); conditionList.Add("Timestamp", AmazonMethods.urlEncode(MTlistModel.Timestamp.ToString())); } if (MTlistModel.Version != null) { Url += "\n&Version=" + AmazonMethods.urlEncode(MTlistModel.Version); conditionList.Add("Version", AmazonMethods.urlEncode(MTlistModel.Version)); } if (MTlistModel.Signature == null) { String formattedParameters = AmazonMethods.GetSignatureStr(conditionList, MTlistModel.TopUrl); String signature = AmazonMethods.Sign(formattedParameters, MTlistModel.AWSAccessKeyId); Url += "\n&Signature=" + AmazonMethods.urlEncode(signature); } return Url; }
AmazonMethods.cs
//這是獲取簽名的字串   
 public static string GetSignatureStr(Dictionary<string,string> parameters,string serviceUrl)
        {
            
             Uri endpoint = new Uri(serviceUrl.ToLower());
            StringBuilder data = new StringBuilder();
            data.Append("POST\n");
            data.Append(endpoint.Host);
            data.Append("\n/");
            data.Append("\n");
            foreach(var oneof in   parameters)
            {
                if (oneof.Value != null)
                {
                    data.Append(oneof.Key + "=" + oneof.Value);
                }
                else {
                    data.Append(oneof.Key + "=");
                }
                data.Append("&");
            }
            string str = data.ToString();
            if (parameters.Count > 0)
            {
                str = str.Substring(0, str.Length - 1);
            }
            return str;
        }
  //將拼接字串轉換成64string
      public static string Sign(string data,string secretKey)
        {
            var encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(secretKey);
            byte[] messageBytes = encoding.GetBytes(data);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                var res = Convert.ToBase64String(hashmessage);
                return HttpUtility.UrlEncode(res);
            }
 
        }
//處理下欄位的格式,每個對應的引數值都得搞一下
 public static string urlEncode(string rawValue) {
            String value = (rawValue == null) ? "" : rawValue;
            String encoded = null;
            try
            {
                encoded = System.Web.HttpUtility.UrlEncode(value, System.Text.Encoding.UTF8);
                encoded = encoded.Replace("+", "%20").Replace("*", "%2A").Replace("%7E", "~");
            }
            catch (Exception e)
            {
                return e.ToString();
            }

            return encoded;
        }

到了這一步,Signature的值輕鬆搞出來

下一步,URL拼接,在GettUrl方法裡面已經對URl進行拼接,直接拿出來,

//引數的賦值,以及請求,解析xm檔案        
public async Task<IActionResult> Index()
        {
            DateTime dtnow = DateTime.Now;
          

            MTlistModel listOrdersModel = new MTlistModel()
            { 
                TopUrl = "https://mws.amazonservices.com/Products/2011-10-01",
                AWSAccessKeyId = "AKIAEXAMPLEFWR4TJ7ZQ",
                Action = "ListMatchingProducts",
                MWSAuthToken = "amzn.mws.4ea38b7b-f563-7709-4bae-87aeaEXAMPLE",
                SellerId = "A1IMEXAMPLEWRC",
                SignatureVersion = "2",
                Timestamp =  DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"),
                Version = "2011-10-01",
                SignatureMethod = "HmacSHA256",
                MarketplaceId = "ATVPDKIKX0DER",
                Query = "0439708184"
            };
            AmazonMethods amazonMethods = new AmazonMethods();
//獲取Url這裡面就是請求的地址
            string Url=   AmazonManagement.GettUrl(listOrdersModel);
            AmazonMethods MyAmazon = new AmazonMethods();
  //獲取Url這裡面就是請求的地址返回的結果          
 var ss=   await MyAmazon.getPost(Url);
//解析xml檔案         
   var diclis= AmazonMethods.XMLToDictionary(ss.ToString());
            ViewBag.diclist = diclis;
           
            return View();
        }
//這一步就就是請求post介面了   
public async Task<string> getPost(string Url)
        {
            try
            {
               
                HttpClient httpClient = new HttpClient();
                HttpResponseMessage responseMessage = await httpClient.PostAsync(Url, null);
                string reString = await responseMessage.Content.ReadAsStringAsync();
                return reString;
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

處理返回結果

   public static Dictionary<string, string> XMLToDictionary(string xml, string findXPath = null, ILogger logger = null)
        {
            var stringReader = new StringReader(xml);

            XDocument document = XDocument.Load(stringReader);

            IEnumerable<XElement> elements = null;

            if (string.IsNullOrEmpty(findXPath))
            {
                elements = document.Root.Elements();
            }
            else
            {
                try
                {
                    var findElement = document.XPathSelectElement(findXPath);

                    if (findElement != null)
                    {
                        elements = findElement.Elements();
                    }
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.LogError(e, $"{nameof(XMLToEntity)}: findXPath vaild");
                    }
                }
            }

            if (elements != null)
            {
                var dictionary = elements.ToDictionary(k => k.Name.LocalName, k => k.Value);
                return dictionary;
            }
            else
            {
                return new Dictionary<string, string>();
            }
        }

備註:不要試圖竊取AWSAccessKeyId,MWSAuthToken,SellerId我這幾個引數,都是假的

如有不明白請留言