Making a post request to yobit api - c#

I am trying to make a post request to yobit api in UWP platform,this codes are working for other platforms.Here are my codes-
public async Task<RootObject> sellLimitCode()
{
RootObject track = null;
try
{
string url = "https://yobit.net/tapi/";
string parameters = "method=Trade&pair=ltc_btc&type=buy&rate=1&amount=1&nonce=" + (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
String strMsg = "api secret";
var uriBytes = encoding.GetBytes(parameters);
var uriBytes1 = encoding.GetBytes(strMsg);
string str_alg_name = MacAlgorithmNames.HmacSha512;
MacAlgorithmProvider obj_mac_prov = MacAlgorithmProvider.OpenAlgorithm(str_alg_name);
IBuffer buff_msg = CryptographicBuffer.CreateFromByteArray(uriBytes);
IBuffer buff_key_material = CryptographicBuffer.CreateFromByteArray(uriBytes1);
CryptographicKey hmac_key = obj_mac_prov.CreateKey(buff_key_material);
IBuffer hmac = CryptographicEngine.Sign(hmac_key, buff_msg);
byte[] digest = hmac.ToArray();
string hashText = byteToString(digest);
StringBuilder hex1 = new StringBuilder(hashText.Length * 2);
foreach (byte b in digest)
{
hex1.AppendFormat("{0:x2}", b);
}
string sign1 = hex1.ToString();
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Key"] = "api key";
httpWebRequest.Headers["Sign"] = sign1;
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{ }
return track;
}
But I am getting Success:0,invalid key,method or nonce.I have tried changing everything.Still not working.

Related

Authenticate SharePoint online REST API without user name and password

I am trying to build a console app that reads the data from SharePoint list.
But i dont want to pass the user credentials in order to authenticate, instead use the token. Is this possible?
I tried using the following code but i get forbidden error while trying to GetFormDigest
static void Main(string[] args)
{
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/web/lists/getbytitle('sd')/GetItems");
string sResult = string.Empty;
string stringData = "{'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml':'<View><Query><Where><Eq><FieldRef Name =\"Title\"/><Value Type=\"Text\">HR</Value></Eq></Where></Query></View>'}}";
HttpWebRequest oWebRequest = (HttpWebRequest)WebRequest.Create(oUri);
oWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentType = "application/json;odata=verbose";
oWebRequest.Headers.Add("X-RequestDigest", GetFormDigest());
oWebRequest.ContentLength = stringData.Length;
StreamWriter writer = new StreamWriter(oWebRequest.GetRequestStream());
writer.Write(stringData);
writer.Flush();
WebResponse wresp = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
}
public static string GetFormDigest()
{
string sFormDigest = null;
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/contextinfo");
HttpWebRequest oWebRequest = HttpWebRequest.Create(oUri) as HttpWebRequest;
oWebRequest.UseDefaultCredentials = true;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentLength = 0;
oWebRequest.ContentType = "application/json";
string sResult;
WebResponse sWebReponse = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(sWebReponse.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
var jss = new JavaScriptSerializer();
var val = jss.Deserialize<Dictionary<string, object>>(sResult);
var d = val["d"] as Dictionary<string, object>;
var wi = d["GetContextWebInformation"] as Dictionary<string, object>;
sFormDigest = wi["FormDigestValue"].ToString();
return sFormDigest;
}
You could use Add-in authentication to access SharePoint data.
You could check my test demo below.
https://social.msdn.microsoft.com/Forums/office/en-US/d33f5818-f112-42fb-becf-3cf14ac5f940/app-only-token-issue-unauthorized-access?forum=appsforsharepoint

POST request in Apple News API

I am struggling with the POST request for creating an article.
Can anybody please provide me an example value of the canonical request in C#?
The error I receive is signature issue:
{"errors":[{"code":"WRONG_SIGNATURE"}]}
From what I learnt a canonical request is build from:
Method = POST
URL = https://news-api.apple.com/channels/ChanelID/articles
Date = 2019-07-24T18:12:32Z
Content-Type = multipart/form-data
Body - Not fully understood
The Apple News API documentation says
If the request is a POST request and it includes an entity, include
the following:
The value of the Content-Type header
The full content of the entity - What is meant by this?
I want to post one test article from the json files provided in the apple's documentation.
This is the class generating the auth header:
public class Security
{
public static string AuthHeader(string method, string url, object content=null)
{
string formDataBoundary = String.Format("{0:N}", Guid.NewGuid());
var apiKeyId = Constants.AppleNewsKeyId;
var apiKeySecret = Constants.AppleNewsKeySecret;
if (string.IsNullOrEmpty(apiKeyId) || string.IsNullOrEmpty(apiKeySecret)) return string.Empty;
var encoding = new ASCIIEncoding();
var dt = DateTime.Now.ToString(Constants.DateFormat);
var canonicalRequest = string.Format("{0}{1}{2}{3}", method, url, dt, content);
var key = Convert.FromBase64String(apiKeySecret);
var hmac = new HMACSHA256(key);
var hashed = hmac.ComputeHash(encoding.GetBytes(canonicalRequest));
var signature = Convert.ToBase64String(hashed);
var authorizaton = string.Format(#"HHMAC; key={0}; signature={1}; date={2}", apiKeyId, signature, dt);
return authorizaton;
}
}
This is the constants class:
public static class Constants
{
public static readonly string ChannelId = "myID";
public static readonly string AppleNewsBaseUri = "https://news-api.apple.com";
public static readonly string DateFormat = "yyyy-MM-ddTHH:mm:ssK";
public static readonly string AppleNewsKeySecret = "myID";
public static readonly string AppleNewsKeyId = "myID";
}
And the action class which is missing code in order to have proper content instead of null passed to the AuthHeader method:
public class Action
{
public static string SendCommand(string action, string method)
{
var url = $"{Constants.AppleNewsBaseUri}{action}" + "/articles";
//string content = String.Format("{0}:{1}", "Content-Disposition", "form-data; filename=article.json; name=article.json;");
var authheader = Security.AuthHeader(method, url, null);
var request = WebRequest.Create(url);
request.PreAuthenticate = true;
request.Method = "POST";
request.Headers.Add("Authorization", authheader);
if (method.Equals("post", StringComparison.InvariantCultureIgnoreCase))
request.ContentType = "multipart/form-data;" ;
var output = string.Empty;
try
{
string filePath = Path.GetFullPath("article.json");
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
dynamic jsonObj = JsonConvert.DeserializeObject(json);
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(json);
request.ContentLength = bytes.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
try
{
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
output = reader.ReadToEnd();
}
}
catch (WebException e)
{
using (var reader = new StreamReader(e.Response.GetResponseStream()))
{
output = reader.ReadToEnd();
}
}
return output;
}
public static string ReadChannel()
{
var action = $"/channels/{Constants.ChannelId}";
const string method = "POST";
return SendCommand(action, method);
}
}

Best way to POST and GET Response from REST API'S

I am doing post and get response using HttpClient to communicate with REST API as below:
public static string PostToAPI( string value)
{
var payload = new APIModel
{
CommandText = value
};
var stringPayload = JsonConvert.SerializeObject(payload);
var httpContent = new StringContent(stringPayload,Encoding.UTF8,"application/json");
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
HttpResponseMessage message=client.PostAsync("https://testAPI/test",httpContent).Result if (message.IsSuccessStatusCode)
{
string result = message.Content.ReadAsStringAsync().Result;
return result;
}
return string.Empty;
}
is there any other alternative or best way do it?
You can always use HttpWebRequest and HttpWebResponse. Try Below
try
{
var webAddr = "URL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application";
httpWebRequest.Method = "POST";
string str = "request string";
httpWebRequest.Headers["Authorization"] = "";
httpWebRequest.Headers["TenantId"] = "";
httpWebRequest.Headers["Client-Type"] = "";
httpWebRequest.Headers["Protocol"] = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
Console.WriteLine(str);
streamWriter.Write(str);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine("result=" + result);
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}

Pulling categories from store via BigCommerce restful API

I am tring to pull categories from my store on BigCommerce via API.
When I try my credentials at API Console;
https://developer.bigcommerce.com/console
it is working fine, but I when send credentials via C# post request it does not work.
I am receiving [{"status":401,"message":"No credentials were supplied in the request."}]
My code is like;
List<PostCredential> postCredentials = new List<PostCredential>();
postCredentials.Add(new PostCredential { name = "store_url", value = ApiPath });
postCredentials.Add(new PostCredential { name = "username", value = Username });
postCredentials.Add(new PostCredential { name = "api_key", value = ApiToken });
JavaScriptSerializer serializer = new JavaScriptSerializer();
string serialize = serializer.Serialize(postCredentials);
const string requestUrl = "https://myteststore1234.mybigcommerce.com/api/v2/categories.json";
StringBuilder postData = new StringBuilder();
postData.Append(serialize);
string postRequest = PostRequest(requestUrl, postData.ToString());
public static string PostRequest(string url, string postData)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
string responseString = new StreamReader(responseStream).ReadToEnd();
return responseString;
}
return null;
}
is there any workaround for this?
WebHeaderCollection wHeader = new WebHeaderCollection();
wHeader.Clear();
//wHeader.Add("username:test");
//wHeader.Add("password:4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b");
//wHeader.Add("u","test:4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b");
string Username = "test";
string ApiToken = "4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b";
string sUrl = "https://store-bwvr466.mybigcommerce.com/api/v2/brands.json"; //txtstoreurl.Text.ToString() + "/api/v2/products.json";
HttpWebRequest wRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(sUrl);
wRequest.Credentials = new NetworkCredential(Username, ApiToken);
wRequest.ContentType = "application/json"; //' I don't know what your content type is
//wRequest.Headers = wHeader;
wRequest.Method = "GET";
HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse();
string sResponse = "";
using (StreamReader srRead = new StreamReader(wResponse.GetResponseStream()))
{
sResponse = srRead.ReadToEnd();
MessageBox.Show(sResponse);
}
After some research I found out I need to pass parameters like this;
httpWReq.Method = "GET";
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
httpWReq.Credentials = new NetworkCredential(Username, ApiToken);

How to use Magento REST API from C#

Where can I find samples that show how to connect to the Magento REST API using C#?
I found was a php one which I could not figure out except a little.
Using a Dropbox OAuth sample I found on the net I tried to make it work for 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);
}
Unfortunately this returns a BAD REQUEST response.
I recently started a project for a C# REST API client for Magento that might help you out:
https://github.com/nickvane/Magento-RestApi
It's not yet feature complete, but the oauth authentication is implemented.
The code uses restsharp which has support for oauth authentication.
I had the same question but couldn't find the answer hence I spent a day to make it work. I share my code here and I hope it will help other people in the feature.
use the following code in an aspx page to get oAuth access
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
}
add the following code in a class file
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; }
}
also don't forget to add the https://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs to the project
it's ready to use. to read from api :
var request = CreateAuthorizedRequest(MagentoServer + "/api/rest/products", "get", new ApiFilter() {Page = 1 });
var responseText = FetchRequest(request);
Magento REST Api documantion can be found here
you can quickly create a client REST API using Spring.NET Social :
http://www.springframework.net/social/
Magento uses OAuth 1.0a authentication like Twitter. You can take a look to the Twitter implementation here:
http://www.springframework.net/social-twitter/
And the related documentation with step by step instructions:
http://www.springframework.net/social/refdoc/implementing.html
I'm not sure if this helps or not, but once I was able to get the oauth_token and oauth_token_secret from Magento (I used a PHP Magento sample to get it) I was able to query the REST API by putting everything in your requestUri into the header.
Your example helped me get most of the code correct, and just modified it a little (here's a little snippet):
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();
}
Does that help?

Categories