using System; using System.IO; using System.Net; using System.Text; using System.Security.Cryptography; using System.Collections.Generic; namespace com.rwmanila { public class api { private const string AuthenticationHeaderName = "Authentication"; private const string TimestampHeaderName = "Timestamp"; private const string RandomHeaderName = "Random"; internal const string serverUrl = "https://phoenix.newportworldresorts.com/api"; internal const string publicUserId = "public"; internal const string publicAPIKey = "7CE766FE1473813B97C148EB9F7BD49514B9ECD0"; public string userId { get; internal set; } public string apiKey { get; internal set; } public Uri server { get; internal 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 g = Guid.NewGuid().ToString("D"); 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, g, this.server.AbsolutePath).Trim())); req.Headers.Add(api.RandomHeaderName, g); 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; } public string sendJSON(string commandGroup, string command, Dictionary parameters) { StringBuilder json = new StringBuilder(); json.AppendLine("{"); json.Append(" cgrp:'"); json.Append(commandGroup); json.AppendLine("',"); json.Append(" cmnd:'"); json.Append(command); json.AppendLine("',"); json.AppendLine(" prms:{"); foreach (KeyValuePair item in parameters) { json.Append(" '"); json.Append(item.Key); json.Append("':'"); json.Append(item.Value); json.AppendLine("',"); } json.AppendLine(" }"); json.AppendLine("}"); return this.send(json.ToString(), "application/json"); } 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; } } }