Google OAuth2 Error 400 when exchanging for an Access Token - api

I am receiving a "400 Bad Request" error when using the following VBA code to exchange a valid Authorization token for an access token in the Google API. Can anyone shed light as to why, I have been struggling with this one for over a week.
Dim http As MSXML2.XMLHTTP
Dim sUrl As String
Dim sUrlHeader As String
Dim svarbody As String
Set http = New MSXML2.XMLHTTP
sUrl = "https://accounts.google.com/o/oauth2/token? HTTP/1.1"
http.Open "POST", sUrl
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
svarbody = "code=4%2FXAjmXiUlBXUAUGCnMvNKsxdyuJEJ.8kfzzrqo3wwTuJJVnL49Cc9gML_lbgI&" & _
"client_id=50487549202#-q27v28nvhmjhc0uobq35tjn09lhrh47r.apps.googleusercontent.com&" & _
"redirect_uri=http%3A%2F%2Flocalhost&" & _
"scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds&" & _
"client_secret=<secret delete for this post>&" & _
"grant_type=authorization_code"
http.send svarbody
Me.Text3 = http.status & vbCrLf & http.statusText & vbCrLf & http.responseText

this is a very very common problem. You may try to solve it doing many approaches and tests... but...
The really one you should try in the first place is:
UPDATE YOUR SERVER/COMPUTER WINDOWS CLOCK, USE time.nist.gov (or brothers). Double-click in your Windows Hour-Date (on the bottom of your screen and change Internet Time in this way)
SntsDev

In my experience using Oauth 2.0 in VBA this error happens when you use the code more than once for requesting a token. The usage sequence I use based on the documentation and experience is:
access GET https://accounts.google.com/o/oauth2/auth once for geting the code
access POST https://accounts.google.com/o/oauth2/token once for geting the token
after that use the token as long as it is valid

It is possible that you need set up billing info in your google account.

Related

How to POST JSON data to an API using VBscript

I am currently working on a signup form and I want users to be pushed to my hubspot account upon sign up. The form is built in a .asp file format using HTML, CSS, and VBscript. I want the user to fill out all of the required fields and then send their responses to Hubspot using their Create Contact API endpoint.
The form itself is built out and working, now all I need to do is link up the API POST request. I am not familiar with VBscript or how one could go about sending JSON data to an API using VB. I started out by just trying to send dummy data that would be easily searchable figuring I can work on making the values dynamic later, but even this won't work. This is the code that I have written directly in the markup. Any help is appreciated!
<%
Dim objXmlHttpMain, URL, strJSONToSend
strJSONToSend = "{'properties': [{'property': 'email','value': 'testingapis#hubspot.com'},{'property': 'firstname','value': 'Adrian'},{'property': 'lastname','value': 'Mott'},{'property': 'website','value': 'http://hubspot.com'},{'property': 'company','value': 'HubSpot'},{'property': 'phone','value': '555-122-2323'},{'property': 'address',},{'property': 'city','value': 'Cambridge'},'property': 'state','value': 'MA'},{'property': 'zip','value': '02139'}]}"
URL="https://api.hubapi.com/contacts/v1/contact/?hapikey=df670ac6-cc2d-452d-a571-11d0374e515e"
Set objXmlHttpMain = CreateObject("Msxml2.ServerXMLHTTP")
On Error Resume Next
objXmlHttpMain.open "POST",URL, False
If Err Then
WScript.Echo Err.Description & " [0x" & Hex(Err.Number) & "]"
WScript.Quit 1
End If
On Error Goto 0
objXmlHttpMain.open "POST",URL, False
objXmlHttpMain.setRequestHeader "Accept", "application/json>"
objXmlHttpMain.setRequestHeader "Content-Type", "application/json"
objXmlHttpMain.send strJSONToSend
set objJSONDoc = nothing
set objResult = nothing
%>

Posting with an open event

Action: Trying to 'post' excel data to a webpage that the user sees/uses with a vba code event.
Issue: I can open a window with a get, or I can xmlhttp with a post and a get a response variable, but neither is what I need. I need to POST login information (a service account) from baked in vba code on a button to POST and open a browser.
The webpage is behind Spring Security and the service account credentials should not be known to the user, it's hidden in a protected workbook/vba. I need to post those over to the url.
--> How do I open AND post at the same time?
What I need is the excel equivalent of an HTML form post with a
target=_blank
attribute in vba. Is this possible?
I've tried both
ShellExecute
functions
and
xmlhttp
methods
but both only give me half of the package.
Any advice?
Adding to what #Florent B. has posted, check whether the cookie is set when calling the login page (which I assume) or really when posting the login data.
Dim xhttp As MSXML2.XMLHTTP ' make sure you reference to MSXML!
Dim strCookie As String
Set xHttp = New MSXML2.XMLHTTP
XMLHttp.Open "GET" TheURLOfYourLogInPage
If xHttp.Status = 200 Then
strCookie = xHttp.getResponseHeader("Set-Cookie")
End If
Check your web browser for what is sent to the server when login in, probably something like "username=" & YourUserName & "&password=" & YourPassword & "&cookie=" & strCookie Declare another string variable (I will call it strTicker) and fill it accordingly, then
xHttp.Open "POST", "URLOfYourLoginPage"
xHttp.setRequestHeader "Cookie", strCookie
xHttp.send strTicker

