Add images via Shopware 6 API / VBA by URL - vba

I try to use the Shopware 6 API to migrate things to a new shop from an existing Access Database using VBA with WinHttp.WinHttpRequest.5.1. Everything works fine except the media transfer.
My approach:
Create a media object in shopware in the right mediafolder
POST /api/v3/media
payload: "{""mediaFolderId"":""" & folderID & """,""id"":""ec90cae2cc84c37b6b7a0cb9fe5c4548""}"
works fine!
Upload the new image (testfile.png) via url
POST /api/v3/_action/media/ec90cae2cc84c37b6b7a0cb9fe5c4548/upload?extension=png&fileName=testfile
payload: "{""url"":"" & MediaUrl & "." & MediaUrlExt & ""}"
response 204 (no error),
A media file is created, but the content of the file is not the PNG image but the payload string.
the VBA code:
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
AuthURL = url & "/api/v2/_action/media/" & newMediaID & "/upload?extension=" & FileExtFromUrl(MediaUrl) & "&fileName=" & FileNameFromUrl(MediaUrl) & "&_response=true"
objHTTP.Open "POST", AuthURL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/json"
objHTTP.setRequestHeader "Accept", "application/json"
objHTTP.setRequestHeader "Authorization", "Bearer " & Token
Debug.Print AuthURL
payload = "{""url"":""https://" & FTPUrl & ftpKategorieOrdner & "/" & MediaUrl & """}"
Debug.Print payload
objHTTP.send (payload)
strResult = objHTTP.responseText
Debug.Print strResult
Debug.Print "uploadMedia " & objHTTP.Status; " - " + objHTTP.StatusText
maybe creating the thumbnail is the problem? dev.log:
[2021-05-18 15:13:22] messenger.INFO: Sending message Shopware\Core\Content\Media\Message\GenerateThumbnailsMessage with Enqueue\MessengerAdapter\QueueInteropTransport {"message":"[object] (Shopware\\Core\\Content\\Media\\Message\\GenerateThumbnailsMessage: {})","class":"Shopware\\Core\\Content\\Media\\Message\\GenerateThumbnailsMessage","sender":"Enqueue\\MessengerAdapter\\QueueInteropTransport"} []
[2021-05-18 15:13:23] php.INFO: User Deprecated: The "Symfony\Component\Debug\DebugClassLoader" class is deprecated since Symfony 4.4, use "Symfony\Component\ErrorHandler\DebugClassLoader" instead. {"exception":"[object] (ErrorException(code: 0): User Deprecated: The \"Symfony\\Component\\Debug\\DebugClassLoader\" class is deprecated since Symfony 4.4, use \"Symfony\\Component\\ErrorHandler\\DebugClassLoader\" instead. at ./vendor/symfony/debug/DebugClassLoader.php:16)"} []
What's wrong?

This should work - the admin panel uses the same endpoint for uploading a image via URL and for uploading the binary data.
The only difference I can spot is the content type of the request.
Unfortunately you did not mention which content type you are setting and I believe that is the problem.
Only if the content type is application/json, the file is fetched from the URL.
Make sure in the 2nd request to set the header
Content-Type: application/json
EDIT As per x-post in https://forum.shopware.com/t/bilder-upload-ueber-api-url/87850/4 it was found that VBA sends
content-type: "application/json; Charset=UTF-8"
So a possible patch for the Shopware core is
124: if (strpos($contentType,'application/json') !== false))

Related

Runtime error while sending Rest request via VBA

I send Rest request to HTTP server via VBA script looking like this:
HTTP.Open "PUT", rUrl, True
HTTP.SetRequestHeader "Host", rHost
HTTP.SetRequestHeader "Authorization", "Bearer " + rToken
HTTP.SetRequestHeader "Content-Length", Len(rBody)
HTTP.send rBody
Everything works fine on Windows 10 (64bit), but I get a runtime error on Windows 7 (64bit) at the line HTTP.send rBody:
Do you know what could cause this error?

Twilio SMS API call not recognizing mediaurls

My goal is to send a text message in VBA with Twilio's API by using WinHttpRequest and a POST call.
I put together a custom call using the WinHttpRequest for a basic SMS message and that worked. I can send text messages just fine.
But then I tried adding the MediaURL to the data, and it ignored the URL (no image attached to SMS). I confirmed the URL was valid by testing it in the Visual Studio project and it was able to send just fine.
I went back and tried sending a test image on twilio's servers and it works. I copied the same image to a server and it won't work.
WORKS
HTTPReq.send ("Body=Hi Brent, Hello From Me!&From=+1XXXXXXXXXX&To=+1XXXXXXXXX&MediaUrl=https://demo.twilio.com/owl.png")
DOESN'T WORK
HTTPReq.send ("Body=Hi Brent, Hello From ME!&From=+1XXXXXXXXXX&To=+1XXXXXXXXXX&MediaURL=https://smarttanktester.com/wp-content/uploads/2018/10/owl.png")
(Phone numbers removed).
I tested with a few more images from their site and they work.
So it appears that URLs external to their server are being ignored. My guess is that I have something configured wrong from my end.
Here is my code.
TargetURL = "https://api.twilio.com/2010-04-01/Accounts/XXX/Messages"
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Open "POST", TargetURL, False
HTTPReq.setRequestHeader "Accept", "application/json"
temp = "Basic " & EncodeBase64
HTTPReq.setRequestHeader "Authorization", temp
HTTPReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
HTTPReq.send ("Body=Hi Brent, Hello From Me!&From=+1XXXXXXXXXX&To=+1XXXXXXXXXX&MediaURL=https://smarttanktester.com/wp-content/uploads/2018/10/owl.png")
Any help is greatly appreciated.

