Amazon Web服务的GetAuthToken方法无法正常工作

时间:2015-07-06 09:30:51

标签: amazon-web-services amazon aws-marketplace amazon-marketplace

我正在尝试使用GetAuthToken()方法访问amazon webservice。但每次我得到签名不正确的错误。每次我收到此错误。无法找到确切的原因

任何人都可以分享这方面的工作示例,或者看看我在这做什么?

我的代码:

 private void GetToken()
{
    string secretKey = "my secret key";       
    string serviceUrl = "https://mws.amazonservices.com/Sellers/2011-07-01";
    string CHARACTER_ENCODING = "UTF-8";
    string ALGORITHM = "HmacSHA256";

    // Create set of parameters needed and store in a map
    Dictionary<string, string> parameters = new Dictionary<string,string>();

    // Add required parameters. Change these as needed.
    parameters.Add("AWSAccessKeyId", "my access id");
    parameters.Add("Action","GetAuthToken");
    parameters.Add("MWSAuthToken", "");
    parameters.Add("SellerId","my seller id");
    parameters.Add("SignatureMethod", ALGORITHM);
    parameters.Add("SignatureVersion",("2");

    parameters.Add("Timestamp", "2015-07-06T16:03:00Z");
    parameters.Add("Version", "2011-07-01");

    // Format the parameters (without the signature parameter)
    string formattedParameters = calculateStringToSignV2(parameters, serviceUrl);

    string signature = signNew(formattedParameters, secretKey);

    // Add signature to the parameters 
    parameters.Add("Signature", signature);

    formattedParameters = calculateStringToSignV2(parameters, serviceUrl);



    string querystring = formattedParameters.Substring(formattedParameters.IndexOf("AWSAccessKeyId"));


      // Setup the HTTP request.
    HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl + "?" + querystring);
    objWebRequest.Method = "POST";
    objWebRequest.AllowAutoRedirect = true;
    objWebRequest.ContentLength = querystring.Length;

    // Post to the login form.
    StreamWriter swRequestWriter = new StreamWriter(objWebRequest.GetRequestStream());
    swRequestWriter.Write(querystring);
    swRequestWriter.Close();
    HttpWebResponse objWebResponse = null;
    try
    {
        // Get the response.
        objWebResponse =
            (HttpWebResponse)objWebRequest.GetResponse();
    }
    catch(WebException e)
    {

    }
    // Read the response
    StreamReader srResponseReader = new
        StreamReader(objWebResponse.GetResponseStream());
    string strResponseData = srResponseReader.ReadToEnd();
    srResponseReader.Close();

    responseTxt.Text =strResponseData;



private static string calculateStringToSignV2(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");

    SortedDictionary<string, string> sorted = new SortedDictionary<string, string>();
    foreach (KeyValuePair<String, String> pair in _Parameters)
    {
        sorted.Add(pair.Key, pair.Value);
    }


    if (sorted.Count > 0)
    {
        //data.Append("?");
        bool first = true;
        foreach (KeyValuePair<String, String> pair in sorted)
        {
            if (!first)
            {
                data.Append("&");
            }
            else
            {
                first = false;
            }
            data.Append((pair.Key));
            data.Append("=");
            data.Append((pair.Value));
        }
    }

    return data.ToString();
}

}

  private static String signNew(string parameters, string secretKey)
     {           

         string data = parameters;

         HMACSHA256 hmac = new    HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
         hmac.Initialize();

         byte[] bytes = Encoding.UTF8.GetBytes(data);
         byte[] signature = hmac.ComputeHash(bytes);

         string signatureBase64 = Convert.ToBase64String(signature);

         return signatureBase64;           
  }

  private static String urlEncodeNew(String rawValue) {

    string value = (rawValue == null) ? "" : rawValue;
    string encoded = null;

    try {
        encoded = System.Web.HttpUtility.UrlEncode(rawValue, Encoding.UTF8).Replace("+", "%20")
            .Replace("*", "%2A")
            .Replace("%7E", "~");


    } catch (Exception e) {

    }

    return encoded;
}    

2 个答案:

答案 0 :(得分:1)