'401 Unauthorised' when calling a url with Net.WebClient

In my app I'm making a call to an API.
I start by building the URL...
Dim url As String = "http://" & Home.sn_username & ":" & Home.sn_password & "#" & Home.sn_ip & "/command.htm?number=" & phonenumber
url = Replace(url, Chr(13), "")
I want to make sure the URL its attempting to call is correct, so i've dumped it to the console...
Console.WriteLine("DIALING: " & url)
The URL is spot on, so finally I call the URL with Net.Webclient...
Dim client As New Net.WebClient
client.DownloadString(url)
This does not work.
An exception is thrown and I get a 401 Unauthorised error.
Am i doing something wrong?
The final URL is like this:
http://username:passwrd#domainame.com/command.htm?Number=01611234565
If i take that and paste it directly into my browser it works fine! (its for an IP phone API... my desk phone dials the number!).
Do i need to look at a different way of supplying the credentials or something?
Thanks in advance!
Try adding your authentication credentials directly to the WebClient instead of prepending them before the url before executing.
client.Credentials = new NetworkCredential(Home.sn_username, Home.sn_password)

REST Interacting with BigCommerce from VB EXCEL

NOTE: Further research (and thick skin, and lots of coffee) has lead me here where it suggests that the store cannot receive the uid and pwd in the URL, and I gather from the PHP examples here that the transmission needs to be encrypted. Is this my problem? If so I have not been able to find anything on how to work around this.
I would be happy if the open() command prompted the UID & PWD window to open and I can manually input the values. Does anyone have a suggestion. Thanks!
I am learning how to use the BigCommerce APIs and I am programming in VB / XL to be able to directly post / retrieve from all fields in the store's DB.
I have never coded on this before (although I get around VB OK) and I am stuck. I have the following code:
Const URL As String = "https://www.myurl.com/api/v2/brands.json"
Public Sub Test()
Dim xmlHttp As Object
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlHttp.Open "GET", URL, False, "myid", "mytoken"
xmlHttp.setRequestHeader "Content-Type", "application/json"
xmlHttp.send
Dim html As MSHTML.HTMLDocument
Set html = New MSHTML.HTMLDocument
html.body.innerHTML = xmlHttp.ResponseText
Range("A1").Value = html.body.innerHTML
End Sub
What I get back is "401" or more precisely:
[{"status":401,"message":"No credentials were supplied in the request."}]
The credentials are valid and working, as if I place the URL in my browser and submit it, the pop up for UID & PWD comes up, and once I place the values I am using in the code, the resulting BRANDS list appears in the browser.
Additionally, if I add a "rand num" to the URL to ensure the returned data is not cached as suggested here, then the request looks like this:
xmlHttp.Open "GET", URL & "&t=" & WorksheetFunction.RandBetween(1, 99), False, `"myid", "mytoken"`
and the response back from BC changes to:
406</STATUS><MESSAGE>The requested content type is not available.</MESSAGE></ERROR></ERRORS>
I have also tried this (where UID and PWD are the correct values):
xmlHttp.Open "GET", URL & "&user=UID" & "&password=PWD", False
and i get:
406</STATUS><MESSAGE>The requested content type is not available.</MESSAGE></ERROR></ERRORS>
Can anyone help me understand pls. I have followed examples at MSDN, but I am still stuck. The BC API site is poor in examples (none actually!) for VB.
Thank you
Sorted! BC required this:
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlHttp.Open "GET", URL_Cat, UID, PWD
xmlHttp.setRequestHeader "Content-Type", "application/json"
xmlHttp.setRequestHeader "Authorization", "Basic " & Base64Encode(UID & ":" & PWD)
xmlHttp.send
I got Base64Encode code from here. Hope this helps someone.

Not understanding why WinHTTP does NOT authenticate certain HTTPS resource

