How do I add just a username within an authentication header in stripe-payments? - vb.net

I'm trying to get a simple post request to work to create a customer via the Stripe.js API.
https://stripe.com/docs/api/java#authentication
I'm doing this in vb.net and don't want to use the stripe.net library.
I keep getting authorization failed. All I have to pass is the username in the header, or in this case the username is my test api key.
Here's a chunk of the code:
Dim asPostRequest As HttpWebRequest = WebRequest.Create(String.Format(ApiEndpoint))
Dim as_ByteArray As Byte() = Encoding.UTF8.GetBytes(stripeccw.ToString)
asPostRequest.Method = "POST"
asPostRequest.ContentType = "application/json"
'asPostRequest.Headers("Authorization") = "Basic" + apikey
'asPostRequest.Credentials("bearer", apikey)
'asPostRequest.Headers.Add("Authorization") = apikey
'asPostRequest.Credentials("Username") = apikey
'asPostRequest.Credentials = New NetworkCredential(apikey, "")
asPostRequest.ContentLength = as_ByteArray.Length
Dim as_DataStream As Stream = asPostRequest.GetRequestStream()
as_DataStream.Write(as_ByteArray, 0, as_ByteArray.Length)
as_DataStream.Close()
Where I've commented out... those are different ways that I've tried. I know some are just stupid attempts, but just getting frustrated. I know for a fact my api key is correct. I can verify this by navigating to https://api.stripe.com/v1/customers and entering it in for my username only.
Hoping someone can spot something simple :)
Thank you!

If I were in your shoes, the first thing I'd do is take a look at how Stripe.Net does it. Even if you don't want to use that library yourself, that doesn't mean you can't use the source code as a reference.
From Requestor.cs:
internal static WebRequest GetWebRequest(string url, string method, string apiKey = null, bool useBearer = false)
{
apiKey = apiKey ?? StripeConfiguration.GetApiKey();
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
if(!useBearer)
request.Headers.Add("Authorization", GetAuthorizationHeaderValue(apiKey));
else
request.Headers.Add("Authorization", GetAuthorizationHeaderValueBearer(apiKey));
request.Headers.Add("Stripe-Version", StripeConfiguration.ApiVersion);
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Stripe.net (https://github.com/jaymedavis/stripe.net)";
return request;
}
private static string GetAuthorizationHeaderValue(string apiKey)
{
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", apiKey)));
return string.Format("Basic {0}", token);
}
private static string GetAuthorizationHeaderValueBearer(string apiKey)
{
return string.Format("Bearer {0}", apiKey);
}
So it seems there are two ways to do it. You can either use "Bearer" format, which is:
asPostRequest.Headers.Add("Authorization", "Bearer " & apiKey)
or you can use "Basic" format which is:
asPostRequest.Headers.Add("Authorization", _
"Basic " & Convert.ToBase64String(Encoding.UTF8.GetBytes(apiKey & ":")))

Related

Getting (401) UnAuthorized error on some requests not all, but most

I don't think this is a code issue, but we have a list of hundreds of addresses to process. Some return data and we are able to get Long and Lat but most return (401) UnAuthorized errors. What would cause this to happen? We have tried passing Host Headers and everything else, the REST API seems to work better in our development environment but throws way more errors when deployed to our Job Server. Any help on this issue will be greatly appreciated. We would like to understand why some calls work and others don't, we pass the same apiKey each time so this is really confusing. Thanks
Here is a code snippet using c# (Work in progress):
//GET THE LATITUDE AND LONGITUDE BASED OFF THE PHYSICAL ADDRESS
String clientAddress = clientRow["home_address"].ToString() + ", " + clientRow["home_city"].ToString() + ", " + clientRow["home_state"].ToString() + ", " + clientRow["home_zip"].ToString();
Logger.Debug("CLIENT ADDRESS: {0}", clientAddress);
String geocoderUri = "https://geocode.search.hereapi.com/v1/geocode?q=" + clientAddress + "&apiKey=xxxxxxxxxxxxxxxxxxxxx"; //KEY REMOVED FOR POSTING ON STACK OVERFLOW
var syncClient = new WebClient();
var content = syncClient.DownloadString(geocoderUri);
//CREATE THE JSON SERIALIZER AND PARSE OUR RESPONSE
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AddressData));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
var addressData = (AddressData)serializer.ReadObject(ms);
if (addressData.items.Count() > 0)
{
//INSERT THE LATITUDE AND LONGITUDE IN DB
String sLat = addressData.items[0].position.lat.ToString();
String sLong = addressData.items[0].position.lng.ToString();
Logger.Debug("CLIENT GEOLOCATION - Longitude: {0} Latitude: {1}", sLong, sLat);
insertLatLong(sLat, sLong, clientRow["clientID"].ToString(), 1);
}
}
Would you please try to use RestSharp lib for rest api?
Please see below sample code.
var client = new RestClient("https://geocode.search.hereapi.com/v1/geocode?q="+ clientAddress);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer YOUR TOKEN");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

