Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v11.0.0+

Quickbooks OAuth1 Authorization (3-legged)

See more QuickBooks Examples

Demonstrates 3-legged OAuth1 authorization for Quickbooks.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL cConsumerKey
LOCAL cConsumerSecret
LOCAL cRequestTokenUrl
LOCAL cAuthorizeUrl
LOCAL cAccessTokenUrl
LOCAL cCallbackUrl
LOCAL nCallbackLocalPort
LOCAL oHttp
LOCAL oReq
LOCAL oResp
LOCAL oHashTab1
LOCAL cRequestToken
LOCAL cRequestTokenSecret
LOCAL oSbUrlForBrowser
LOCAL cUrl
LOCAL oListenSock
LOCAL nBackLog
LOCAL oSock
LOCAL nMaxWaitMs
LOCAL oTask
LOCAL oOauth2
LOCAL cStartLine
LOCAL cRequestHeader
LOCAL oSbResponseHtml
LOCAL oSbResponse
LOCAL oSbStartLine
LOCAL nNumReplacements
LOCAL cAuthVerifier
LOCAL oHashTab2
LOCAL cAccessToken
LOCAL cAccessTokenSecret
LOCAL oJson
LOCAL cRealmId
LOCAL cDataSource
LOCAL oFac

nSuccess := 0

cConsumerKey := "QUICKBOOKS_CONSUMER_KEY"
cConsumerSecret := "QUICKBOOKS_CONSUMER_SECRET"

cRequestTokenUrl := "https://oauth.intuit.com/oauth/v1/get_request_token"
cAuthorizeUrl := "https://appcenter.intuit.com/Connect/Begin"
cAccessTokenUrl := "https://oauth.intuit.com/oauth/v1/get_access_token"

//  The port number is picked at random. It's some unused port that won't likely conflict with anything else..
cCallbackUrl := "http://localhost:3017/"
nCallbackLocalPort := 3017

//  The 1st step in 3-legged OAuth1.0a is to send a POST to the request token URL to obtain an OAuth Request Token
oHttp := CreateObject("Chilkat.Http")

oHttp:OAuth1 := 1
oHttp:OAuthConsumerKey := cConsumerKey
oHttp:OAuthConsumerSecret := cConsumerSecret
oHttp:OAuthCallback := cCallbackUrl

oReq := CreateObject("Chilkat.HttpRequest")
oReq:HttpVerb := "POST"
oReq:ContentType := "application/x-www-form-urlencoded"

oResp := CreateObject("Chilkat.HttpResponse")
nSuccess := oHttp:HttpReq(cRequestTokenUrl, oReq, oResp)
IF (nSuccess == 0)
    ? oHttp:LastErrorText
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    RETURN
ENDIF

IF (oResp:StatusCode >= 400)
    ? "Error response status code = " + Str(oResp:StatusCode)
    ? oResp:BodyStr
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    RETURN
ENDIF

//  If successful, the resp.BodyStr contains this:  
//  oauth_token=-Wa_KwAAAAAAxfEPAAABV8Qar4Q&oauth_token_secret=OfHY4tZBX2HK4f7yIw76WYdvnl99MVGB&oauth_callback_confirmed=true
? oResp:BodyStr

oHashTab1 := CreateObject("Chilkat.Hashtable")
oHashTab1:AddQueryParams(oResp:BodyStr)

cRequestToken := oHashTab1:LookupStr("oauth_token")
cRequestTokenSecret := oHashTab1:LookupStr("oauth_token_secret")
oHttp:OAuthTokenSecret := cRequestTokenSecret

? "oauth_token = " + cRequestToken
? "oauth_token_secret = " + cRequestTokenSecret

//  ---------------------------------------------------------------------------
//  The next step is to form a URL to send to the AuthorizeUrl
//  This is an HTTP GET that we load into a popup browser.
oSbUrlForBrowser := CreateObject("Chilkat.StringBuilder")
oSbUrlForBrowser:Append(cAuthorizeUrl)
oSbUrlForBrowser:Append("?oauth_token=")
oSbUrlForBrowser:Append(cRequestToken)
cUrl := oSbUrlForBrowser:GetAsString()

