Access the Coinbase Candles url - c#

I have successfully managed to call some of Coinbase API's end points, but struggling on calling the Candles Url:
using RestSharp;
using System.Globalization;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
var symbol = "BTC-GBP";
var _privateApiKey = "xxxx";
var _secret = "xxxxxxxxxx";
var _timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
var _requestPath = "/api/v3/brokerage/products/" + symbol + "/candles";
var _method = "GET";
var client = new RestClient(#"https://api.coinbase.com" + _requestPath + "?granularity=ONE_DAY&start=" + DateTime.Now.AddMilliseconds(-3000).ToUniversalTime().Ticks + "&end=" + DateTime.Now.ToUniversalTime().Ticks + "");
var request = new RestRequest();
request.Method = Method.Get;
request.AddHeader("Content-Type", "application/json");
request.AddHeader("CB-ACCESS-KEY", _privateApiKey);
request.AddHeader("CB-ACCESS-TIMESTAMP", _timestamp);
request.AddHeader("CB-ACCESS-SIGN", GetAccessSign(_timestamp, _method, _requestPath, "", _secret));
request.AddHeader("CB-VERSION", "2023-01-18");
try
{
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
string GetAccessSign(string timestamp, string method, string path, string body, string apiSecret)
{
var convertedString = Convert.FromBase64String(apiSecret);
var hmaccsha = new HMACSHA256(convertedString);
string timestampStr = timestamp;
string httpMethodStr = method;
var prehash = timestampStr + httpMethodStr + path + body;
// Convert the input string and key to byte arrays
byte[] prehashBytes = Encoding.UTF8.GetBytes(prehash);
byte[] keyBytes = Encoding.UTF8.GetBytes(apiSecret);
// Compute the SHA-256 hash of the input data using the key
HMACSHA256 hmac = new HMACSHA256(keyBytes);
byte[] hash2 = hmac.ComputeHash(prehashBytes);
// Convert the hash to a hexadecimal string
string signedSignature = BitConverter.ToString(hash2).Replace("-", "").ToLower();
return signedSignature;
}
But i keep getting this error:
{"error":"INVALID_ARGUMENT","error_details":"start and end argument is invalid - number of candles requested should be less than 300 ","message":"start and end argument is invalid - number of candles requested should be less than 300 "}

You are missing the required arguments:
https://docs.cloud.coinbase.com/advanced-trade-api/reference/retailbrokerageapi_getcandles
Path Params
product_id string required
The trading pair.
Query Params
start string required
Timestamp for starting range of aggregations, in UNIX time.
end string required
Timestamp for ending range of aggregations, in UNIX time.
granularity string required
The time slice value for each candle.
The API probably just has a bad error message and treats undefined start and end range query params as out of range values.

I managed to get the results back using this in the RestClient and to Tomáš Hübelbauer link:
var client = new RestClient(string.Format(#"https://api.coinbase.com" + _requestPath + "?granularity=ONE_MINUTE&start={0}&end={1}", DateTimeOffset.Now.AddSeconds(-6000).ToUnixTimeSeconds(), DateTimeOffset.Now.ToUnixTimeSeconds()));
Which gave me about 30 to 35 elements of data back

Related

Create Table in Azure using REST API

Has anyone tried creating a table inside a storage account using REST API? I can do it without an issue if I use SharedKeyLite authorization. However, when using SharedKey authorization, the authentication keeps on failing.
My guess is it's got to do something with the "Content-MD5" value in the Authorization signature. The documentation is a little vague on Content-MD5 value and I can't find a recommended way to generate Content-MD5 in the documentation.
I can't find an example using C#. The only example I found was using Powershell and that is using an empty string for Content-MD5. However, that doesn't work for my case.
Here is my code:
public static void CreateTable(string storageAccount, string storageKey, string tableName)
{
var client = new HttpClient();
string date = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
client.DefaultRequestHeaders.Add("x-ms-date", date);
string msVersion = "2018-03-28";
client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0;NetFx");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata");
string payload = "{ \"TableName\":\""+ tableName +"\" }";
int contentLength = GetContentLength(payload);
string authH = "SharedKey " + storageAccount + ":" + CreateTableSignature("POST", payload, "application/json", date, storageAccount + "/Tables", storageKey, new List<string>() { });
client.DefaultRequestHeaders.Add("Authorization", authH);
string requestUri = $"https://{storageAccount}.table.core.windows.net/Tables";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Content = new StringContent(payload,
Encoding.UTF8,
"application/json");
request.Content.Headers.ContentLength = contentLength;
client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
}
public static string CreateTableSignature(string verb, string content, string contentType, string date, string resource, string key, List<string> canonicalizedResourceParms)
{
string msgSignature = verb + "\n" +
CreateMD5(content) + "\n" +
contentType + "\n" +
date + "\n";
msgSignature += "/" + resource;
foreach (string parm in canonicalizedResourceParms)
msgSignature += "\n" + parm;
byte[] SignatureBytes = Encoding.UTF8.GetBytes(msgSignature);
// Create the HMACSHA256 version of the storage key.
HMACSHA256 SHA256 = new HMACSHA256(Convert.FromBase64String(key));
// Compute the hash of the SignatureBytes and convert it to a base64 string.
return Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
}
public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
return Convert.ToBase64String(hashBytes);
}
}
Two points to fix.
Content-Type
request.Content = new StringContent(payload,
Encoding.UTF8,
"application/json");
In this method, SDK actually sets application/json; charset=utf-8 when we sending the request. This means the signature needs application/json; charset=utf-8 as well.
Or I recommend you to remove that misleading content type setting and use
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Content-MD5
It's not required in signature, you can leave it empty. Otherwise If you want to put it in the signature, you need to add corresponding request header first.
request.Content.Headers.ContentMD5 = Convert.FromBase64String(CreateMD5(payload));
Besides, in method CreateMD5(), Encoding should be UTF8
System.Text.Encoding.UTF8.GetBytes(input);

Error: "response":"X006","description":"Invalid hash"

I made a call with Restsharp with the following code in Gridview row command in ASP.net C#:
const string task = "pay";
const string command_api_token = "D3Kc4vMatqQ7pQtU39D22j35aKqy8";
const string merchant_email_on_voguepay = "abc#wyz.com";
Random rnd = new Random();
string refl = DateTime.Now + rnd.Next(1, 9999999).ToString();
byte[] hash_target = Encoding.UTF8.GetBytes(command_api_token + task + merchant_email_on_voguepay + refl);
string hash = BitConverter.ToString(new SHA512CryptoServiceProvider().ComputeHash(hash_target)).Replace("-", string.Empty).ToUpper();
// //load all fields as json and serialize
var keyValues = new Dictionary<string, string>
{
{ "task", "pay"},
{ "merchant", "1234-4567"},
{ "ref",refl},
{ "hash",hash},
{ "remarks", "secure trade"},
{ "seller", "seller#website.com"},
{ "cur", "usd"},
{ "amount", "20"}
};
//serialization using Newtonsoft JSON
string json = JsonConvert.SerializeObject(keyValues);
//url encode the json
var postString = HttpUtility.UrlEncode(json);
//calling API with Restsharp
var client = new RestClient("https://voguepay.com/api/");
var request = new RestRequest(Method.POST);
request.AddParameter("json", json);
IRestResponse response = client.Execute(request);
the call returns the following error when I use the real parameters for email_on_voguepay and command_api_token.
this is what it returns:
{"response":"X006","description":"Invalid hash","values":"","salt":"58656ba1d162a","hash":"2638fb45f266d35bc78524490a3329a3fecf7b5189c473e82e45d7d6a22f07656743e2cb9ae28dfc81e77eef49eb24d46e0fd4a71cab16847a7afd225310feb5","username":"MyName"}
Please I need help here, what did I do wrong and how do I correct that?
Seems to be your request has a invalid hash (token). I suggest you to check the string refl = DateTime.Now + rnd.Next(1, 9999999).ToString();
The time function in php (according with voguePay API, returns the unix timestamp.
So in C# please consider using DateTimeOffset.ToUnixTimeSeconds or (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds
For more info, please consider checking the generated token was following instructions:
Required Security code generated by concatenating the following and passing the result through a sha512 encryption
your command api token
task specified above
your voguepay email
ref specified above
ref Unique id for each request (Required) $field['ref'] = time().mt_rand(0,999999999);
https://voguepay.com/developers

translate perl hash to C#

I have a perl script that hashes and hexes parameters for authenticating a post message. I have to write the same procedure in C#, but have had no luck so far. Here is the perl code:
my $sha1_user_pwd = sha1_base64($user_pwd);
$sha1_user_pwd .= '=' x (4 - (length($sha1_user_pwd) % 4));
my $sha1_ws_pwd = sha1_base64($ws_pwd);
$sha1_ws_pwd .= '=' x (4 - (length($sha1_ws_pwd) % 4)); # Padding; if neccesary.
my $utc_time = time;
my ($utc_time, $kontekst, $projekt, $userid, $sha1_user_pwd) = #_;
my $auth = calc_hmac($sha1_ws_pwd, $sha1_user_pwd, $utc_time, $kontekst, $projekt, $userid);
sub calc_hmac {
my ($sha1_ws_pwd, $sha1_user_pwd, $utc_time, $kontekst, $projekt, $userid) = #_;
my $hmac = Digest::HMAC_SHA1->new($sha1_ws_pwd . $sha1_user_pwd);
$hmac->add($utc_time . $kontekst . $projekt . $userid);
return $hmac->hex digest;
}
$kontekst, $projekt, $userid and $ws_userid are all original string values.
Final post message (i have inserted line breaks for readability)
wsBrugerid=$ws_userid
&UTCtime=$utc_time
&kontekst=$kontekst
&projekt=$projekt
&BrugerId=$userid
&Auth=$auth
I have tried to copy the procedure in C#:
const string APP_KEY = "APP_KEY";
Encoding enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(APP_KEY));
hmac.Initialize();
string ws_user = "ws_usr";
string ws_password = "ws_pwd";
DateTime epochStart = new System.DateTime(1970, 1, 1, 8, 0, 0, System.DateTimeKind.Utc);
int time = (int) (System.DateTime.UtcNow - epochStart).TotalSeconds;
string context = "context";
string project = "project";
string user_id = "user_id";
string user_pwd = "user_pwd";
string sha1_ws_pwd = System.Convert.ToBase64String(hmac.ComputeHash(enc.GetBytes(ws_password)));
sha1_ws_pwd += '=';
string sha1_user_pwd = System.Convert.ToBase64String(hmac.ComputeHash(enc.GetBytes(user_pwd)));
sha1_user_pwd += '=';
string k0 = sha1_ws_pwd + sha1_user_pwd;
string m0 = time + context + project + user_id;
byte[] _auth = hmac.ComputeHash(enc.GetBytes(k0 + m0));
string auth = BitConverter.ToString(_auth).Replace("-", string.Empty);
string url = "https://auth.emu.dk/mauth?wsBrugerid="+ws_user+
"&UTCtime="+time+
"&kontekst="+context+
"&projekt="+project+
"&BrugerId="+user_id+
"&Auth="+auth;
print("AuthenticationManager, url: " + url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
String responseString = "";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
using (Stream stream = response.GetResponseStream()){
StreamReader reader = new StreamReader(stream, encoding);
responseString = reader.ReadToEnd();
}
JSONNode json = JSON.Parse(responseString);
print("AuthenticationManager, response: " + json[0] + " - " + json[1]);
I have no access to the server or application, which gives the response. The real values has of course been swapped. For example, APP_KEY is not "APP_KEY", but instead an actual string used for authentication. I know the data is correct as it passes in the perl script.
I appreciate any help I can get very much.
I figured it out!
It was not the time, but instead it was the hmac key. I was using APP_KEY as key, but the perl script is using sha1_ws_pwd + sha1_user_pwd. (so that was a stupid mistake...)
my $hmac = Digest::HMAC_SHA1->new($sha1_ws_pwd . $sha1_user_pwd);
Finally i also had to lower case the auth in C#. So the change in C# was:
// sha1 hash the passwords
string sha1_ws_pwd = System.Convert.ToBase64String(sha1.ComputeHash(enc.GetBytes(ws_password)));
string sha1_user_pwd = System.Convert.ToBase64String(sha1.ComputeHash(enc.GetBytes(user_pwd)));
…
string k0 = sha1_ws_pwd + sha1_user_pwd;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(k0));
…
string auth = BitConverter.ToString(_auth).Replace("-", string.Empty).ToLower();
Thank you for your time and answers.

HMAC validation Failure with code 403

I have been exploring payeezy api from last three days. I am just making a simple http web request from a C# application. I have followed all the steps mentions and correctly verified each and everything. Below is the detail per item.
API Key :- I have verified my api key its correct.
API Secret :- It is also correct.
merchant token :- It is also verified.
Nonce :- I have created cryptographically strong random number as following.
RandomNumberGenerator rng = new RNGCryptoServiceProvider();
byte[] nonceData = new byte[18];
rng.GetBytes(nonceData);
string nonce = BitConverter.ToUInt64(nonceData,0).ToString();
Timestamp :-
string timestamp = Convert.ToInt64(ts.TotalMilliseconds).ToString();
Payload :-
{"merchant_ref":"Astonishing-Sale","transaction_type":"authorize","method":"credit_card","amount":"1299","currency_code":"USD","credit_card":{"type":"visa","cardholder_name":"John Smith","card_number":"4788250000028291","exp_date":"1020","cvv":"123"}}
Then I have created HMAC as following.
private string CreateAuthorization(string data, string secret)
{
// data is in following format.
// data = apiKey + nonce + timestamp + token + payload;
secret = secret ?? "";
using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
{
byte[] hashdata = hmacsha256.ComputeHash(Encoding.UTF32.GetBytes(data));
return Convert.ToBase64String(hashdata);
}
}
Now I am getting hmac validation error. My generated hmac string is 64 bit while on your website under docs and sandbox its 86 bit.
Can you please assist me in this as I am stuck on this issue from last three days.
Thanks
These are the common causes for “HMAC validation Failure”:
API key and/or API secret are incorrect.
Leading or trailing spaces in the API key, API secret, merchant token.
Timestamp in the HTTP header is not in milliseconds.
Timestamp in the HTTP header does not represent EPOCH time.
Timestamp in the HTTP header is not within 5 minutes of our server time.
System time is not accurate.
Here is a sample c# code to generate HMAC:
public byte[] CalculateHMAC(string data, string secret)
{
HMAC hmacSha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] hmac2Hex = hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(data));
string hex = BitConverter.ToString(hmac2Hex);
hex = hex.Replace("-","").ToLower();
byte[] hexArray = Encoding.UTF8.GetBytes(hex);
return hexArray;
}
protected void Button1_Click(object sender, EventArgs e)
{
string jsonString = "{ \"merchant_ref\": \"MVC Test\", \"transaction_type\": \"authorize\", \"method\": \"credit_card\", \"amount\": \"1299\", \"currency_code\": \"USD\", \"credit_card\": { \"type\": \"visa\", \"cardholder_name\": \"Test Name\", \"card_number\": \"4005519200000004\", \"exp_date\": \"1020\", \"cvv\": \"123\" } }";
Random random = new Random();
string nonce = (random.Next(0, 1000000)).ToString();
DateTime date = DateTime.UtcNow;
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (date - epoch);
string time = span.TotalSeconds.ToString();
string token = Request.Form["token"];//Merchant token
string apiKey = Request.Form["apikey"];//apikey
string apiSecret = Request.Form["apisecret"];//API secret
string hashData = apiKey+nonce+time+token+jsonString;
string base64Hash = Convert.ToBase64String(CalculateHMAC(hashData, apiSecret));
string url = "https://api-cert.payeezy.com/v1/transactions";
//begin HttpWebRequest
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.Accept = "*/*";
webRequest.Headers.Add("timestamp", time);
webRequest.Headers.Add("nonce", nonce);
webRequest.Headers.Add("token", token);
webRequest.Headers.Add("apikey", apiKey);
webRequest.Headers.Add("Authorization", base64Hash );
webRequest.ContentLength = jsonString.Length;
webRequest.ContentType = "application/json";
StreamWriter writer = null;
writer = new StreamWriter(webRequest.GetRequestStream());
writer.Write(jsonString);
writer.Close();
string responseString;
try
{
using(HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream()))
{
responseString = responseStream.ReadToEnd();
request_label.Text = "<h3>Request</h3><br />" + webRequest.Headers.ToString() + System.Web.HttpUtility.HtmlEncode(jsonString);
response_label.Text = "<h3>Response</h3><br />" + webResponse.Headers.ToString() + System.Web.HttpUtility.HtmlEncode(responseString);
}
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
{
using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
{
string remoteEx = reader.ReadToEnd();
error.Text = remoteEx;
}
}
}
}
}
I've been working on an integration and it's working great; maybe you can take a peek
https://github.com/clifton-io/Clifton.Payment
Specifically you'll want to look here:
https://github.com/clifton-io/Clifton.Payment/blob/cc4053b0bfe05f2453dc508e96a649fc138b973c/Clifton.Payment/Gateway/Payeezy/PayeezyGateway.cs#L66
Best of luck :)

