2012-07-18 221 views
3

我在哪裏可以找到樣本說明如何連接到使用C#Magento的REST API?如何使用Magento的REST API從C#

我發現了一個PHP的一個我無法弄清楚,除了一點點。

使用Dropbox的OAuth的示例中,我在我試圖使它成爲Magento的工作網發現:

private void button1_Click(object sender, RoutedEventArgs e) 
{ 
    var consumerKey = 「xxxxxxxxxxxxx」; 
    var consumerSecret = 「xxxxxxxxxxxxxxxx」; 

    var uri = new Uri("http://www.MagentoWebsite.com/oauth/token"); 

    // Generate a signature 
    OAuthBase oAuth = new OAuthBase(); 
    string nonce = oAuth.GenerateNonce(); 
    string timeStamp = oAuth.GenerateTimeStamp(); 
    string parameters; 
    string normalizedUrl; 
    string signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, 
    String.Empty, String.Empty, 「GET」, timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, 
    out normalizedUrl, out parameters); 

    signature = HttpUtility.UrlEncode(signature); 

    StringBuilder requestUri = new StringBuilder(uri.ToString()); 
    requestUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey); 
    requestUri.AppendFormat("oauth_nonce={0}&", nonce); 
    requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp); 
    requestUri.AppendFormat("oauth_signature_method={0}&", 「HMAC-SHA1"); 
    requestUri.AppendFormat("oauth_version={0}&", 「1.0"); 
    requestUri.AppendFormat("oauth_signature={0}", signature); 

    var request = (HttpWebRequest)WebRequest.Create(new Uri(requestUri.ToString())); 
    request.Method = WebRequestMethods.Http.Get; 

    var response = request.GetResponse(); 

    var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

    var parts = queryString.Split(’&’); 
    var token = parts[1].Substring(parts[1].IndexOf(’=’) + 1); 
    var tokenSecret = parts[0].Substring(parts[0].IndexOf(’=’) + 1); 

    queryString = String.Format("oauth_token={0}", token); 
    var authorizeUrl = 「http://www.MagentoWebsite.com/admin/oauth_authorize?」+queryString; 
    Process.Start(authorizeUrl); 
} 

不幸的是這將返回BAD REQUEST響應。

+0

你在這裏得到一個anwser?你能分享解決方案嗎?歡呼聲 – 2012-10-27 18:52:30

+1

我有同樣的問題「壞請求」。你找到解決方案嗎? – ihorko 2012-10-31 11:05:17

+0

抱歉有點遲來回應,但我找不到任何積極的解決方案來做到這一點呢。謝謝。 – 2012-11-03 08:46:13

回答

0

我不知道這是否有助於或沒有,但一旦我能從Magento獲得oauth_token和oauth_token_secret(我使用PHP Magento示例獲取它)我可以通過將requestUri中的所有內容放入標頭來查詢REST API。

你舉的例子幫助我得到的大部分代碼正確,只是修改了一些(在這裏是一個小片段):

  StringBuilder sb = new StringBuilder("OAuth "); 
      sb.AppendFormat("oauth_version={0},", "1.0"); 
      sb.AppendFormat("oauth_signature_method={0},", "HMAC-SHA1"); 
      sb.AppendFormat("oauth_nonce={0},", nonce); 
      sb.AppendFormat("oauth_timestamp={0},", timeStamp); 
      sb.AppendFormat("oauth_consumer_key={0},", consumerKey); 
      sb.AppendFormat("oauth_token={0},", oauth_token); 
      sb.AppendFormat("oauth_signature={0}", sig); 

      Debug.WriteLine(sb.ToString()); 
      var request = (HttpWebRequest)WebRequest.Create((resourceUrl)); 
      request.Headers[HttpRequestHeader.Authorization] = sb.ToString(); 
      request.ContentType = "text/xml"; 
      request.Accept = "text/xml"; 
      request.KeepAlive = true; 
      //request.Method = WebRequestMethods.Http.Get; 
      request.Method = "GET"; 

      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      Debug.WriteLine(response.StatusCode); 
      Debug.WriteLine(response.Server); 
      if (response.StatusCode == HttpStatusCode.OK) 
      { 

       Stream responseStream = response.GetResponseStream(); 
       StreamReader responseReader = new StreamReader(responseStream); 
       XmlDocument xmlDoc = new XmlDocument(); 
       xmlDoc.Load(response.GetResponseStream()); 
       Dts.Variables["User::XML_Response"].Value = xmlDoc.OuterXml.ToString(); 

      } 

這是否幫助?

7

最近,我開始了一個C#REST API客戶端項目的Magento可以幫助你了:

https://github.com/nickvane/Magento-RestApi

它沒有完整的功能,但OAuth認證實現。 該代碼使用restsharp,它支持oauth認證。

+0

它看起來不錯,甚至有單元測試和nuget包的負載 - Magento.RestApi – user3791372 2016-11-29 01:03:53

1

我有同樣的問題,但無法找到答案,因此我花了一天的時間來使它工作。我在這裏分享我的代碼,希望它能夠幫助其他人使用該功能。

使用下面的代碼在aspx頁面來獲得OAuth訪問

 protected void Page_Load(object sender, EventArgs e) 
    { 
     string oauth_token = Request.QueryString["oauth_token"]; 
     string oauth_verifier = Request.QueryString["oauth_verifier"]; 

     if (string.IsNullOrEmpty(oauth_token) || string.IsNullOrEmpty(oauth_verifier)) 
     { 
      BeginAuthorization(); 
     } 
     else 
     { 
      Authorize(oauth_token,oauth_verifier); 
     } 
    } 

    private void Authorize(string oauth_token, string oauth_verifier) 
    { 
     var uri = new Uri(MagentoServer + "/oauth/token"); 
     string oauth_token_secret = (string)Session["oauth_token_secret"]; 

     OAuthBase oAuth = new OAuthBase(); 
     string nonce = oAuth.GenerateNonce(); 
     string timeStamp = oAuth.GenerateTimeStamp(); 
     string parameters; 
     string normalizedUrl; 
     string signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, 
     oauth_token,oauth_token_secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, 
     out normalizedUrl, out parameters); 

     StringBuilder sb = new StringBuilder("OAuth "); 
     sb.AppendFormat("oauth_verifier=\"{0}\",", oauth_verifier); 
     sb.AppendFormat("oauth_token=\"{0}\",", oauth_token); 
     sb.AppendFormat("oauth_version=\"{0}\",", "1.0"); 
     sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT"); 
     sb.AppendFormat("oauth_nonce=\"{0}\",", nonce); 
     sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp); 
     sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey); 
     sb.AppendFormat("oauth_signature=\"{0}\"", signature); 

     var request = (HttpWebRequest)WebRequest.Create(uri); 
     request.Headers[HttpRequestHeader.Authorization] = sb.ToString(); 
     request.ContentType = "text/xml"; 
     request.Accept = "text/xml"; 
     request.KeepAlive = true; 
     request.Method = "POST"; 

     try 
     { 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      if (response.StatusCode == HttpStatusCode.OK) 
      { 

       Stream responseStream = response.GetResponseStream(); 
       StreamReader responseReader = new StreamReader(responseStream); 
       string text = responseReader.ReadToEnd(); 
       try 
       { 
        Dictionary<String, string> responseDic = GetDictionaryFromQueryString(text); 

        string token = responseDic.First(q => q.Key == "oauth_token").Value; 
        string secret = responseDic.First(q => q.Key == "oauth_token_secret").Value; 

        Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 
        AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings"); 
        //Edit 
        if (objAppsettings != null) 
        { 
         objAppsettings.Settings["Magento.Token"].Value = token; 
         objAppsettings.Settings["Magento.TokenSecret"].Value = secret; 
         objConfig.Save(); 
        } 

        errorLabel.Text = "Done"; 
        errorLabel.ForeColor = System.Drawing.Color.Green; 

       } 
       catch (Exception ex) 
       { 
        errorLabel.Text = "Exchanging token failed.<br>Response text = " + text + "<br>Exception = " + ex.Message; 
       } 
      } 
     } 
     catch (WebException ex) 
     { 
      var responseStream = ex.Response.GetResponseStream(); 
      StreamReader responseReader = new StreamReader(responseStream); 
      string resp = responseReader.ReadToEnd(); 
      errorLabel.Text = resp; 
     } 

    } 

    private void BeginAuthorization() 
    { 
     string CallbackUrl = Server.UrlEncode(Request.Url.AbsoluteUri); 
     var uri = new Uri(MagentoServer + "/oauth/initiate?oauth_callback=" + CallbackUrl); 

     OAuthBase oAuth = new OAuthBase(); 
     string nonce = oAuth.GenerateNonce(); 
     string timeStamp = oAuth.GenerateTimeStamp(); 
     string parameters; 
     string normalizedUrl; 
     string signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, 
     String.Empty, String.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, 
     out normalizedUrl, out parameters); 

     StringBuilder sb = new StringBuilder("OAuth "); 
     sb.AppendFormat("oauth_callback=\"{0}\",", CallbackUrl); 
     sb.AppendFormat("oauth_version=\"{0}\",", "1.0"); 
     sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT"); 
     sb.AppendFormat("oauth_nonce=\"{0}\",", nonce); 
     sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp); 
     sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey); 
     sb.AppendFormat("oauth_signature=\"{0}\"", signature); 

     var request = (HttpWebRequest)WebRequest.Create(uri); 
     request.Headers[HttpRequestHeader.Authorization] = sb.ToString(); 
     request.ContentType = "text/xml"; 
     request.Accept = "text/xml"; 
     request.KeepAlive = true; 
     request.Method = "GET"; 

     try 
     { 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      if (response.StatusCode == HttpStatusCode.OK) 
      { 

       Stream responseStream = response.GetResponseStream(); 
       StreamReader responseReader = new StreamReader(responseStream); 
       string text = responseReader.ReadToEnd(); 
       try 
       { 
        Dictionary<String, string> dic = GetDictionaryFromQueryString(text); 

        string oauth_token = dic.First(q => q.Key == "oauth_token").Value; 
        string oauth_token_secret = dic.First(q => q.Key == "oauth_token_secret").Value; 
        Session["oauth_token_secret"] = oauth_token_secret; 
        string redirectUrl = MagentoServer + "/index.php/admin/oauth_authorize?oauth_token=" + oauth_token + "&oauth_verifier=" + 
         oauth_token_secret; 
        Response.Redirect(redirectUrl); 

       } 
       catch (Exception ex) 
       { 
        errorLabel.Text = "Parsing request token failed.<br>Response text = " + text + "<br>Exception = " + ex.Message; 
       } 

      } 
     } 
     catch (WebException ex) 
     { 
      var responseStream = ex.Response.GetResponseStream(); 
      StreamReader responseReader = new StreamReader(responseStream); 
      string resp = responseReader.ReadToEnd(); 
      errorLabel.Text = resp; 
     } 
    } 

    private static Dictionary<string, string> GetDictionaryFromQueryString(string queryString) 
    { 
     string[] parts = queryString.Split('&'); 
     Dictionary<String, string> dic = new Dictionary<string, string>(); 
     foreach (var part in parts) 
     { 
      dic.Add(part.Split('=')[0], part.Split('=')[1]); 
     } 
     return dic; 
    } 

    #region Settings 

    string MagentoServer 
    { 
     get 
     { 
      return ConfigurationManager.AppSettings["Magento.Server"]; 
     } 
    } 

    string ConsumerKey 
    { 
     get 
     { 
      return ConfigurationManager.AppSettings["Magento.ConsumerKey"]; 
     } 
    } 

    string ConsumerSecret 
    { 
     get 
     { 
      return ConfigurationManager.AppSettings["Magento.ConsumerSecret"]; 
     } 
    } 

    #endregion 
} 