//  When the urlForBrowser is loaded into a browser, the response from Quickbooks will redirect back to localhost:3017
//  We'll need to start a socket that is listening on port 3017 for the callback from the browser.
oListenSock := CreateObject("Chilkat.Socket")

nBackLog := 5
nSuccess := oListenSock:BindAndListen(nCallbackLocalPort, nBackLog)
IF (nSuccess == 0)
    ? oListenSock:LastErrorText
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab1:destroy()
    oSbUrlForBrowser:destroy()
    oListenSock:destroy()
    RETURN
ENDIF

//  Wait for the browser's connection in a background thread.
//  (We'll send load the URL into the browser following this..)
//  Wait a max of 60 seconds before giving up.
oSock := CreateObject("Chilkat.Socket")
nMaxWaitMs := 60000
oTask := oListenSock:AcceptNextAsync(nMaxWaitMs, oSock)
oTask:Run()

//  Launch the system's default browser navigated to the URL.
oOauth2 := CreateObject("Chilkat.OAuth2")
nSuccess := oOauth2:LaunchBrowser(cUrl)
IF (nSuccess == 0)
    ? oOauth2:LastErrorText
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab1:destroy()
    oSbUrlForBrowser:destroy()
    oListenSock:destroy()
    oSock:destroy()
    oOauth2:destroy()
    RETURN
ENDIF

//  Wait for the listenSock's task to complete.
nSuccess := oTask:Wait(nMaxWaitMs)
IF (.NOT. nSuccess .OR. (oTask:StatusInt != 7) .OR. (oTask:TaskSuccess != 1))
    IF (.NOT. nSuccess)
        //  The task.LastErrorText applies to the Wait method call.
        ? oTask:LastErrorText
    ELSE
        //  The ResultErrorText applies to the underlying task method call (i.e. the AcceptNextConnection)
        ? oTask:Status
        ? oTask:ResultErrorText
    ENDIF

    oTask:destroy()
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab1:destroy()
    oSbUrlForBrowser:destroy()
    oListenSock:destroy()
    oSock:destroy()
    oOauth2:destroy()
    RETURN
ENDIF

//  If we get to this point, the connection from the browser arrived and was accepted.

//  We no longer need the listen socket...
//  Close it so that it's no longer listening on port 3017.
oListenSock:Close(10)

oTask:destroy()

//  Read the start line of the request..
cStartLine := oSock:ReceiveUntilMatch(Chr(13) + Chr(10))
IF (oSock:LastMethodSuccess == 0)
    ? oSock:LastErrorText
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab1:destroy()
    oSbUrlForBrowser:destroy()
    oListenSock:destroy()
    oSock:destroy()
    oOauth2:destroy()
    RETURN
ENDIF

//  Read the request header.
cRequestHeader := oSock:ReceiveUntilMatch(Chr(13) + Chr(10) + Chr(13) + Chr(10))
IF (oSock:LastMethodSuccess == 0)
    ? oSock:LastErrorText
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab1:destroy()
    oSbUrlForBrowser:destroy()
    oListenSock:destroy()
    oSock:destroy()
    oOauth2:destroy()
    RETURN
ENDIF

//  The browser SHOULD be sending us a GET request, and therefore there is no body to the request.
//  Once the request header is received, we have all of it.
//  We can now send our HTTP response.
oSbResponseHtml := CreateObject("Chilkat.StringBuilder")
oSbResponseHtml:Append("<html><body><p>Chilkat thanks you!</b></body</html>")

oSbResponse := CreateObject("Chilkat.StringBuilder")
oSbResponse:Append("HTTP/1.1 200 OK" + Chr(13) + Chr(10))
oSbResponse:Append("Content-Length: ")
oSbResponse:AppendInt(oSbResponseHtml:Length)
oSbResponse:Append(Chr(13) + Chr(10))
oSbResponse:Append("Content-Type: text/html" + Chr(13) + Chr(10))
oSbResponse:Append(Chr(13) + Chr(10))
oSbResponse:AppendSb(oSbResponseHtml)

oSock:SendString(oSbResponse:GetAsString())
oSock:Close(50)