I'd be extremely grateful for any kind of help that may help me resolving the problem.
From Excel VBA code I need to download & parse CSV file from HTTPS site https://redmine.itransition.com/. I try to use WinHTTP to get the file. However, I can't understand why authentication does not work. Here is the piece of related code:
TargetURL = "https://redmine.itransition.com/projects/pmct/time_entries.csv"
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Option(4) = 13056 ' WinHttpRequestOption_SslErrorIgnoreFlags 13056: ignore all err, 0: accept no err
HTTPReq.Open "GET", TargetURL, False
HTTPReq.SetCredentials "UN", "PW", 0
HTTPReq.send
returns the following response (only certain strings are listed):
Content-Type: text/html; charset=utf-8
Status: 406
X-Runtime: 5
However, if I send "Cookie" string from Firefox cookie after successful manual authentication using
HTTPReq.setRequestHeader "Cookie", SetCookieString
HTTPReq.send
I easily get the expected file. Of course I'm not happy with such solution, and want to perform true WinHTTP authentication. However, I can't understand what's wrong or what I miss in my code. Most likely I have to use .SetClientCertificate method, but this is unclear for me - which cert is required?
Or, being more general: which WinHTTP methods or functions I should use for debugging to find out which step is blocking / incorrect and prevents me from correct authentication? I spent 2 weeks seeking through MSDN and various resources, but still have no solution.
Thanks in advance for your suggestions!
The above #Alex K. response was exactly what I was looking for soooo long!
With the help of Firebug and MSDN I finished with 3 requests:
GET request to collect authenticity_token data from login page using RegEx
POST request to authenticate & collect required Cookie string from response
GET request to finally obtain my beloved CSV
The following piece of code which is working as expected:
Set RegX_AuthToken = CreateObject("VBScript.RegExp")
' Below Pattern w/o double-quotes encoded: (?:input name="authenticity_token" type="hidden" value=")(.*)(?:")
RegX_AuthToken.Pattern = "(?:input name=" & Chr(34) & "authenticity_token" & Chr(34) & " type=" & Chr(34) & "hidden" & Chr(34) & " value=" & Chr(34) & ")(.*)(?:" & Chr(34) & ")"
RegX_AuthToken.IgnoreCase = True
RegX_AuthToken.Global = True
TargetURL = "https://redmine.itransition.com/login"
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Open "GET", TargetURL, False
HTTPReq.Send
Set Token_Match = RegX_AuthToken.Execute(HTTPReq.ResponseText)
AuthToken = Token_Match.Item(0).SubMatches.Item(0)
PostData = "authenticity_token=" & AuthToken & "&back_url=https://redmine.itransition.com/" & "&username=" & UN & "&password=" & PW & "&login=Login »"
HTTPReq.Open "POST", TargetURL, False
HTTPReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
HTTPReq.Send (PostData)
SetCookieString = HTTPReq.GetResponseHeader("Set-Cookie")
TargetURL = "https://redmine.itransition.com/projects/pmct/time_entries.csv"
HTTPReq.Open "GET", TargetURL, False
HTTPReq.setRequestHeader "Cookie", SetCookieString
HTTPReq.Send
The following URL was helpful in building POST request: http://tkang.blogspot.com/2010/09/sending-http-post-request-with-vba.html
You need to load that page with no credentials, grab what looks like
the volatile field authenticity_token from the generated form & post
that along with username & password to /login.
Alex K. - thanks again for the brilliant suggestion! (:
The logon at https://redmine.itransition.com/ is just an HTML form that posts a username & password to a script at /login.
This is not compatible with SetCredentials which is designed for server based authentication schemes like basic/digest/ntlm.
You need to load that page with no credentials, grab what looks like the volatile field authenticity_token from the generated form & post that along with username & password to /login.
If its a session based system it will response with the set-cookie header + data you need to use in subsequent request.
And one more thing (in addition to the above solution) one should be aware of in case of using POST requests similar to the above code: for some obscure reason I still got once in 4-5 times (or even more) the hated 406 response from the website, which means in my case auth is NOT complete. After hours of step-by-step debugging I happily caught the cause: auth token value may have + signs, and from analyzing an arrow of several dozens auth tokens / response codes I discovered that +-containing tokens exactly match 406 codes.
The solution became pretty obvious: safely URL-encode +es for the PostData. With the help of http://www.blooberry.com/indexdot/html/topics/urlencoding.htm I finally came up to the following:
PostData = "authenticity_token=" & Replace(AuthToken, "+", "%2B", vbTextCompare) & _
"&back_url=https://redmine.itransition.com/projects/" & Trim(RedmineProject) & _
"/time_entries" & "&username=" & UN & "&password=" & PW & "&login=Login »"
+es are replaced by %2Bs, and this was that - no more 406s!)
The other special chars do not matter in my case, but the lesson was learned. Hope this will save several hours of life for someone else!