可能有很多原因:

  1. 您的代码使用了错误的网址

  2. 错误的参数&#34; MWSAuthToken&#34;

  3. 检查您是否传递了正确的参数值

  4. 看看你是如何计算签名的。

  5. 亚马逊公开了自己的图书馆:Download it here

    下载库后,添加&#34; MWSClientCsRuntime-1.0.dll&#34;在您的解决方案中。

    可以使用两种方法:

    1. MWSClientCsRuntime.MwsUtil.UrlEncode(这是用于编码字符)
    2. MWSClientCsRuntime.MwsUtil.Sign(这是签名)
    3. 完整的调整代码:

       private void GetToken()
       {
           string secretKey = "your secret key";
           string serviceUrl = "https://mws.amazonservices.com/Sellers/2011-07-01";
           string CHARACTER_ENCODING = "UTF-8";
           string ALGORITHM = "HmacSHA256";
      
           Dictionary<string, string> parameters = new Dictionary<string, string>();
      
          parameters.Add("AWSAccessKeyId", MWSClientCsRuntime.MwsUtil.UrlEncode("your access key", true));
          parameters.Add("Action", MWSClientCsRuntime.MwsUtil.UrlEncode("GetAuthToken", true));
          parameters.Add("SellerId", MWSClientCsRuntime.MwsUtil.UrlEncode("your seller id", true));
          parameters.Add("SignatureMethod", MWSClientCsRuntime.MwsUtil.UrlEncode(ALGORITHM, true));
          parameters.Add("SignatureVersion", MWSClientCsRuntime.MwsUtil.UrlEncode("2", true));
          parameters.Add("Timestamp", MWSClientCsRuntime.MwsUtil.UrlEncode(("2015-07-06T17:13:00Z", true)); 
          parameters.Add("Version", MWSClientCsRuntime.MwsUtil.UrlEncode("2011-07-01", true));
      
      
          string formattedParameters = calculateStringToSignV2(parameters, serviceUrl);
      
          Uri u = new Uri("https://mws.amazonservices.com");
          string signature = MWSClientCsRuntime.MwsUtil.Sign(formattedParameters, secretKey, ALGORITHM);
      
          // Add signature to the parameters
          parameters.Add("Signature", MWSClientCsRuntime.MwsUtil.UrlEncode(signature, true));
          formattedParameters = calculateStringToSignV2(parameters, serviceUrl);
      
          string data = formattedParameters.Substring(formattedParameters.IndexOf("AWSAccessKeyId"));
      
          HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl + "?" + data);
          objWebRequest.Method = "POST";
          objWebRequest.AllowAutoRedirect = true;
          objWebRequest.ContentLength = data.Length;
      
          StreamWriter swRequestWriter = new StreamWriter(objWebRequest.GetRequestStream());
          swRequestWriter.Write(data);
          swRequestWriter.Close();
          HttpWebResponse objWebResponse = null;
          try
          {
              // Get the response.
              objWebResponse =
                  (HttpWebResponse)objWebRequest.GetResponse();
      
              StreamReader srResponseReader = new StreamReader(objWebResponse.GetResponseStream());
              string strResponseData = srResponseReader.ReadToEnd();
              srResponseReader.Close();
      
              responseTxt.Text = strResponseData;
          }
          catch (WebException e)
          {
              responseTxt.Text = e.Message;
          }
      
      
        private static string calculateStringToSignV2(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("/Sellers/2011-07-01");
          data.Append("\n");
      
          if (_Parameters.Count > 0)
          {
              bool first = true;
              foreach (KeyValuePair<String, String> pair in _Parameters)
              {
                  if (!first)
                  {
                      data.Append("&");
                  }
                  else
                  {
                      first = false;
                  }
                  data.Append((pair.Key));
                  data.Append("=");
                  data.Append((pair.Value));
              }
          }
      
          return data.ToString();
         }
       }
      

答案 1 :(得分:0)

重要提示:您必须在2015年3月31日之前调用此操作(GetAuthToken)以获取现有卖家的授权令牌。在此日期之后,此操作将不再可用。

//来自https://images-na.ssl-images-amazon.com/images/G/01/mwsportal/doc/en_US/bde/MWSAuthToken.pdf //