//  The information we need is in the startLine.
//  For example, the startLine will look like this:
//   GET /?oauth_token=abcdRQAAZZAAxfBBAAABVabcd_k&oauth_verifier=9rdOq5abcdCe6cn8M3jabcdj3Eabcd HTTP/1.1
oSbStartLine := CreateObject("Chilkat.StringBuilder")
oSbStartLine:Append(cStartLine)
nNumReplacements := oSbStartLine:Replace("GET /?", "")
nNumReplacements := oSbStartLine:Replace(" HTTP/1.1", "")
oSbStartLine:Trim()

//  oauth_token=qyprdP04IrTDIXtP1HRZz0geQdjXHVlGDxXPexlXZsjZNRcY&oauth_verifier=arx5pj5&realmId=193514465596199&dataSource=QBO
? "startline: " + oSbStartLine:GetAsString()

oHashTab1:Clear()
oHashTab1:AddQueryParams(oSbStartLine:GetAsString())

cRequestToken := oHashTab1:LookupStr("oauth_token")
cAuthVerifier := oHashTab1:LookupStr("oauth_verifier")

//  ------------------------------------------------------------------------------
//  Finally , we must exchange the OAuth Request Token for an OAuth Access Token.

oHttp:OAuthToken := cRequestToken
oHttp:OAuthVerifier := cAuthVerifier

oReq:HttpVerb := "POST"
oReq:ContentType := "application/x-www-form-urlencoded"

nSuccess := oHttp:HttpReq(cAccessTokenUrl, oReq, oResp)
IF (nSuccess == 0)
    ? oHttp:LastErrorText
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab1:destroy()
    oSbUrlForBrowser:destroy()
    oListenSock:destroy()
    oSock:destroy()
    oOauth2:destroy()
    oSbResponseHtml:destroy()
    oSbResponse:destroy()
    oSbStartLine:destroy()
    RETURN
ENDIF

//  Make sure a successful response was received.
IF (oResp:StatusCode != 200)
    ? oResp:StatusLine
    ? oResp:Header
    ? oResp:BodyStr
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab1:destroy()
    oSbUrlForBrowser:destroy()
    oListenSock:destroy()
    oSock:destroy()
    oOauth2:destroy()
    oSbResponseHtml:destroy()
    oSbResponse:destroy()
    oSbStartLine:destroy()
    RETURN
ENDIF

//  If successful, the resp.BodyStr contains something like this:
//  oauth_token=12347455-ffffrrlaBdCjbdGfyjZabcdb5APNtuTPNabcdEpp&oauth_token_secret=RxxxxJ8mTzUhwES4xxxxuJyFWDN8ZfHmrabcddh88LmWE
? oResp:BodyStr

oHashTab2 := CreateObject("Chilkat.Hashtable")
oHashTab2:AddQueryParams(oResp:BodyStr)

cAccessToken := oHashTab2:LookupStr("oauth_token")
cAccessTokenSecret := oHashTab2:LookupStr("oauth_token_secret")

//  The access token + secret is what should be saved and used for
//  subsequent REST API calls.
? "Access Token = " + cAccessToken
? "Access Token Secret = " + cAccessTokenSecret

//  Save this access token for future calls.
oJson := CreateObject("Chilkat.JsonObject")
oJson:AppendString("oauth_token", cAccessToken)
oJson:AppendString("oauth_token_secret", cAccessTokenSecret)

//  Also save the realmId and dataSource from hashTab1.
cRealmId := oHashTab1:LookupStr("realmId")
? "realmId = " + cRealmId
cDataSource := oHashTab1:LookupStr("dataSource")
? "dataSource = " + cDataSource

oJson:AppendString("realmId", cRealmId)
oJson:AppendString("dataSource", cDataSource)

oFac := CreateObject("Chilkat.FileAccess")
oFac:WriteEntireTextFile("qa_data/tokens/quickbooks.json", oJson:Emit(), "utf-8", 0)

? "Success."

oHttp:destroy()
oReq:destroy()
oResp:destroy()
oHashTab1:destroy()
oSbUrlForBrowser:destroy()
oListenSock:destroy()
oSock:destroy()
oOauth2:destroy()
oSbResponseHtml:destroy()
oSbResponse:destroy()
oSbStartLine:destroy()
oHashTab2:destroy()
oJson:destroy()
oFac:destroy()