Passing arguments to Gdax API via VBA HTTP Post

I got a problem in vba while trying to interact with GDAX API.
I get this error: {"message":"Requires product_id"}
I cant pass my product_id in the orders "POST" in WinHttp.WinHttpRequest.5.1 Nothing seems to work:
I tried adding ?product_id=BTC-EUR after the URL as Methodoptions(this works for GET Statements)
i tried adding "product_id=BTC-EUR" after the send
I tried using JsonString = "{""size"": ""0.01"",""price"": ""0.100"",""side"": ""buy"",""product_id"": ""BTC-USD""}" this as postdata
Does anyone know, how to pass those arguments?
This is the code im working with, that works well for all other authenticated statements not passing parameters.
TradeApiSite = "https://api-public.sandbox.gdax.com"
SignMsg = NonceUnique & UCase(HTTPMethod) & "/" & Method & MethodOptions
APIsign = Base64Encode(ComputeHash_C("SHA256", SignMsg, Base64Decode(secretkey), "RAW"))
' Instantiate a WinHttpRequest object and open it
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
objHTTP.Open UCase(HTTPMethod), TradeApiSite & "/" & Method & MethodOptions, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.setRequestHeader "CB-ACCESS-KEY", apikey
objHTTP.setRequestHeader "CB-ACCESS-SIGN", APIsign
objHTTP.setRequestHeader "CB-ACCESS-TIMESTAMP", NonceUnique
objHTTP.setRequestHeader "CB-ACCESS-PASSPHRASE", passphrase
objHTTP.Send '(postdata)
Figured it out after look a bit deeper at how danpaquin/gdax-python does authentication over here https://github.com/danpaquin/gdax-python/blob/master/gdax/gdax_auth.py
You want to send the JSON string as the post data like you described
Content-Type header should be set to application/json
The post data needs to appended to the pre-hash (in your case SignMsg)
Step 2 is important because with out it, GDAX doesn't seem to read your post data - so you get Requires product_id error. If you do step 2 without step 3, you will get invalid signature error

Request Tracker (RT) REST API HTTP POST

I'm trying to create a ticket in RT via the REST API. The wiki provides the guidance on how RT REST wiki
The instructions are:
Ticket Create Edit To create a new ticket: post on
/REST/1.0/ticket/new with a variable named "content",
containing "key: value" line by line, example:
Testing the new ticket section
id: ticket/new Queue: Requestor: Subject: Cc: <...> AdminCc: <...> Owner: <...>
Status: <...> Priority: <...> InitialPriority: <...> FinalPriority:
<...> TimeEstimated: <...> Starts: <...> Due: <...> Text: CF-: If there are any
"special" characters (Umlauts, dash, ...?) in a custom field's name,
you can still access it via its ID:
CF-$id: If you want to have a multiline Text, prefix every
line with a blank.
Due: <...> Text: This is a multiline Text !!!
CF-: The response should look
like:
RT/4.0.6 200 Ok
Ticket 775 created.
I'm using VBA and I can create a ticket in the right queue with my code, but it doesnt accept any of the other fields I include in the request.
Public Sub TestRT()
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "https://[RT IP]/REST/1.0/ticket/new?user=root&pass=password"
objHTTP.Open "POST", URL, False
objHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.SetRequestHeader "Content-type", "application/x-www-form-urlencoded"
RTContent = "Queue: Incidents&"
objHTTP.Send ("content=" & RTContent)
MsgBox objHTTP.ResponseText
End Sub
This works, with the & on the end of incidents.I've tried a lot of variations of the RTContent variable but just can't seem to get it to work. If I try RTContent = "Queue: Incidents&Subject: Test" The ticket gets created but with no subject.
I've looked on google, and although some people have asked the question around using VBA, the responses I've found point to just using another language. Unfortunately I need to get this working via VBA if possible.
Thanks
RTContent = "Queue: Incidents" & vbLf & "Subject: New item2"
It was the linefeed that was missing. Now added, works fine.

default credentials in VBA

I'm tryng to make a HTTP request from VB for Applications ( VBA)
that should have been simple:
URL = "https://www.google.com/"
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xhr.Open "GET", URL, False
xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xhr.Send
MsgBox xhr.responseText
BUT I'm behind a proxy server which require basic auth (base64).
How to set the credentials in VBA ?
(something equivalent to : myHttpWebRequest.Credentials = CredentialCache.DefaultCredentials)
If this is not possible, how to solve the issue with another approach ?
Thanks !
You'd need the setProxyCredentials method. I don't have a proxy to test, but this should do the trick:
URL = "https://www.google.com/"
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xhr.Open "GET", URL, False
xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xhr.setProxy 2, "192.168.0.222:8080"
xhr.setProxyCredentials "your_username" , "password_for_username"
xhr.Send
MsgBox xhr.responseText
Taken from This Question which points out the 2 argument is a version number that you may need to change.