在類文件

public class ApiClient 
{ 

    public ApiClient(string magentoServer, string consumerKey, string consumerSecret, string accessToken, string accessTokenSeccret) 
    { 
     MagentoServer = magentoServer; 
     ConsumerKey = consumerKey; 
     ConsumerSecret = consumerSecret; 
     AccessToken = accessToken; 
     AccessTokenSecret = accessTokenSeccret; 
    } 

    #region Request 

    HttpWebRequest CreateAuthorizedRequest(string url, string requestMethod,ApiFilter filter) 
    { 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + filter.ToString()); 

     OAuthBase oAuth = new OAuthBase(); 
     string nonce = oAuth.GenerateNonce(); 
     string timeStamp = oAuth.GenerateTimeStamp(); 
     string parameters; 
     string normalizedUrl; 
     string signature = oAuth.GenerateSignature(new Uri(url), ConsumerKey, ConsumerSecret, 
     AccessToken, AccessTokenSecret, requestMethod, timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, 
     out normalizedUrl, out parameters); 

     StringBuilder sb = new StringBuilder("OAuth "); 
     sb.AppendFormat("oauth_token=\"{0}\",", AccessToken); 
     sb.AppendFormat("oauth_version=\"{0}\",", "1.0"); 
     sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT"); 
     sb.AppendFormat("oauth_nonce=\"{0}\",", nonce); 
     sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp); 
     sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey); 
     sb.AppendFormat("oauth_signature=\"{0}\"", signature); 

     request.Headers[HttpRequestHeader.Authorization] = sb.ToString(); 
     request.Method = requestMethod; 

     //request.ContentType = "application/json"; 
     request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//application/json, 
     request.KeepAlive = true; 

     return request; 
    } 

    string FetchRequest(HttpWebRequest request) 
    { 
     try 
     { 
      string responseText = string.Empty; 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      if (response.StatusCode == HttpStatusCode.OK) 
      { 
       using (Stream responseStream = response.GetResponseStream()) 
       { 
        using (StreamReader responseReader = new StreamReader(responseStream)) 
        { 
         responseText = responseReader.ReadToEnd(); 
         return responseText; 
        } 
       } 
      } 

      return responseText; 
     } 
     catch (WebException ex) 
     { 
      var responseStream = ex.Response.GetResponseStream(); 
      StreamReader responseReader = new StreamReader(responseStream); 
      string responseText = responseReader.ReadToEnd(); 
      throw new MagentoApiException(responseText,ex.Status); 
     } 
    } 

    #endregion 

    #region Public properties 

    string MagentoServer { get; set; } 

    string ConsumerKey { get; set; } 

    string ConsumerSecret { get; set; } 

    string AccessToken { get; set; } 

    string AccessTokenSecret { get; set; } 

    #endregion 

} 


