POST request error 403 Microsoft graph from Excel VBA - excel

I am trying to create folder on sharepoint site with Microsoft graph from Excel VBA, code working on some endpoints but on some it return response error 403. On App permission side, everything looks fine and all permissions are granted. Please look at code below:
Sub create_folder()
Dim http As New MSXML2.XMLHTTP60
Dim url As String
access_token = "tokentokentoken"
url = "https://graph.microsoft.com/v1.0/drives/{drive-id}/items/"
http.Open "POST", url, False
http.setRequestHeader "application", "x-www-form-urlencoded"
http.setRequestHeader "Content-Type", "application/json;odata=verbose"
http.setRequestHeader "Authorization", "Bearer " & access_token
http.send "{""name"": ""New Folder"", ""folder"": {}}"
If http.Status = 200 Then
MsgBox ("OK")
End If
Set XMLHTTP = Nothing
End Sub

Related

Calling an API from Excel Macro to POST data using WinHTTPRequest

I am trying to call an API for sending SMS from Excel Macro.
I tried sending using MSXML2.XMLHTTP it sends SMS successfully from my system, But in client's system it is giving error "An error occurred in the secure channel support".
Set httpObject = CreateObject("MSXML2.XMLHTTP")
sURL = "https://api.xxx.in/send/?apiKey=" & sAPIKey & "&sender=" & sSenderID & "&numbers=" & sMobileNo & "&message=" & sMsg
httpObject.Open "POST", sURL, False
httpObject.Send
sGetResult = httpObject.ResponseText
I tried second method like
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "https://api.xxx.in/send/?"
postData = "apikey=" & sAPIKey & "&message=" & sMsg & "&numbers=" & sMobileNo & "&sender=" & sSenderID
winHttpReq.Open "POST", myURL, False
winHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
winHttpReq.Send (postData)
SendSMS = winHttpReq.ResponseText
On line winHttpReq.SetRequestHeader it gives error "An error occured in the secure channel support" on my system. As per suggestions I enabled all TLS versions but still the same error. I am using Win 7 and excel 6.5.Somewhere i read to add the ciphers to the servers. I have no idea how to do that. I guess issue is somewhere else.
Can anyone pls help. I will prefer to use the 2nd method.
Thanks

Download .csv from an indirect Asana link

This code creates a download but not of the linked file as it is not direct. When I open the .csv file it downloads, it appears to be the data from the redirect, not the file linked to the redirect.
This is the code:
Sub Asana()
Dim myURL As String
myURL = "https://app.asana.com/-/csv?id=955497629707333"
Dim HttpReq As Object
Set HttpReq = CreateObject("Microsoft.XMLHTTP")
HttpReq.Open "GET", myURL, False, "username", "password"
HttpReq.send
myURL = HttpReq.responseBody
If HttpReq.Status = 200 Then
Set oStrm = CreateObject("ADODB.Stream")
oStrm.Open
oStrm.Type = 1
oStrm.Write HttpReq.responseBody
oStrm.SaveToFile ThisWorkbook.Path & "\" & "SER_Backlog_BRCC.csv", 2 ' 1 = no overwrite, 2 = overwrite
oStrm.Close
End If
End Sub
It should be a spreadsheet copy of the data on the page, but it comes out with data in a spreadsheet of the website and not the linked .csv file you would get, if done manually.
Should be this:
.
I guess, you have an authorization problem, as user/password is not supported by Asana.
You need a Personal Access Token, which has to be set in your request header.
Please replace this line
'Set HttpReq = CreateObject("Microsoft.XMLHTTP")
Set HttpReq = CreateObject("MSXML2.XMLHTTP")
and that line:
'HttpReq.Open "GET", myURL, False, "username", "password"
HttpReq.Open "GET", myURL, False
HttpReq.setRequestHeader "Authorization", "Bearer " & "your Asana token here"

VBA httpWebRequest with Credentials

