Exchanging Authorization Code for Access Token for Google Calendar API with VBA and Oauth2 - vba

After successfully obtaining the authorization code, I am having trouble exchanging it for an access token and refresh token while trying to access the Google Calendar API. I get Error 404 Not Found. Here is my code:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/auth2/token"
Dim getTokenBody As String
getTokenBody = "code=" & code & _
"&redirect_uri=urn:ietf:wg:oauth:2.0:oob" & _
"&client_id=xxxxxxx-xxxxxxxx.apps.googleusercontent.com" & _
"&client_secret={myLittleSecret}" & _
"&grant_type=authorization_code"
Dim Http As MSXML2.XMLHTTP60
Set Http = CreateObject("MSXML2.XMLHTTP.6.0")
With Http
.Open "POST", getTokenUrl, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send(getTokenBody)
End With
Do While Http.ReadyState <> 4
Loop
Debug.Print Http.responseText
I have also tried putting everything in the url parameter of the .Open method and nothing in the .Send method:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/oauth2/token&code=" & code & "&client_id=xxxxxx-xxxxxx.apps.googleusercontent.com&client_secret={myLittleSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code"
Dim Http As MSXML2.XMLHTTP60
Set Http = CreateObject("MSXML2.XMLHTTP.6.0")
With Http
.Open "POST", getTokenUrl, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send("")
End With
I have tried using WinHttp.WinHttpRequest instead of MSXML2.XMLHTTP.
I have tried using http://localhost instead of urn:ietf:wg:oauth:2.0:oob.
I have tried making http://localhost and urn:ietf:wg:oauth:2.0:oob url encoded.
All give Error 404 Not Found.
Can someone help point me in the right direction?

Finally figured it out--
The URL I was using was wrong--a one-letter type-o /forehead-slap/
instead of:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/auth2/token"
it should have been:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/oauth2/token"
note the oauth2 instead of just auth2
Geesh. Sometimes I just need more sleep.
Incidentally, I could only get it to work when I put only the base URL in the .Open request and the parameters in the .send() (rather than stringing them all together in to one URL and "POST"ing it).
Working like a charm now!

Related

Click on a href in VBA

I want to click on the following link
I have the class name and the line code I was trying ot use is the following:
objIE.document.getElementByClassName("msDataText searchLink").Click
This may well be a very basic question.. any guidance
Thanks a lot
Not sure if it is a duplicate question.
A good function GetHTTPResult is already available from the link. You need to just pass the url for the GET request to fetch the data. For POST request (this function will not work), you need to make a POST request with postdata.
Also there is a sample for XMLHttpRequest at link
Function GetHTTPResult(sURL As String) As String
Dim XMLHTTP As Variant, sResult As String
Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
XMLHTTP.Open "GET", sURL, False
XMLHTTP.Send
Debug.Print "Status: " & XMLHTTP.Status & " - " & XMLHTTP.StatusText
sResult = XMLHTTP.ResponseText
Debug.Print "Length of response: " & Len(sResult)
Set XMLHTTP = Nothing
GetHTTPResult = sResult
End Function

Error Unsupported Grant Type

I am trying to connect to an API, using MS Excel VBA. The parameters needed for login are grant type, username, and password.
I have came up with the code below, however i am getting the error :
{"error":"unsupported_grant_type"}
Can anyone enlighten me where i am doing it wrongly?
Sub test()
Dim objHttp As Object
Dim json As String
Dim user, password As String
user = "user1"
password = "password1"
json = "{""grant_type"":""password"",""username"":""" & user & """,""password"":""" & password & """}"
MsgBox json
Dim result As String
Set objHttp = CreateObject("MSXML2.XMLHTTP")
url = "http://dummywebsite.com"
objHttp.Open "POST", url, False
objHttp.SetRequestHeader "Content-type", "application/json"
objHttp.Send (json)
result = objHttp.ResponseText
MsgBox result
End Sub
The code is actually working, and it is due to user rights after testing with another user account.
Try:
Headers:
- Content-Type: application/x-www-form-urlencoded
- Accept-Charset: UTF-8
- Authorization: [Your Authorization Code]
Body:
username=[username]&password=[password]&grant_type=password

Sending values as parameters in HTTP GET using VBA request

So I am trying to send a basic request to a new API I'm testing out with the following script:
Sub CalcDemo()
TargetURL = "https://my-api-url.com"
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Open "GET", TargetURL, False
HTTPReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
postData = "user=myUsername&password=myPassword"
HTTPReq.send (postData)
MsgBox (HTTPReq.responseText)
End Sub
But I'm getting the following error message: HTTP Status 401 - user and password should be specified as parameters on the request. I was under the impression that the manner in which postData is being passed above meant they are sent as parameters, but I guess I am wrong. How can I send a string of parameters?
It seems to me that the value of postData is not collecting the values of the variables myUsername or myPassword. you have to create the concatenated data like so:
postData = "user=" & myUsername & "&password=" & myPassword
I suppose that myUsername and myPassword are global variables. Otherwise you also need to pass them as arguments to your function.
Hope this helps!
As one comment has suggested, you are trying to send a post string usin a GET command. If you replace the folowing line, it should work:
HTTPReq.Open "GET", TargetURL, False
replaced by:
HTTPReq.Open "POST", TargetURL, False

VBA RESTful API GET Method issue

Hi I'm calling an API and using the winhttp request and the GET method. I'm passing a json style parameter in the send method but it just can't get accepted. I end up with the error message:
{"code":"INS03","description":"Event ID required","requestId":"_181603230829162847306080","data":{},"validationErrors":null}
Which seems weird because I am indeed passing the event id parameter, as follows:
inventory_URL = "https://api.stubhub.com/search/inventory/v1"
Dim oRequest As WinHttp.WinHttpRequest
Dim sResult As String
Set oRequest = New WinHttp.WinHttpRequest
With oRequest
.Open "GET", inventory_URL, True
.setRequestHeader "Authorization", "Bearer " & access_token
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Accept-Encoding", "application/json"
.send ("{""eventid"":""9445148""}")
.waitForResponse
sResult = .responseText
Debug.Print sResult
sResult = oRequest.Status
Debug.Print sResult
End With
Is there any issue with my code?
Thank you in advance,
Vadim
For GET request query string should be composed.
Your data can't be passed in Send but in query string:
.Open "GET", inventory_URL & "?eventid=9445148", True
Check GET vs POST.

VBA WinHttp request:parameter is incorrect (error 80070057)

I have this script to automatically fetch Google Analytics results, it has worked fine for over a year. All of the sudden it stopped working.
I'm getting error 80070057: parameter is incorrect
This is the code. And yes, I'm using a proxy.
The error happens at the first SetRequestHeader
Dim WinHttpReq As WinHttp.WinHttpRequest
' Create an instance of the WinHTTPRequest ActiveX object.
Set WinHttpReq = New WinHttpRequest
' Assemble an HTTP Request.
WinHttpReq.Open "GET", url, False
WinHttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "http://webproxy.vum.be:8080"
WinHttpReq.SetRequestHeader "Authorization", "GoogleLogin Auth=" & auth
WinHttpReq.SetRequestHeader "GData-Version", 2
' Send the HTTP Request.
WinHttpReq.Send
' Put status and content type into status text box.
strStatus = WinHttpReq.STATUS & " - " & WinHttpReq.StatusText
'Debug.Print "Status: " & strStatus
If Body = True Then
get_url_google = WinHttpReq.ResponseText
Else
get_url_google = strStatus
End If
It was Google's fault. The "auth" variable was misformed, during the authentication procedure google was asking for a captcha.