RestSharp call to eBay oauth2 user token - vb.net

I am trying to get eBay user tokens for my users using the identity api. I finally got it to work in Postman. Converted the call from Postman to a restsharp call from a vb.net test app. The Postman call works, the VB call returns "404 Not Found". Looked at the two calls using Fiddler. The only difference I can see is that the Postman call goes to:
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token";
and the VB app call goes to
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token/1"
It would appear that somewhere the VB app is appending "/1" to the api url. Not sure where this is occurring as I can step through the code as it executes and don't see it.
Is there a property in RestSharp that might cause this value to be appended?
EDIT added code. This code is supposed to return a user token and refresh token from eBay. It is taken pretty much from Postman with mods to work with the latest version.
Async Sub RSGetCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com/identity/v1/oauth2/token")
Dim request As RestRequest = New RestRequest(Method.Post)
sCode = WebUtility.UrlDecode(sCode)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItOD..........................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode)
.AddParameter("redirect_uri", "Murphys_Creativ-Mu...........")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub```

I got it to work by slightly reformating the code. See below.
Async Sub PostRestCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com")
Dim request As RestRequest = New RestRequest("identity/v1/oauth2/token", Method.Post)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItODc2OGMzZWZkYT..............................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode) '"v^1.1#i^1#I^3#p^3#f^0#r^1#t^Ul41Xzg6NEN.......................................")
.AddParameter("redirect_uri", "Murphys_Creativ-Mu......................")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub

Related

Need help in solving error in HTTP GET request

Need help in solving error in HTTP GET request [closed]
I have the following code in VB.NET framework which should pull the data in json format and add it to a list view control using GET request. However I am getting following error:
System.Threading.Tasks.Task.FromResult(System.Net.Http.HttpResponseMessage)
Dim client = New HttpClient()
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{Subscription-Key}")
Dim uri = "https://example.com/" & SearchKey
Dim response = client.GetAsync(uri)
lstMer.Items.Add(response.ToString)
Initially I wrote the following code in VBA and it was working fine:
Dim jsonText as String
Set req = New MSXML2.ServerXMLHTTP60
key_id = "{Subscription-Key}"
key_header_name = "Subscription-Key-Id"
liveURL = "https://example.com/" & SearchKey
req.Open "GET", liveURL, False
req.setRequestHeader {Subscription-Key-Id}, {Subscription-Key}
req.setRequestHeader "Host", "site Address"
req.send
jsonText = req.responseText
The requirement is to get the headers from URL and fill a list view.
I think I understand. You don't get an error
System.Threading.Tasks.Task.FromResult(System.Net.Http.HttpResponseMessage)
rather you get that as a result of response.ToString(). This is because you are calling client.GetAsync(uri) directly, which returns a Task.FromResult<TResult>. However, it is meant to be run async, and there are some convenient keywords for achieving this, namely Async / Await. If you await the task, instead of returning a Task.FromResult<TResult>, it will return a TResult. So change your code to do just that
Private Async Sub Foo()
Dim client = New HttpClient()
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{Subscription-Key}")
Dim uri = "https://example.com/" & SearchKey
Dim response = Await client.GetAsync(uri)
lstMer.Items.Add(response.ToString)
End Sub
See HttpClient.GetAsync and about what it returns Task.FromResult

Stripe Payment with VB - 400 Bad Request

I'm trying to make a stripe payment work from a VB website. I know, I know, "I should use C#". I can't because the site is already in VB. Nothing I can do about it.
Anyway, I have most of it figured out:
User clicks submit button with valid info
Form submits to Stripe
Stripe sends a token back
A jQuery ajax function posts the data to donate/pay-by-stripe
I have this line of code in my Global.asax.vb
routes.MapRoute("pay-by-stripe", "donate/pay-by-stripe", New With{.controller = "Dynamic", .action = "PayByStripe"})
So my PayByStripe function in the Dynamic Controller looks like this:
Function PayByStripe()
''The Stripe Account API Token
Dim STR_Stripe_API_Token As String = "sk_test_*****"
''The Stripe API URL
Dim STR_Stripe_API_URL As [String] = "https://api.stripe.com/v1/charges"
''The Stripe Card Token
Dim token As String = HttpContext.Request.Form("token")
Dim description As String = HttpContext.Request.Form("description")
Dim amount As Single = HttpContext.Request.Form("amount")
''Creates a Web Client
Dim OBJ_Webclient As New System.Net.WebClient()
''Creates Credentials
Dim OBJ_Credentials As New System.Net.NetworkCredential(STR_Stripe_API_Token, "")
''Sets the Credentials on the Web Client
OBJ_Webclient.Credentials = OBJ_Credentials
''Creates a Transaction with Data that Will be Sent to Stripe
''Dim OBJ_Transaction As New System.Collections.Specialized.NameValueCollection()
Dim OBJ_Transaction As NameValueCollection = New NameValueCollection()
OBJ_Transaction.Add("amount", amount)
OBJ_Transaction.Add("currency", "usd")
OBJ_Transaction.Add("address-country", "US")
OBJ_Transaction.Add("description", "")
OBJ_Transaction.Add("card", token)
''The Stripe Response String
Dim STR_Response As String = Encoding.ASCII.GetString(OBJ_Webclient.UploadValues(STR_Stripe_API_URL, OBJ_Transaction))
'Response.Redirect("/donate/?transaction=success");
Return STR_Response
End Function
I'm getting a 400 bad request error on the STR_Response line:
Dim STR_Response As String = Encoding.ASCII.GetString(OBJ_Webclient.UploadValues(STR_Stripe_API_URL, OBJ_Transaction))
I'm a VB and Stripe noob, and not sure what this means. My main theory now is that it's because I don't have a /donate/pay-by-stripe/ page, but I don't know what I'd even put in there if I did create it.
Any help would be great!
That's a webservice you are calling, right?
A 400 Bad Request with a webservice means your XML request is malformed.
Example, in my request, part of it is a UTC in a certain date format. Example: <pp:utc>2013-05-24 2025</pp:utc>
So, if I were to malform my request to this <pp:utc>2013-05-24 2025</pp:utc2> it would result in:
HTTP/1.1 400 Bad Request
Cache-Control: private
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.5
So, check your request and make sure everything is properly formatted.
EDIT: just noticed I put the "incorrect" utc tags incorrectly.
Please notice the opening tag <pp:utc> is being closed with a </pp:utc2>, which is the reason why you see 400 bad request
I had to put my password in System.Net.NetworkCredentials, and address-country is not a usable field. The only usable fields when submitting a charge are amount, currency, description, and card (which is actually the token). This is the final, working version of my PayByStripe Function in my Dynamic Controller:
Function PayByStripe()
'' The Stripe Account API Token - change this for testing
Dim STR_Stripe_API_Token As String = ""
If (this_is_a_test) Then
' Test Secret Key
STR_Stripe_API_Token = "sk_test_***"
Else
' Prod Secret Key
STR_Stripe_API_Token = "sk_live_***"
End If
''The Stripe API URL
Dim STR_Stripe_API_URL As [String] = "https://api.stripe.com/v1/charges"
''The Stripe Card Token
Dim token As String = HttpContext.Request.Form("token")
Dim description As String = HttpContext.Request.Form("description")
Dim amount As Single = HttpContext.Request.Form("amount")
''Creates a Web Client
Dim OBJ_Webclient As New System.Net.WebClient()
''Creates Credentials
Dim OBJ_Credentials As New System.Net.NetworkCredential(STR_Stripe_API_Token, "YOUR PASSWORD FOR STRIPE")
''Sets the Credentials on the Web Client
OBJ_Webclient.Credentials = OBJ_Credentials
''Creates a Transaction with Data that Will be Sent to Stripe
Dim OBJ_Transaction As New System.Collections.Specialized.NameValueCollection()
OBJ_Transaction.Add("amount", amount)
OBJ_Transaction.Add("currency", "usd")
OBJ_Transaction.Add("description", description)
OBJ_Transaction.Add("card", token)
''The Stripe Response String
Dim STR_Response As String = Encoding.ASCII.GetString(OBJ_Webclient.UploadValues(STR_Stripe_API_URL, OBJ_Transaction))
Return STR_Response
End Function
I've never had to pass in my password when connecting to Stripe's API. Simply pass in your private API Key through an authorization header with no password. It may also help to pass in a version header as well, something Stripe recommends. The following lines of card are in C#, I know your question was in VB, but I'm sure you can easily adaptive this:
webrequest.Headers.Add("Stripe-Version", "2014-12-22");
webrequest.Headers.Add("Authorization", String.Concat("Basic ", (Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", "sk_test_XXXXXXXXXXXXXXXXXXX"))))));
Also, it may help to know that Stripe sends a 400 Bad Request when an expired or invalid card token is sent.

How to POST a JSON to a specific url using VB.NET?

I'm a newbie about web services in VB.NET. I'm making a desktop application that will talk to JIRA (http://www.atlassian.com/software/jira/). They provided a REST api that I decided to use. The first step is to login which they say that...
"To log in to JIRA, you need to POST a username and password in JSON format..."
{"username" : "admin", "password" : "admin"}
to this url...
https://addressgoeshere (we are using https)
Can someone provide me a sample code to do this so I can have a guide and a good start?
Here is the code to post json effectively. The variable res is able to give you the responce to your query
remember to import
System.Net
System.IO
System.text
by using
Imports
and then the import names
to bypass expired ssl certificate check this: http://blog.jameshiggs.com/2008/05/01/c-how-to-accept-an-invalid-ssl-certificate-programmatically/
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim response As String
Dim request As WebRequest
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = contentType
request.Method = method
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function
to use this function
Dim data = Encoding.UTF8.GetBytes(jsonSring)
Dim result_post = SendRequest(uri, data, "application/json", "POST")
--EDIT--
The linked page has expired by now. Here is a working archived copy:
https://web.archive.org/web/20110924191356/http://blog.jameshiggs.com/2008/05/01/c-how-to-accept-an-invalid-ssl-certificate-programmatically/
For 'The underlying connection was closed:' error include these 2 lines of code after the line ...WebRequest.Create(Url) -it should work
System.Net.ServicePointManager.UseNagleAlgorithm = False
System.Net.ServicePointManager.Expect100Continue = False

Getting multiple SQL Reports with HttpWebRequest - 401 Unauthorized

I am trying to call multiple SQL Reporting Services Reports, get the .pdfs back, then append them together. I have no problems appending .pdfs, but I'm getting an error on the second report. Here's some example code:
Dim httpReq As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(strLink), System.Net.HttpWebRequest)
Dim creds As New System.Net.NetworkCredential
creds.Domain = "MyDomain"
creds.UserName = "UserName"
creds.Password = "Password"
httpReq.Credentials = creds
Dim httpResp As System.Net.HttpWebResponse = DirectCast(httpReq.GetResponse(), System.Net.HttpWebResponse)
httpResp.Close()
httpReq = Nothing
httpResp = Nothing
Dim SecondHttpReq As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(strSecondLink), System.Net.HttpWebRequest)
SecondHttpReq.Credentials = creds
Dim SecondHttpResp As System.Net.HttpWebResponse = DirectCast(SecondHttpReq.GetResponse(), System.Net.HttpWebResponse)
When I try to create the second HttpResponse, I get a 401 Unauthorized error. When I check the SecondHttpReq object when it errors, I find that the Credentials property has been set back to Nothing. I've tried using a CookieContainer to no avail. I'd really rather not have to write a parent/sub report to get these together, so I'd like to hear other options. Thanks in advance.
Fixed. Someone changed permissions on our report server without notifying anyone.

How to use HttpWebRequest to download file

Trying to download file in code.
Current code:
Dim uri As New UriBuilder
uri.UserName = "xxx"
uri.Password = "xxx"
uri.Host = "xxx"
uri.Path = "xxx.aspx?q=65"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri.Uri), HttpWebRequest)
request.AllowAutoRedirect = True
request = DirectCast(WebRequest.Create(DownloadUrlIn), HttpWebRequest)
request.Timeout = 10000
'request.AllowWriteStreamBuffering = True
Dim response As HttpWebResponse = Nothing
response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim s As Stream = response.GetResponseStream()
'Write to disk
Dim fs As New FileStream("c:\xxx.pdf", FileMode.Create)
Dim read As Byte() = New Byte(255) {}
Dim count As Integer = s.Read(read, 0, read.Length)
While count > 0
fs.Write(read, 0, count)
count = s.Read(read, 0, read.Length)
End While
'Close everything
fs.Close()
s.Close()
response.Close()
Running this code and checking the response.ResponseUri indicates im being redirected back to the login page and not to the pdf file.
For some reason its not authorising access what could I be missing as Im sending the user name and password in the uri? Thanks for your help
You don't need all of that code to download a file from the net
just use the WebClient class and its DownloadFile method
you should check and see if the site requires cookies (most do), i'd use a packet analyzer and run your code and see exactly what the server is returning. use fiddler or http analyzer to log packets
With UWP, this has become a more pertinent question as UWP does not have a WebClient. The correct answer to this question is if you are being re-directed to the login page, then there must be an issue with your credentials OR the setting (or lack of) header for the HttpWebRequest.
According to Microsoft, the request for downloading is sent with the call to GetResponse() on the HttpWebRequest, therefore the downloaded file SHOULD be in the stream in the response (returned by the GetResponse() call mentioned above).