I need to get some data from a cloud service.
This is my code so far:
Option Explicit
Sub Test()
Call GetHTTPResult("https://venice.unit4.com/WebConnect/api/ZZKlesserRob/2017/Balance/GetBalance?AccountNumber=604&BeginMonth=1&EndMonth=1", "username", "password")
End Sub
Function GetHTTPResult(sURL As String, Optional username As String, Optional password As String) As String
Dim XMLHTTP As Object, sResult As String
Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
username = "dummy"
password = "dummypass"
XMLHTTP.Open "GET", sURL, False
XMLHTTP.setRequestHeader "Authorization", "Basic" & Base64Encode("username" & ":" & "password")
XMLHTTP.Send
Debug.Print "Status: " & XMLHTTP.Status & " - " & XMLHTTP.StatusText
sResult = XMLHTTP.ResponseText
GetHTTPResult = sResult
Set XMLHTTP = Nothing
End Function
Without the credentials it gives me the "401 - Unauthorized" -response, which is good, I suppose.
However I do have the necessary credentials at my disposal but I can't seem to fix the problem posed by the Base64 encoding.
What should I do?
Thanks in advance!
From inspecting the docs I believe your are missing a space in your Authorization header:
var request = new XMLHttpRequest();
...
request.setRequestHeader("Accept","application/xml");
request.setRequestHeader("Authorization","Basic " + Base64.encode ("User:Password"));
So your should read:
XMLHTTP.setRequestHeader "Authorization", "Basic " & Base64Encode(username & ":" & password)
Also, you should add an Accept header to the request with application/xml or application/json to specify the format of the requested data.

Post Request to CoinFloor API in Excel VBA not working - Getting 415 Unsupported Media Type Error

I am trying to access CoinFloor BIST API through Excel VBA or Access VBA. I am able to make get requests (like ticker) successfully. But when I try a post request (like get balance) I get an error "415 Unsupported Media Type". I looked through many threads for this error and all are pointing to the content-type and accept headers, but I was not able to get it working.
The code is pasted below.
Function BalancePostRequest()
Dim auth, URL, data
Dim cred As Credentials
Dim Lib As New jsonlib
cred = getCredentials
auth = cred.userId & "/" & cred.API_Key & ":" & cred.passphrase
URL = "https://webapi.coinfloor.co.uk:8090/bist/XBT/GBP/balance/"
Dim xhr: Set xhr = CreateObject("MSXML2.XMLHTTP")
With xhr
.Open "POST", URL, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Authorization", "Basic " + Base64Encode(auth)
End With
xhr.send data
If xhr.Status <> 200 Then
Err.Raise vbObjectError + 1000, "Util.SendRequest", "Status code: " & xhr.Status & " " & xhr.statusText & ". Response was: " & xhr.responseText
End If
Set xhr = Nothing
End Function

Excel VBA dowload file using the InternetExplorer object

So I have a VBA code that is currently successfully logging into a website and further navigating to other pages of the website and scraping data that I need.
I now need to navigate to a page (no problem), fill a textbox with a query (no problem) and click on a 'download' button (no problem). This then prompts a popup to download a file (open/save/cancel). My requirement is to save this file without user interaction - the macro should save the file in a predetermined directory.
Any ideas on how to achieve this? I couldn't get SendKeys to work at all.
Set appIE = New InternetExplorerMedium
sURL2 = "http://somewebsite.com/query.asp?"
With appIE
.Navigate sURL2
.Visible = True
End With
Do While appIE.Busy Or appIE.ReadyState <> 4
DoEvents
Loop
'code to enter the query in textbox and click on download file button
appIE.Document.getElementsByTagName("textarea")(0).Value = Sheets("UserEntry").Range("L37")
appIE.Document.getElementsByName("btnSubmit")(203).Click
Application.SendKeys "%{s}"
Set appIE = Nothing
Edit: Even if I could get SendKeys to work, I need to 'save as' the file automatically, not just 'save' it in the Downloads folder.
Ok, got it working, thanks to the approach suggested by #BrownishMonster
I used WinHTTP.WinHTTPRequest.5.1
I also used Fiddler to investigate what the browser was sending in the POST requests and then made VBA do the same
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
'This is to POST the login info and login to the site
WHTTP.Open "POST", mainUrl, False
WHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WHTTP.send loginString
'This is to POST the download info and download the file
WHTTP.Open "POST", fileUrl_XLSResult, False
WHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WHTTP.send downloadString
FileData = WHTTP.responseBody
'This is to save the file in the location MyFilePath
If WHTTP.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WHTTP.responseBody
oStream.SaveToFile MyFilePath, 1
oStream.Close
End If

Resources