public class ApiFilter 
{ 
    public ApiFilter() 
    { 
     filterDescriptions = new List<FilterDescription>(); 
    } 

    public int? Page { get; set; } 
    public int? Limit { get; set; } 
    public List<FilterDescription> filterDescriptions; 

    public const string Type = "rest"; 

    public void AddFilter(string column, FilterType filterType, string value) 
    { 
     filterDescriptions.Add(new FilterDescription() 
     { 
      Column = column, 
      FilterType = filterType, 
      Value = value 
     }); 
    } 

    public override string ToString() 
    { 
     StringBuilder sb = new StringBuilder(); 
     sb.AppendFormat("type={0}", Type); 

     if (Page.HasValue) 
      sb.AppendFormat("&page={0}", Page.Value); 
     if (Limit.HasValue) 
      sb.AppendFormat("&limit={0}", Limit.Value); 

     int counter = 1; 
     foreach (var filter in filterDescriptions) 
     { 

      sb.AppendFormat("&filter[{0}][attribute]={1}&filter[{2}][{3}]={4}", counter, filter.Column, counter, filter.FilterType, filter.Value); 
      counter++; 
     } 

     return sb.ToString(); 
    } 
} 

public class FilterDescription 
{ 
    public string Column { get; set; } 
    public FilterType FilterType { get; set; } 
    public string Value { get; set; } 
} 