WebClient or WebRequest to get the re-directed URL of the landing page

From the string I parsed from Bing's Pic of the Day, I got the info of the pic to be downloaded, let's say today it is /az/hprichbg/rb/PearlHarborWindows_EN-US8565186567, then we will have full URL of the image be like http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1366x768.jpg
Usually Bing has an image of higher resolutions, so I will download the image 1920x1200 too. It's easy with the URL changed to be like http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg, then give the task to a WebClient such as client1.DownloadFile(url, fileName)
The issue here is, some days, the resolution 1920x1200 is not available, and the download URL of this res.(1920x1200) will be re-directed to the URL of the image /sa/simg/hpb/NorthMale_EN-US8782628354_1920x1200.jpg - as default (you can check it).
So my try was a function to get the return/re-directed URL from the input URL:
Public Function GetWebPageURL(ByVal url As String) As String
Dim Request As WebRequest = WebRequest.Create(url)
Request.Credentials = CredentialCache.DefaultCredentials
Return Request.RequestUri.ToString
End Function
and compare to the input URL to see it they are different, but the result was not as expected.
Could anyone let me know the method to check this re-directed URL, like the return URL after we press Enter and wait for the site to load.
Please give me idea to overcome this obstacle. Thank you!
Notes: Some issues related to access rights on different PCs cause me not to use HttpWebRequest, so I prefer the solution not using HttpWebRequest (WebClient or others are better).
With help from #IvanValadares #AlenGenzić, and suggestion of Proxy for HttpWebRequest from #Jimi, I have come to the fair solution, as the below code:
url1 = "http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg"
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(url1), HttpWebRequest)
myHttpWebRequest.MaximumAutomaticRedirections = 1
myHttpWebRequest.AllowAutoRedirect = True
Dim defaultProxy As IWebProxy = WebRequest.DefaultWebProxy
If (defaultProxy IsNot Nothing) Then
defaultProxy.Credentials = CredentialCache.DefaultCredentials
myHttpWebRequest.Proxy = defaultProxy
End If
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse, HttpWebResponse)
url2 = myHttpWebResponse.ResponseUri.ToString
Label1.Text = url1
Label2.Text = url2
Use AllowAutoRedirect and check the StatusCode.
var webRequest = (HttpWebRequest)System.Net.WebRequest.Create("http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg");
webRequest.AllowAutoRedirect = false;
using (var response = (HttpWebResponse)webRequest.GetResponse())
{
if (response.StatusCode == HttpStatusCode.Found)
{
// Have been redirect
}
else if (response.StatusCode == HttpStatusCode.OK)
{
// Have not been redirect
}
}
Using HttpClient
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync("http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg");
if (response.StatusCode == HttpStatusCode.Found)
{
// Have been redirect
}
else if (response.StatusCode == HttpStatusCode.OK)
{
// Have not been redirect
}
With help from #IvanValadares #AlenGenzić, and suggestion of Proxy for HttpWebRequest from #Jimi, I have come to the fair solution as below:
url1 = "http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg"
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(url1), HttpWebRequest)
myHttpWebRequest.MaximumAutomaticRedirections = 1
myHttpWebRequest.AllowAutoRedirect = True
Dim defaultProxy As IWebProxy = WebRequest.DefaultWebProxy
If (defaultProxy IsNot Nothing) Then
defaultProxy.Credentials = CredentialCache.DefaultCredentials
myHttpWebRequest.Proxy = defaultProxy
End If
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse, HttpWebResponse)
url2 = myHttpWebResponse.ResponseUri.ToString
Label1.Text = url1
Label2.Text = url2
The System.Net.WebException: The remote server returned an error: (407) Proxy Authentication Required. is no longer thrown.

