Formulating POST request to CoinSpot API - r

I am pulling my hair out trying to query the CoinSpot API.
The endpoint for the Read Only API is: https://www.coinspot.com.au/api/ro
The documentation states:
All requests to the API will need to include the following security
data.
Headers: key - Your API key generated from the settings page sign -
The POST data is to be signed using your secret key according to
HMAC-SHA512 method. Post Params: nonce - Any integer value which must
always be greater than the previous requests nonce value.
I try to query the 'List My Balances' endpoint via: https://www.coinspot.com.au/api/ro/my/balances
However, the code I have formulated below always returns an error: "invalid/missing nonce".
I have tried so many different variations and approaches but it is always the same error.
require(httr)
key <- "68z...39k"
secret <- "71A...48i"
result <- POST("https://www.coinspot.com.au/api/ro/my/balances",
body = list('nonce'=as.integer(as.POSIXct(Sys.time()))), add_headers("key"=key,"sign"=openssl::sha512("https://www.coinspot.com.au/api/ro/my/balances",key = secret)))
content(result)
Any help much appreciated.

Ive struggled with this too- the coinspot API guide isn't very clear.
I figured out you are meant to encode the postdata in correct json format using sha512 and add that to the sign header. See example below querying account balances on v2 of the api.
require(httr)
api_key = "68z...39k"
api_secret = "71A...48i"
base_url = "https://www.coinspot.com.au/api/v2/ro"
request = "/my/balances"
nonce = as.character(as.integer(Sys.time()))
postdata = paste0('{"nonce":"',nonce,'"}') # important to get the quotes correct
api_sign = digest::hmac(api_secret, postdata, algo="sha512",raw=F)
result = POST(paste0(base_url, request),
body = list("nonce"=nonce),
add_headers(c("key"=api_key,
"sign"=api_sign)),
encode="json"
)
cat(rawToChar(result$content))
You would change what is in postdata based on what you are doing with the API- this is a simple example to build on. If you want to see what postdata should look like prior to encryption in sign, use cat(rawToChar(result$request$options$postfields)) after making a request.

For me, I was missing the JSON string encoded postdata in the body, including the nonce. As soon as I added that, it started working.

Heres my code in c# using Restsharp and Newtonsoft
//put the nonce at the beginning
JObject joBody = JObject.Parse(#"{'nonce': '" + DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() + "'}");
joBody.Merge(originalBody);
var client = new RestClient(_coinspotSettings.BaseURL);
RestRequest request = new RestRequest(endpoint, Method.POST);
request.AddJsonBody(JsonConvert.SerializeObject(joBody));
request.AddHeader("key", coinspotAccount.APIKey);
request.AddHeader("sign", SignData(coinspotAccount, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(joBody))).ToLower());
request.AddHeader("Content-Type", "application/json");
private string SignData(CoinspotAccount coinspotAccount, byte[] JSONData)
{
var HMAC = new HMACSHA512(Encoding.UTF8.GetBytes(coinspotAccount.APISecret));
byte[] EncodedBytes = HMAC.ComputeHash(JSONData);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= EncodedBytes.Length - 1; i++)
stringBuilder.Append(EncodedBytes[i].ToString("X2"));
return stringBuilder.ToString();
}

Related

How to set url or email or special character to cookie in Asp.net core 3.0?

I want to set cookie using asp.net core. i use this code to add cookie
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Append("email", "hello#gmail.com", options);
But in cookie email is not store as it is . its like hello%gmail.com . I can store the url and email into cookie.
Any help. Thank you
As far as I know, if you store the cookie in the response, it will use url encrypt the cookie by default.
When you checked the client cookie, it will store as below:
This will not affect reading cookie in your asp.net core backend codes.
The source codes will decrypt the cookie value by default to let you see the result.
More details, you could refer to below example:
var re = Request.Cookies["email"];
Result:
I try to read the cookie using Javascript and it seems it not show as it should
If you want to read the cookie from js, you should use decodeURIComponent
method to decode it.
More details, you could refer to below codes:
$(document).ready(function () {
var read_cookies = document.cookie;
var split_read_cookie = read_cookies.split(";");
for (i = 0; i < split_read_cookie.length; i++) {
var value = split_read_cookie[i];
value = value.split("=");
if (value[0] == " email" ) {
alert(value[1]);
alert(decodeURIComponent(value[1]));
}
}
});
Result:

Getting complete list of followers from twitter with c#