public enum FilterType 
{ 
    /// <summary> 
    /// Not Equal To 
    /// </summary> 
    neq, 
    /// <summary> 
    /// equals any of 
    /// </summary> 
    @in, 
    /// <summary> 
    /// not equals any of 
    /// </summary> 
    nin, 
    /// <summary> 
    /// greater than 
    /// </summary> 
    gt, 
    /// <summary> 
    /// less than 
    /// </summary> 
    lt 

} 

public class MagentoApiException : Exception 
{ 

    public MagentoApiException(string responseText, WebExceptionStatus status) 
    { 
     ResponseText = responseText; 
     Status = status; 
    } 

    public string ResponseText { get; set; } 
    public WebExceptionStatus Status { get; set; } 
} 

還添加以下代碼不要忘記將https://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs添加到項目

它已經準備好使用。從API閱讀:

var request = CreateAuthorizedRequest(MagentoServer + "/api/rest/products", "get", new ApiFilter() {Page = 1 }); 
      var responseText = FetchRequest(request); 

Magento的REST API documantion可以發現here

+0

我很欣賞你的努力Rabolf。感謝分享,我一定會盡快給它試一試,並將其標記爲答案,如果按預期工作的話!再次感謝。 – 2014-07-14 06:08:08

+0

您可以分享我們的完整文件嗎?因爲我不會在那裏放置這些代碼和Im得到錯誤。 – Jen143 2016-04-27 02:21:03