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)
Related
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 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)
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
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.
I have successfully been able to create a Jira Issue, now want to to add an attachment using: api/2/issue/{issueIdOrKey}/attachments
My following VB code wont work, any suggestions please as this is new to me, thanks. The error I get is: HTTP Status 500 - Error parsing Content-Type
Sub JIRA_PostAttachment()
Dim pHtml As String
Dim oHttp As Object
Dim strResponse As String
pHtml = "https://jira.ae.sda.corp.test.com/rest/api/2/issue/IS-163/attachments"
sVar = """file="": ""C:\Users\c776469\FORM.msg"""
Set oHttp = CreateObject("Microsoft.XMLHTTP")
Call oHttp.Open("POST", pHtml, False)
'oHttp.SetRequestHeader "Content-Type", "application/json"
oHttp.SetRequestHeader "Content-Type", "multipart/form-data;Charset=UTF-8; boundary="
'oHttp.SetRequestHeader "Accept", "application/json"
oHttp.SetRequestHeader "X-Atlassian-Token", "no-check"
oHttp.SetRequestHeader "Authorization", "Basic Yzc4NjQ3OTpHaWxpdDIwMTY/"
Call oHttp.Send(sVar)
strResponse = oHttp.ResponseText
MsgBox strResponse
Set oHttp = Nothing
End Sub
Please look at this link:
https://answers.atlassian.com/questions/39127148/answers/39127815/comments/39130956
It has a VBA example that works (also a C# example)