i want to get complete list of followers using REST API with c# but i only get 20 followers
var postBody = "screen_name=" + Uri.EscapeDataString(screen_name);//
resource_url += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse)request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
JObject j = JObject.Parse(result);
JArray data = (JArray)j["users"];
So with the above codes, i get only 20 followers and from here i see in an answer there is a broken link to a package. Also, i am using only Newton.Json. How do i get complete list of followers?
you have to add parameters to your query with the cursor provided in the json returned in your first query.
https://dev.twitter.com/rest/reference/get/followers/ids
I am not sure I do understand what your problem is. But getting all the followers of a member is not a 'simple' process.
I would suggest that you try out the project Tweetinvi and learn more about this feature here : https://github.com/linvi/tweetinvi/wiki/Get-All-Followers-Code.
You will first want to get all the users ids and then get the user objects via.
Then you can use var userIds = User.GetUsersFromIds(userIds); to get the users from Followers.
NOTE : Remember that Twitter has rate limits on its API. Take a look at https://github.com/linvi/tweetinvi/wiki/Rate-Limits to learn how to use them.
For simplicity I would suggest that you use :
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;

Not getting WeChat Follow response

I have a Debugging Official Account with WeChat. I have entered my public URL and Token into the field provided http://admin.wechat.com/debug/sandbox and also attempted debugging the request with http://admin.wechat.com/debug/
My ASP.Net [.Net4.5] Web API application's POST Method looks like the following :
public HttpResponseMessage PostMessage([FromBody]Strikemedia.Api.WeChat.TextMessage value)
{
if (value == null)
{
var richMediaMessage = new RichMediaMessage();
richMediaMessage.touser = value.FromuserName;
//Create Article
var item = new Article()
{
title = "Didn't receive anything back",
description = "Mind entering 'test'",
picurl = "URL",
url = "URL"
};
var articles = new List<Article>();
articles.Add(item);
richMediaMessage.articles = articles;
richMediaMessage.articleCount = articles.Count;
return Request.CreateResponse(HttpStatusCode.OK, richMediaMessage, "application/json");
}
var exploded = value.Content.Split(' ')[0];
var richMedia = new RichMediaMessage();
richMedia.touser = value.FromuserName;
//Create Article
var article = new Article() {
title = response.KeywordDescription,
description = response.Response,
picurl = "URL",
url = "URL"
};
var _articles = new List<Article>();
_articles.Add(article);
richMedia.articles = _articles;
richMedia.articleCount = _articles.Count;
//Return response
var resp = Request.CreateResponse(HttpStatusCode.OK, richMedia, "application/json");
//resp.RequestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
return resp;
}
It needs to respond with a RichMessageType in JSON format and is received in XML format
Am i missing something or have i overlooked something?
Can you confirm that you have submitted the URL and token into admin.wechat.com and that the URL and token was accepted?
Also note you get XML and you respond with XML no json response.
Have you had a look at: http://youtu.be/kB20Zf51QWU
And then this
http://youtu.be/_2FSzD2B2F0
This is the documentation for the XML can be found when you google "wechat guide to message api"
So if you still not receiving a success message when submitting your app on admin.wechat.com then you can send me your test URL here. To find this URL check your access logs to see exactly what URL wechat is calling. Then post it here. Please note that when you hit the URL as wechat will you should only see the "echostr" printed on the screen (when viewing the source in your browser). No XML no HTML just the echostr.
Also make sure there are no spaces or newlines after or before the "echostr". When you view the source it should only be one line which is the echostr GET param's value.
The XML response only comes in later when you actually start responding to messages from users. For now Wechat is just confirming if your security is setup correctly.
Also note if your server is load balanced you will have to skip the signature validation and build your own validation when a echostr GET parameter gets passed through and only echo the "echostr" param to screen.

WCF Service Call during post

I have given
[WebGet(UriTemplate = "/{year}/{issue}/{article}")]
Article GetArticle(string year, string issue, string article);
[OperationContract]
[WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]
Article AddArticle(string year, string issue, Article article);
My URL is http://localhost:1355/Issues.svc/
if I give this I am fetching all data from the database
http://localhost:1355/Issues.svc/2010/June/A
GetArticle method fires for the filtered data to bring from db.
Similarly I have to call the Add Article(WebInvoke) method to insert data in to the database.
How should I call this method in the browser
how my url should be should I give method=post
check this post help you to achieve the task you want :Create REST service with WCF and Consume using jQuery
You won't be able to send an HTTP post from a browser by just modifying the URL. You'll have to have a web page with a HTML form, some Javascript code, some server-side code, or something else that has the ability to make an HTTP POST request to your service URL.
If you are just wanting to test your service while in development, here's a good HTTP debugging tool that you might want to check out: http://fiddler2.com
You can't use post it using browser url.
Try this code
//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/DemoApp/Default.aspx") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Source : http://www.dotnetthoughts.net/2009/11/10/post-data-using-httpwebrequest-in-c-sharp/

