I have the following curl code which I am trying to convert to VBA for excel
Endpoint : http://api.datadoctorit.com/email-validate
Request Type : POST
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen( $data ),
'X-Auth-Token: XXXXXXX'
) );
Here is the code that I came up with:
Dim strURL As String
Dim hReq As WinHttpRequest: Set hReq = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim strResp As String
Dim Token As String
Token = mytoken
strURL = "http://api.datadoctorit.com/email-validate"
hReq.Open "POST", strURL, False
hReq.SetRequestHeader "Content-Type", "application/json"
hReq.Send "X-Auth-Token" & ":" & token
strResp = hReq.ResponseText
MsgBox strResp
I keep getting this error:
"
{""error"":""You need to sign in or sign up before continuing.""}"
Adding authentication can be done with your Base 64 authorization (generated from the username and password of your basic authorization API call)
Just add the following:
hReq.setRequestHeader "Authorization", "Basic " & authCode
eg.
hReq.SetRequestHeader "Content-Type", "application/json"
hReq.setRequestHeader "Authorization", "Basic cHBzX2NyZWdJIYXAhjhjdjsfhjdshakjfdhakfhjk5c0AjMTZAY3JlZ"
(a real Auth code is about 50 characters long)
Related
I'm trying to login to a website using VBA Excel, but I'm having trouble to send payload post method like in python request.
Example in python
def login():
s = requests.Session()
payload = {
'username':sett.username,
'password':sett.password1
}
res = s.post(link, json=payload)
ref_t = json.loads(res.content)['content']['refresh_token']
t = json.loads(res.content)['content']['token']
return t
this is what I've tried but fail:
Dim request As New WinHttpRequest
request.Open "POST", auth_url, False
auth = "username=" & user & "," & "password=" & pass
request.SetRequestHeader "content-type", "application/json;charset=UTF-8"
request.SetCredentials "username:" & user, "password:" & pass, 0
request.Send auth
If request.Status <> 200 Then
MsgBox request.ResponseText
Exit Sub
End If
the response text shows "Username is required, but was not received", "Password is required, but was not received", "code":400.
Edit:
Dim auth As New Dictionary
auth.Add "username", user
auth.Add "password", pass
request.Open "POST", auth_url, False
request.SetRequestHeader "content-type", "application/json"
request.Send JsonConverter.ConvertToJson(auth)
Turns out that I need to use SetRequestHeader
Edit:
Dim auth As New Dictionary
auth.Add "username", user
auth.Add "password", pass
request.Open "POST", auth_url, False
request.SetRequestHeader "content-type", "application/json"
request.Send JsonConverter.ConvertToJson(auth)
I'm trying to receive an access token from the api of a partner via Oauth2.0.
When I use CURL I get the token but not in my VBA-script.
I get this error:
{"error":"invalid_request","error_description":"Missing grant type"}
The succesful CURL way is this:
curl -X POST -H "client_id:xxx" -u xxx:xxx"https://my.arrow.com/api/security/oauth/token" -d "grant_type=client_credentials"
I tried to send grant_type=client_credentials in different positions and spellings (in Body, as SetRequestHeader, grant_type=client_credentials or grant_type:client_credentials or grant_type, client_credentials) nothing helped, always same error.
This is the documentation for the API: https://my.arrow.com/more/developers/#section/Access-Token
Public Function API_MyArrow_Artikel(artikelBez) As String
Dim objHTTP As Object
Dim strHead As String, strClientId As String, strClientSecret As String, strBody As String
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
strClientId = "xxx"
strClientSecret = "xxx"
strUrl1 = "https://my.arrow.com/api/security/oauth/token"
strHead = strClientId & ":" & strClientSecret
lngADRNR = 674
objHTTP.Open "POST", strUrl1, False
objHTTP.SetRequestHeader "application", "x-www-form-urlencoded"
objHTTP.SetRequestHeader "client_id", strClientId
objHTTP.SetRequestHeader "client_secret", strClientSecret
objHTTP.SetRequestHeader "Authorization", "Basic " + Base64Encode(strHead)
'objHTTP.setRequestHeader "grant_type", "client_credentials"
objHTTP.SetTimeouts 10000, 10000, 10000, 10000 'Timeout (in milliseconds) to wait for timeout in each request phase (Resolve, Connect, Send, Receive)
objHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.Send "grant_type=client_credentials"
API_MyArrow_Artikel = objHTTP.responseText
End Function
The problem got solved. The correct way to use grant_type is as follows:
strUrl1 = "https://my.arrow.com/api/security/oauth/token?grant_type=client_credentials"
grant_type not in header or something else will work. Best is add to link.
I am trying to handle moodle data from our schools MS-Access database using VBA-code to post xml.objects.
I implemented the following code from an example for using the RESTful-API into my VBA-code (source https://moodle.org/plugins/webservice_restful):
json code:
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H 'Authorization: {token}' \
-d'{"options": {"ids":[6]}}' \
"https://localhost/webservice/restful/server.php/core_course_get_courses"
This is my conversion in VBA in a ms-access db module so far:
Option Compare Database
Option Explicit
Private Sub btnTestMoodleApi_Click()
Dim objRequest As Object
Dim strResult As String
Dim strPostData As String
Dim strToken as String
Dim strURL as String
strToken = xxx
strURL = xxx
Set objRequest = CreateObject("MSXML2.XMLHTTP")
strPostData = "'options[ids][0]=8'"
With objRequest
.Open "POST", strURL & "/webservice/restful/server.php/core_course_get_courses"
.setRequestHeader "Authorization", strToken
' .setRequestHeader Chr(34) & "Authorization" & Chr(34), Chr(34) & EncodeBase64(strToken) & Chr(34) ' is any of this necessary? I also tried single quotes chr(39)
.setRequestHeader "Content-Type", " application/x-www-form-urlencoded"
.setRequestHeader "Accept", "application/json"
.Send (strPostData)
While .ReadyState <> 4
DoEvents
Wend
strResult = .responseText
Debug.Print strResult
End With
End Sub
I am not sure if the following function that I found is necessary:
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As MSXML2.DOMDocument60
Dim objNode As MSXML2.IXMLDOMElement
Set objXML = New MSXML2.DOMDocument60
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.text
Set objNode = Nothing
Set objXML = Nothing
End Function
Either way the return is an error that there was no authorization header in the request {"exception":"moodle_exception","errorcode":"noauthheader","message":"No Authorization header found in request sent to Moodle"}. I guessed it is a formatting problem, so I tried various sorts of quotes around what I guess is the header type declaration ("Authorization") and the token, nothing worked. Also I found this remark by another person under the CURL source:
"The authorization header was stripped by my version of Apache 2, resulting in a noauthheader error. It worked when added this directive:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1"
However I would not know if that error source applies to my case and how I would implement the directive in my VBA code. Any help would be very much appreciated! By the way this is the corresponding php code in a locallib.php file where I believe the curl request to be directed to:
* Get the webservice authorization token from the request.
* Throws error and notifies caller on failure.
*
* #param array $headers The extracted HTTP headers.
* #return string $wstoken The extracted webservice authorization token.
*/
private function get_wstoken($headers) {
$wstoken = '';
if (isset($headers['HTTP_AUTHORIZATION'])) {
$wstoken = $headers['HTTP_AUTHORIZATION'];
} else {
// Raise an error if auth header not supplied.
$ex = new \moodle_exception('noauthheader', 'webservice_restful', '');
$this->send_error($ex, 401);
}
return $wstoken;
}
I have a bunch of API calls to STRIPE which are working well.
Generally I use the cURL version and work out what I need to do.
I have just come across the need to DELETE a subscription:
curl https://api.stripe.com/v1/subscriptions/sub_FpZkRarex4obNX \
-u sk_test_VHkTM0bOtpsE1dBnTxFbMBAk00WnBQnyI5: \
-X DELETE
The issue is I have no idea how to use the -x in VBA
My current code for other calls is:
api_Key = getStripeAPI
req = "DELETE"
Set httpReq = CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "POST", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
httpReq.setRequestHeader "Authorization", "Bearer " & api_Key
httpReq.send req
strResponse = httpReq.responseText
Debug.Print strResponse
writeToText strResponse
Set parsed = JsonConverter.ParseJson(strResponse)
I know the above code is incorrect but if someone can let me know how to utilise -X that would be great.
You're already using it, just passing the wrong argument. It's the first argument to .Open:
httpReq.Open "DELETE", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
ok wow i just figured it by myself.. after 45 mins of trying.
For those looking fr this:
-x DELETE means use DELETE as the "GET"/"POST" option.
working code:
api_Key = getStripeAPI
Set httpReq = CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "DELETE", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
httpReq.setRequestHeader "Authorization", "Bearer " & api_Key
httpReq.send
strResponse = httpReq.responseText
Debug.Print strResponse
writeToText strResponse
Set parsed = JsonConverter.ParseJson(strResponse)
I was using this method to login to betfair api. Everything works fine, but after Windows 10 update (KB3140741) not working anymore. ResponseText = {"loginStatus":"CERT_AUTH_REQUIRED"} Anyone solved this?
Windows 10 Build 10586.218, version 1511
Microsoft Office 2016
Dim oHTTP As Object: Set oHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim uri As String: uri = "https://identitysso.betfair.com/api/certlogin"
oHTTP.Open "POST", uri, False
oHTTP.SetClientCertificate "Common Name"
oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oHTTP.setRequestHeader "X-Application", App_key
oHTTP.setRequestHeader "Accept", "application/json"
oHTTP.send "username=" & UserName & "&password=" & Password & ""
I would try with Msxml2.ServerXMLHTTP.6.0 instead :
Const uri = "https://identitysso.betfair.com/api/certlogin"
Dim req As Object
Set req = CreateObject("Msxml2.ServerXMLHTTP.6.0")
req.Open "POST", uri, False
req.setOption 2, 13056 ' ignore all certificate errors '
req.setOption 3, "Common Name" ' set the client certificate from the local store '
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.setRequestHeader "X-Application", App_key
req.setRequestHeader "Accept", "application/json"
req.send "username=" & UserName & "&password=" & Password & ""