Converting Curl Request Into C# ASP.NET Web Request Stripe Payments API - c#

curl https://api.stripe.com/v1/charges
\ -u sk_test_BQokikJOvB432343iI2HlWgH4olfQ2:
\ -d amount=400
\ -d currency=usd
\ -d card=tok_15CVG02eZvKYlo2CDVUHUs56
I'm new to curl and need to convert the above curl request into an ASP.NET web request. I believe the -d are post parameters, but I am unsure how to pass in the -u and what -u stands for. Below is the code I have so far. FYI this is for the Stripe Payment Gateway, I can't use the ASP.NET Library because I can add any dlls to the solution I am running so I am using their CURL API.
string formencodeddata = "amount=400&currency=usd&card=tok_15CVG02eZvKYlo2CDVUHUs56";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp("https://api.stripe.com/v1/charges");
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
using (Stream postStream = webrequest.GetRequestStream()) {
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();

This was my final solution:
var postUrl = new StringBuilder();
postUrl.Append("card=");
postUrl.Append(token);
postUrl.Append("currency=usd");
postUrl.Append("&x_amount=");
postUrl.Append(transactionAmount.ToString());
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(postUrl.ToString());
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.Create(Url);
webrequest.Method = "POST";
webrequest.UserAgent = "Stripe Payment Processor";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Stripe-Version", "2014-12-22");
webrequest.Headers.Add("Authorization", String.Concat("Basic ", (Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", this.PrivateKey))))));
using (Stream postStream = webrequest.GetRequestStream())
{
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
StreamReader reader = null;
string stripeResponse;
try
{
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
reader = new StreamReader(responseStream);
stripeResponse = reader.ReadToEnd();
}
catch (WebException exception)
{
using (WebResponse response = exception.Response)
{
using (Stream data = response.GetResponseStream())
using (reader = new StreamReader(data))
{
stripeResponse = reader.ReadToEnd();
}
}
}

Related

Why same code sending different HTTP request in localhost and test server?

My code is sending a HTTP POST request with a JSON body. It is working
as expected in localhost but when I deploy it on server then it is
working differently. On my local machine response is okey but on server the response says request is not same !
var request = WebRequest.Create($"{baseUrl}{resourceAddress}");
request.Method = "POST";
request.ContentType = "application/json";
var json = JsonConvert.SerializeObject(requestBody);
request.ContentLength = json.Length;
using (var webStream = request.GetRequestStream())
{
using (var requestWriter = new StreamWriter(webStream, Encoding.ASCII))
{
requestWriter.Write(json);
}
}
try
{
var webResponse = request.GetResponse();
using var webStream = webResponse.GetResponseStream() ?? Stream.Null;
using var responseReader = new StreamReader(webStream);
var response = responseReader.ReadToEnd();
var paymentUrlResponse = JsonConvert.DeserializeObject<PaymentUrlResponse>(response);
if(paymentUrlResponse.Result.ResultCode != "00")
{
throw new Exception("Failed to get URL. Http Response: OK , Result Code: " + paymentUrlResponse.Result.ResultCode);
}
_httpContextAccessor.HttpContext.Response.Redirect(redirectionUrl);
}

Connecting to a REST webservice in C#

I am not familiar with REST webservices, but I am trying to get a response from one of them in a C# application.
I am trying to connect to the webservice and authenticate my application to get a token. For this, I have an URL, a login and a password.
When I call the authentication method with cURL tool, I get a « success :true» answer, followed with the token string.
But when I try to do the same with my C# code, I always get a « success :false» answer and no token.
Can somebody help me to understand what is missing in my C# code to get the correct answer ? Thank you.
The cURL request (given by the webservice owner) is:
curl -X POST -d "{\"user\":\"mylogin\",\"pwd\":\"mypassword\"}" \
-H "Content-Type: application/json" http://webserviceURL/authenticate
My code is the following : (restlogin, restpassword and resturl are three strings and get the correct values for the connection. The resulting string is obtained in the variable nammed token).
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
request.Method = "POST";
request.Credentials = new NetworkCredential(restlogin, restpassword);
request.ContentType = "application/json";
request.Timeout = 30000;
request.ReadWriteTimeout = 30000;
request.Accept = "application/json";
request.ProtocolVersion = HttpVersion.Version11;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
token = reader.ReadToEnd();
reader.Close();
reader.Dispose();
response.Close();
}
}
As per my comment to the question, you are not sending your credentials in the request body. With request.Credentials you're setting the Authentication Header in your HttpRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
request.Method = "POST";
request.ContentType = "application/json";
request.Timeout = 30000;
request.ReadWriteTimeout = 30000;
request.Accept = "application/json";
request.ProtocolVersion = HttpVersion.Version11;
// Set your Response body
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"user\":\"" + restlogin + "\"," +
"\"pwd\":\"" + restpassword + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
token = reader.ReadToEnd();
reader.Close();
reader.Dispose();
response.Close();
}
}

C# HttpWebResponse gives back encoded response

I'm making a HttpWebRequest to a server. This is in JSON. Now, the response is encoded and looks like this:
�\b\0\0\0\0\0\0��A� #ѻ�U�0l�u�\v�v�...
I can see that my request succeeded in Fiddler. And I can see the response of the server is the right one. But, also in fiddler it requires me to decode the answer first.
I have no idea how to decode this in C#.
Here is a bit of sample code that should do exactly what you want. BatchCollection in my case is my own object that maps to the JSON and so it can be mapped after its de-compressed.
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Headers = headers;
request.Headers.Add("Content-Encoding", "gzip");
request.AutomaticDecompression = DecompressionMethods.GZip;
request.ContentType = "application/json";
var json = JsonConvert.SerializeObject(batchCollection);
using (Stream requestStream = request.GetRequestStream())
{
var buffer = Encoding.UTF8.GetBytes(json);
using (GZipStream compressionStream = new GZipStream(requestStream, CompressionMode.Compress, true))
{
compressionStream.Write(buffer, 0, buffer.Length);
}
}
var response = (HttpWebResponse)request.GetResponse();
BatchCollection batchOut = null;
using (Stream responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var jsonOut = reader.ReadToEnd();
reader.Close();
batchOut = JsonConvert.DeserializeObject<BatchCollection>(jsonOut);
}
return batchOut;

HttpWebRequest method GET/POST not working?

I am working with GoogleApi. I want to get accesstoken as response using Google api. when I am sending httpwebrequest for getting access token then
When I used :- request.Method = "POST"
Exception:- HTTP method POST is not supported by this URL
When I used :- request.Method = "GET"
Exception:- System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type
The actual request might look like:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
A successful response is returned as a JSON array, similar to the following:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
My Code is :-
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
request.Method = "POST";
request.ContentType = "application/json";
//request.KeepAlive = false;
// request.Headers[HttpRequestHeader.Authorization] = "";
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"code\":\"4/M1IIC8htCuvYORuVJK16oadDb3Gd.cigIKgaPjvUYXE-sT2ZLcbSrckCLgwI\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"," + "\"client_secret\":\"MXjKvevD_cKp5eQWZ1RFXfdo\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"grant_type\":\"authorization_code\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
var sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}
This is the problem:
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
That's not the URL you showed originally. That's just the domain root. You need:
var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
I've removed the # as your string doesn't include any line breaks or backslashes, so there's no benefit in using a verbatim string literal.
(Additionally, I'd expect this to be covered in the Google Client APIs - is it not?)

C# HTTP request to PHP file to JSON

I would like to write a class in c# which should send an HTTP request (post) to a PHP file which is on my server in order to retrieve a json object.
This is the code I've got:
public void SendRequest(){
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("url");
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
}
Is that what I need? What do you think I should change or improve?
Thank you for your help.
You need to post data and read the response:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string yourPostData = "Your post data";
string sreverResponseText;
byte[] postDataBytes = Encoding.UTF8.GetBytes(yourPostData);
request.ContentLength = yourPostData.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
using (response = (HttpWebResponse)request.GetResponse())
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
sreverResponseText = streamReader.ReadToEnd();
Now what you are looking for is in sreverResponseText, also you can access headers from response.Headers.ToString()

Categories