using System; using System.IO; using System.Net; using System.Text; using System.Security.Cryptography; namespace com.rwmanila { public class api { private const string AuthenticationHeaderName = "Authentication"; private const string TimestampHeaderName = "Timestamp"; private const string serverUrl = "http://apps-02.rwmanila.com/api"; private const string publicUserId = "public"; private const string publicAPIKey = "7CE766FE1473813B97C148EB9F7BD49514B9ECD0"; public string userId { get; private set; } public string apiKey { get; private set; } public Uri server { get; private set; } public api(string userId = api.publicUserId, string apiKey = api.publicAPIKey, string server = api.serverUrl) { this.userId = userId; this.apiKey = apiKey; this.server = new Uri(server); } public string send(string request, string contentType) { string r = string.Empty; string t = DateTime.Now.ToString("U"); try { HttpWebRequest req = (HttpWebRequest) WebRequest.Create(this.server); req.Method = "POST"; req.ContentType = contentType; req.Headers.Add(api.TimestampHeaderName, t); req.Headers.Add(api.AuthenticationHeaderName, this.userId + ":" + api.genSignature(this.apiKey, string.Join(" ", req.Method, t, this.server.AbsolutePath).Trim())); byte[] postData = Encoding.UTF8.GetBytes(request); req.ContentLength = postData.Length; using (Stream sreq = req.GetRequestStream()) sreq.Write(postData, 0, postData.Length); using (Stream sres = req.GetResponse().GetResponseStream()) using (StreamReader sread = new StreamReader(sres)) r = sread.ReadToEnd(); } catch (Exception ex) { r = ex.Message; } return r; } private static string genSignature(string apikey, string message) { var key = Encoding.UTF8.GetBytes(apikey.ToUpper()); string hashString; using (var hmac = new HMACSHA256(key)) { var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message.Trim())); hashString = Convert.ToBase64String(hash); } return hashString; } } }