c# console application returning no results

This code runs fine in my windows form application using .net framework 4.6.2 but when I go to make it a console application so it can be ran from the task scheduler I get no results. I think I am losing something in translation.
RestClient restClient = new RestClient("https://api.vault.com");
string refreshToken = #"abc";
string encodedClientIdSecret = Base64Encode("AP-123");
string responseStr = "";
string url = "/v1/OAuth";
dynamic jsonObj = "";
RestRequest request = new RestRequest(url, Method.POST);
request.AddHeader("Authorization", encodedClientIdSecret);
request.AddParameter("grant_type", "refresh_token");
request.AddParameter("refresh_token", refreshToken);
IRestResponse response;
restClient.Execute(request);
response = restClient.Execute(request);
Console.WriteLine(response.Content + " || " + encodedClientIdSecret);
Console.ReadKey();
jsonObj = JsonConvert.DeserializeObject(response.Content);
responseStr = jsonObj.access_token;
return responseStr;
It basically tells me the value cannot be null, and when I look at response.Content I get nothing and the status code comes back as "0". Any thoughts?
Just added:
//Required For SSL/TLS Error Start
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//Required For SSL/TLS Error End
and I got my results. Hope this helps someone else!

GDAX Post Call returns invalid signature

I am trying to make a post request on GDAX.
But I always receive a "invalid signature" message.
GDAX API Docs for creating request + signing: https://docs.gdax.com/#creating-a-request
Preshash string returns the following:
1500627733POST/orders{"price":"1000.0","size":"0.02","type":"limit","side":"sell","product_id":"BTC-EUR"}
My signature method:
public String generateSignature(String requestPath, String method, String body, String timestamp) {
try {
String prehash = timestamp + method.toUpperCase() + requestPath + body;
byte[] secretDecoded = Base64.getDecoder().decode(secretKey);
SecretKeySpec keyspec = new SecretKeySpec(secretDecoded, "HmacSHA256");
Mac sha256 = (Mac) Mac.getInstance("HmacSHA256").clone();
sha256.init(keyspec);
return Base64.getEncoder().encodeToString(sha256.doFinal(prehash.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
My request method:
private boolean placeLimitOrder(String currencyPair, String side, String price, String size)
throws UnirestException {
String timestamp = Instant.now().getEpochSecond() + "";
String api_method = "/orders";
String path = base_url + api_method; //base_url = https://api.gdax.com
String method = "POST";
String b = "{\"price\":\"1000.0\",\"size\":\"0.02\",\"type\":\"limit\",\"side\":\"sell\",\"product_id\":\"BTC-EUR\"}";
JsonNode n = new JsonNode(b);
String sig = generateSignature(api_method, method,b, timestamp);
HttpResponse<JsonNode> rep = Unirest.post(path).header("accept", "application/json")
.header("content-type", "application/json")
.header("CB-ACCESS-KEY", publicKey)
.header("CB-ACCESS-PASSPHRASE", passphrase)
.header("CB-ACCESS-SIGN", sig)
.header("CB-ACCESS-TIMESTAMP", timestamp)
.body(n)
.asJson();
System.out.println(rep.getStatusText()); //Bad Request
System.out.println(rep.getBody().toString()); //invalid signature
System.out.println(sig); //returns something
return false;
}
I also tried to make a API Request Call with Insomnia but it returns the same message ("invalid signature").
Any clues?
Thank you very much in advance!
Looks like you are signing the price order data which is a string, but for the body in the post you are turning it into a json node. Which may not match when gdax decodes the signing and compares the payload data to the decrypted(signed body) when they receive it.
Why not just send the string as the body and remove the ".asJson"?
.body(b)
I was stuck on a similar issue when I was testing the API in C#. After 3 afternoons of trying. I tested sending the data as a string and I was able to get pass the invalid signature error.
I had the same problem.
I used http:
but the right one httpS:
Problem solved.

Using Twitter login API

I am trying to use https://api.periscope.tv/api/v2/loginTwitter to get a response from the server so that I can obtain a cookie for periscope API calls.
I have all of the required values for the request query, but I continue to get the "Bad Request" error (error code 400). Is anyone able to use the loginTwitter API still?
Request headers:
POST /api/v2/loginTwitter?bundle_id=com.bountylabs.periscope&phone_number=&session_key=xxxxxxxx&session_secret=xxxxxxxx&user_id=xxxxxxxx&user_name=xxxxxxxx&vendor_id=81EA8A9B-2950-40CD-9365-40535404DDE4 HTTP/1.1
Authorization:
OAuth oauth_consumer_key="xxxxxxxx",oauth_nonce="cecf203cda273c845cd5121007232666",oauth_signature="xxxxxxxx%3D",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1474786616",oauth_token="xxxxxxxx",oauth_version="1.0"
Oauth signature:
POST&https%3A%2F%2Fapi.periscope.tv%2Fapi%2Fv2%2FloginTwitter%3Fbundle_id%3Dcom.bountylabs.periscope%26phone_number%3D%26session_key%xxxxxxxx%26session_secret%3xxxxxxxx%26user_id%3xxxxxxxx%26user_name%xxxxxxxx%26vendor_id%3D81EA8A9B-2950-40CD-9365-40535404DDE4&bundle_id%3Dcom.bountylabs.periscope%26oauth_consumer_key%3xxxxxxxx%26oauth_nonce%3Dcecf203cda273c845cd5121007232666%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1474786616%26oauth_token%xxxxxxxx%26oauth_version%3D1.0%26phone_number%3D%26session_key%xxxxxxxxMX%26session_secret%xxxxxxxxt%26user_id%xxxxxxxx4%26user_name%xxxxxxxx%26vendor_id%3D81EA8A9B-2950-40CD-9365-40535404DDE4
I have solved the problem thanks to help from another. The problem was that I was passing the request parameters in the URL without encoding them into json. For any that are looking to resolve this problem, here is the solution I arrived at with c#.
var httpWebRequest = ( HttpWebRequest )WebRequest.Create( "https://api.periscope.tv/api/v2/loginTwitter" );
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Method = "POST";
using( var streamWriter = new StreamWriter( httpWebRequest.GetRequestStream() ) ){
string json = "{" +
"\"bundle_id\":\"com.bountylabs.periscope\"," +
"\"phone_number\":\"\"," +
"\"session_key\":\""+final_oauth_token+"\"," +
"\"session_secret\":\""+final_oauth_token_secret+"\"," +
"\"user_id\":\""+user_id+"\"," +
"\"user_name\":\""+screen_name+"\"," +
"\"vendor_id\":\"81EA8A9B-2950-40CD-9365-40535404DDE4\"" +
"}";
streamWriter.Write( json );
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = ( HttpWebResponse )httpWebRequest.GetResponse();
using( var streamReader = new StreamReader( httpResponse.GetResponseStream() ) ){
var result = streamReader.ReadToEnd();
display.Text = "cookie: "+result;
}
}
The result yields a cookie in the server's response.
Reference for more detail on this process: Twitter login POST request in Periscope API