API exception while calling 'DataWarehouseGetReportData' in C#

I am using Omniture api to download a report. The report is completed when I checked the status with DataWarehouseCheckRequest method. Now when I try to fetch the report using DataWarehouseGetReportData method, I get
CommunicationException Error in deserializing body of reply message for operation 'DataWarehouseGetReportData
Inner exception says
The specified type was not recognized: name='data_warehouse_report_row', namespace='http://www.omniture.com/', at <rows xmlns=''>
I am new with C# and the API both. Got no idea how to resolve this. Please help.
Thanks
When you want to download a DW report the best option is to do it over http. This the standard way and is much more efficient.
The response to CheckRequest contains a DataURL. Use that to download the data.
Here is some c# sample code I am using for an almost identical API (Partner vs you Enterprise API) (note I'm no c# expert either, so you will need to do a code review on this).
HttpWebResponse statusResponse = null;
string response = "";
StringBuilder sbUrl = new StringBuilder(dwrq.data_url); // hardcode to variable "rest_url" for testing.
HttpWebRequest omniRequest = (HttpWebRequest)WebRequest.Create(sbUrl.ToString());
string timecreated = generateTimestamp();
string nonce = generateNonce();
string digest = getBase64Digest(nonce + timecreated + secret);
nonce = base64Encode(nonce);
omniRequest.Headers.Add("X-WSSE: UsernameToken Username=\"" + username + "\", PasswordDigest=\"" + digest + "\", Nonce=\"" + nonce + "\", Created=\"" + timecreated + "\"");
omniRequest.Method = "GET"; // Switched from POST as GET is the right HTTP verb in this case
try
{
statusResponse = (HttpWebResponse)omniRequest.GetResponse();
using (Stream receiveStream = statusResponse.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
response = readStream.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
Console.WriteLine("Response is a TAB delimeted CSV structure. Printing to screen.");
Console.WriteLine(response);
Console.WriteLine("Ending REST...");
Console.WriteLine("Ending ExportRequestSegmentedData...");
and the supporting methods
/*** Here are the private functions ***/
// Encrypting passwords with SHA1 in .NET and Java
// http://authors.aspalliance.com/thycotic/articles/view.aspx?id=2
private static string getBase64Digest(string input)
{
SHA1 sha = new SHA1Managed();
ASCIIEncoding ae = new ASCIIEncoding();
byte[] data = ae.GetBytes(input);
byte[] digest = sha.ComputeHash(data);
return Convert.ToBase64String(digest);
}
// generate random nonce
private static string generateNonce()
{
Random random = new Random();
int len = 24;
string chars = "0123456789abcdef";
string nonce = "";
for (int i = 0; i < len; i++)
{
nonce += chars.Substring(Convert.ToInt32(Math.Floor(random.NextDouble() * chars.Length)), 1);
}
return nonce;
}
// Time stamp in UTC string
private static string generateTimestamp()
{
return DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
// C#-Base64 Encoding
// http://www.vbforums.com/showthread.php?t=287324
public static string base64Encode(string data)
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
Best of Luck! C.

Categories

Resources