Search code examples
excelvbaxmlhttprequest

Sendpulse SMS using VBA


I am trying to use Sendpulse API in VBA.
It has a method to obtain authorization: https://sendpulse.com/integrations/api#libraries

Image of the Authorization API section
1

My VBA code:

Dim URL As String
Dim xmlHttp As Object
Dim data As String
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP")

URL = "https://api.sendpulse.com/oauth/access_token"
data = "grant_type=client_credentials , client_id=-redacted-, client_secret=-redacted--"
xmlHttp.Open "POST", URL, False                 'False means wait for response after send
xmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlHttp.send data
Debug.Print xmlHttp.ResponseText

I receive

': responseText : "{"error":"unsupported_grant_type","error_description":"The authorization grant type is not supported by the authorization server.","hint":"Check that all required parameters ha"*

Tech support verifies the input parameters work using "postman". I am rather sure it is a VBA syntax problem.

I tried combinations of quotes in the data=... above.
e.g.

data = "grant_type=""client_credentials"" , client_id=""xxxx"" , client_secret=""xxxx"""

I tried colons in place of =. Perhaps the header is wrong?
Without the header it is the same.


Solution

  • Carefully build your data string:

    ' Json skeleton.
    Const DataMask As String = "{""grant_type"":""{0}"",""client_id"":""{1}"",""client_secret"":""{2}""}"
    
    Dim Data       As String
    
    ' Json data fill.
    Data = DataMask
    Data = Replace(Data, "{0}", "client_credentials")
    Data = Replace(Data, "{1}", "237b4af9c99d0f89bdbd876dcd5a0000")
    Data = Replace(Data, "{2}", "a99e7d506d3701c5c04de3db1913eeee")
    
    ' Json check.
    Debug.Print Data
    

    Result:

    {"grant_type":"client_credentials","client_id":"237b4af9c99d0f89bdbd876dcd5a0000","client_secret":"a99e7d506d3701c5c04de3db1913eeee"}