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+ "?AWSAccessKeyId=" +AmazonMethods.urlEncode(MTlistModel.AWSAccessKeyId) + "&Action=" + AmazonMethods.urlEncode(MTlistModel.Action);
            conditionList.Add("AWSAccessKeyId", AmazonMethods.urlEncode(MTlistModel.AWSAccessKeyId));
            conditionList.Add("Action", AmazonMethods.urlEncode(MTlistModel.Action));
            if (MTlistModel.MWSAuthToken != null)
            {
                Url += "&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 += "&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 += "&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 += "&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 += "&OrderStatus.Status." + index + "=" + AmazonMethods.urlEncode(OrderStatus);
                    conditionList.Add("OrderStatus.Status." + index + "", AmazonMethods.urlEncode(OrderStatus));
                    index += 1;
                }
            }
            if (MTlistModel.SellerId != null)
            {
                Url += "&SellerId=" + AmazonMethods.urlEncode(MTlistModel.SellerId);
                conditionList.Add("SellerId", AmazonMethods.urlEncode(MTlistModel.SellerId));
            }
            if (MTlistModel.AmazonOrderId != null)
            {
                Url += "&AmazonOrderId=" + AmazonMethods.urlEncode(MTlistModel.AmazonOrderId);
                conditionList.Add("AmazonOrderId", AmazonMethods.urlEncode(MTlistModel.AmazonOrderId));
            }
            if (MTlistModel.SignatureVersion != null)
            { 
                Url += "&SignatureVersion=" + AmazonMethods.urlEncode(MTlistModel.SignatureVersion);
                conditionList.Add("SignatureVersion", AmazonMethods.urlEncode(MTlistModel.SignatureVersion));
            }
            if (MTlistModel.SignatureMethod != null)
            {
                Url += "&SignatureMethod=" + AmazonMethods.urlEncode(MTlistModel.SignatureMethod);
                conditionList.Add("SignatureMethod", AmazonMethods.urlEncode(MTlistModel.SignatureMethod));
            }
            if (MTlistModel.MarketplaceId != null)
            {
                Url += "&MarketplaceId=" + AmazonMethods.urlEncode(MTlistModel.MarketplaceId);
                conditionList.Add("MarketplaceId", AmazonMethods.urlEncode(MTlistModel.MarketplaceId));
            }
            if (MTlistModel.IdType != null)
            {
                Url += "&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 += "&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 += "&ASINList.ASIN."+index+"=" + AmazonMethods.urlEncode(str);
                    conditionList.Add("ASINList.ASIN." + index + "", AmazonMethods.urlEncode(str));
                    index = index + 1;
                }
            }
            if (MTlistModel.Query != null)
            {
                Url += "&Query=" + AmazonMethods.urlEncode(MTlistModel.Query);
                conditionList.Add("Query", AmazonMethods.urlEncode(MTlistModel.Query));
            }
            if (MTlistModel.NextToken != null)
            {
                Url += "&NextToken=" + AmazonMethods.urlEncode(MTlistModel.NextToken);
                conditionList.Add("NextToken", AmazonMethods.urlEncode(MTlistModel.NextToken));
            }
            if (MTlistModel.LastUpdatedAfter != null)
            {
                Url += " &LastUpdatedAfter=" + AmazonMethods.urlEncode(MTlistModel.LastUpdatedAfter);
                conditionList.Add("LastUpdatedAfter", AmazonMethods.urlEncode(MTlistModel.LastUpdatedAfter));
            }
            if (MTlistModel.Timestamp != null)
            {
                Url += "&Timestamp=" + AmazonMethods.urlEncode(MTlistModel.Timestamp.ToString());
                conditionList.Add("Timestamp", AmazonMethods.urlEncode(MTlistModel.Timestamp.ToString()));
            }
            if (MTlistModel.Version != null)
            {
                Url += "&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 += "&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我这几个参数,都是假的

如有不明白请留言

以上的源码未经测试 ,我还没拿到 用户的注册信息。待测试

 
 

 

 

 

posted @ 2020-07-14 17:09  人走茶亦凉  阅读(1580)  评论(7编辑  收藏  举报