Retrieving HTML pages from a 3rd party log in website with ASP.NET

Our Situation:
Our team needs to retrieve log information from a 3rd party website (Specifically, this log
information is call logs -- our client rents an 866 number. When calls come in, they assist
people and need to make notes accordingly in our application that will correspond with the
current call). Our client has a web account with the 3rd party that allows them to view the
current call logs (date/time, phone number, amount of time on each call, etc).
I contacted the developer of their website and inquired about API or any other means of syncing
our database with their constantly updating database. They currently DO NOT support API. I
informed them of my situation and they are perfectly fine with any way we can retrieve the
information (bot/crawler). *The 3rd party said that they are working on API but could not give
us a general timeline as to when it will be up... and as with every client, they need to start
production ASAP.
I completely understand that if the 3rd party were to change their HTML layout, it may cause a
slight headache for us (sorting the data from the webpage). That being said, this is a temporary
solution to a long term issue. Once they implement their API, we will switch them over to it.
So my question is this:
What is the best way to log into the 3rd party website (see image: http://i903.photobucket.com/albums/ac239/jreedinc/customtf.jpg)
and retrieve certain HTML pages? We have reviewed source codes of webcrawlers, but none of them
have the capability of storing cookies and posting information back to the website (with log in information). We would prefer to do this in ASP.NET.
Is there another way to accomplish logging on to the website, then retrieving said information?
The classes you'll need to use are in the System.Net namespace. Below is some quick and dirty proof of concept code. To login in to a site that uses form login + cookies for security and then scrape the HTML output of a page.
In order to parse the HTML results you'll need to use an additional tool.
Possible HTML parsing tools.
SgmlReader, can convert HTML to XML. You then use .NET's XML features to extract data from the XML.
http://code.msdn.microsoft.com/SgmlReader
HTML Agility Pack, allows XPath queries against HTML documents.
http://htmlagilitypack.codeplex.com/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class WebWorker {
/// <summary>
/// Cookies for use by web worker
/// </summary>
private System.Collections.Generic.List `<System.Net.Cookie` > cookies = new List < System.Net.Cookie > ();
public string GetWebPageContent(string url) {
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url);
System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
request.CookieContainer = cookieContainer;
request.Method = "GET";
//add cookies to maintain session state
foreach(System.Net.Cookie c in this.cookies) {
cookieContainer.Add(c);
}
System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader sReader = new System.IO.StreamReader(responseStream);
System.Diagnostics.Debug.WriteLine("Content:\n" + sReader.ReadToEnd());
return sReader.ReadToEnd();
}
public string Login(string url, string userIdFormFieldName, string userIdValue, string passwordFormFieldName, string passwordValue) {
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url);
System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
request.CookieContainer = cookieContainer;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData = System.Web.HttpUtility.UrlEncode(userIdFormFieldName) + "=" + System.Web.HttpUtility.UrlEncode(userIdValue) +
"&" + System.Web.HttpUtility.UrlEncode(passwordFormFieldName) + "=" + System.Web.HttpUtility.UrlEncode(passwordValue);
request.ContentLength = postData.Length;
request.AllowAutoRedirect = false; //allowing redirect seems to loose cookies
byte[] postDataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
// System.Diagnostics.Debug.Write(WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader sReader = new System.IO.StreamReader(responseStream);
System.Diagnostics.Debug.WriteLine("Content:\n" + sReader.ReadToEnd());
this.cookies.Clear();
if (response.Cookies.Count > 0) {
for (int i = 0; i < response.Cookies.Count; i++) {
this.cookies.Add(response.Cookies[i]);
}
}
return "OK";
}
} //end class
//sample to use class
WebWorker worker = new WebWorker();
worker.Login("http://localhost/test/default.aspx", "uid", "bob", "pwd", "secret");
worker.GetWebPageContent("http://localhost/test/default.aspx");
I used a tool recently called WebQL (its a web scraper tool that lets the developer use SQL like syntax to scrape information from web pages.
WebQL on Wikipedia
This is actually a relatively simple operation. What you need to do is get the page that the screenshot posts back to (something like login.php, etc) and then construct a webrequest to that page with the login data you have. You will most likely get back a cookiecontainer that will have your login cookie to use on all subsequent requests.
You can look at this MSDN article for the basics of how to do it, but their write-up is kind of confusing. Look at the community comments at the end for an example of how to post back page variables (like the username and password). You will need to make sure you pass the cookiecontainer around on subsequent requests.
Unfortunately .NET does not natively have something like WWW::Mechanize, but the Webclient does have an "upload value" which might make it easier. You will still have to manually parse the page to figure out what fields you need to pass.

Resources