Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

PureBasic Web API Examples

Primary Categories

ABN AMRO
AWS Secrets Manager
AWS Security Token Service
AWS Translate
Activix CRM
Adyen
Alibaba Cloud OSS
Amazon Cognito
Amazon DynamoDB
Amazon MWS
Amazon Pay
Amazon Rekognition
Amazon SP-API
Amazon Voice ID
Aruba Fatturazione
Azure Maps
Azure Monitor
Azure OAuth2
Azure Storage Accounts
Backblaze S3
Banco Inter
Belgian eHealth Platform
Bitfinex v2 REST
Bluzone
BrickLink
Bunny CDN
CallRail
CardConnect
Cerved
ClickBank
Clickatell
Cloudfare
Constant Contact
DocuSign
Duo Auth MFA
ETrade
Ecwid
Egypt ITIDA
Egypt eReceipt
Etsy
Facebook
Faire
Frame.io
GeoOp
GetHarvest
Global Payments
Google People
Google Search Console
Google Translate
Google Vision
Hungary NAV Invoicing
IBM Text to Speech
Ibanity
IntakeQ
Jira
Lightspeed
MYOB
Magento
Mailgun
Malaysia MyInvois
Mastercard

MedTunnel
MercadoLibre
MessageMedia
Microsoft Calendar
Microsoft Group
Microsoft Tasks and Plans
Microsoft Teams
Moody's
Okta OAuth/OIDC
OneLogin OIDC
OneNote
OpenAI ChatGPT
PRODA
PayPal
Paynow.pl
Peoplevox
Populi
QuickBooks
Rabobank
Refinitiv
Royal Mail OBA
SCiS Schools Catalogue
SII Chile
SMSAPI
SOAP finkok.com
Salesforce
SendGrid
Shippo
Shopify
Shopware
Shopware 6
SimpleTexting
Square
Stripe
SugarCRM
TicketBAI
TikTok Shop
Trello
Twilio
Twitter API v2
Twitter v1
UPS
UniPin
VoiceBase
Vonage
WaTrend
Walmart v3
Wasabi
WhatsApp
WiX
WooCommerce
WordPress
Xero
Yahoo Mail
Yapily
Yousign
ZATCA
Zendesk
Zoom
_Miscellaneous_
eBay
effectconnect
hacienda.go.cr

 

 

 

(PureBasic) Quickbooks OAuth1 Authorization (3-legged)

Demonstrates 3-legged OAuth1 authorization for Quickbooks.

Chilkat PureBasic Module Download

Chilkat PureBasic Module

IncludeFile "CkJsonObject.pb"
IncludeFile "CkHttp.pb"
IncludeFile "CkFileAccess.pb"
IncludeFile "CkSocket.pb"
IncludeFile "CkHashtable.pb"
IncludeFile "CkHttpRequest.pb"
IncludeFile "CkHttpResponse.pb"
IncludeFile "CkTask.pb"
IncludeFile "CkStringBuilder.pb"

Procedure ChilkatExample()

    consumerKey.s = "QUICKBOOKS_CONSUMER_KEY"
    consumerSecret.s = "QUICKBOOKS_CONSUMER_SECRET"

    requestTokenUrl.s = "https://oauth.intuit.com/oauth/v1/get_request_token"
    authorizeUrl.s = "https://appcenter.intuit.com/Connect/Begin"
    accessTokenUrl.s = "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..
    callbackUrl.s = "http://localhost:3017/"
    callbackLocalPort.i = 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
    http.i = CkHttp::ckCreate()
    If http.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success.i

    CkHttp::setCkOAuth1(http, 1)
    CkHttp::setCkOAuthConsumerKey(http, consumerKey)
    CkHttp::setCkOAuthConsumerSecret(http, consumerSecret)
    CkHttp::setCkOAuthCallback(http, callbackUrl)

    req.i = CkHttpRequest::ckCreate()
    If req.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    resp.i = CkHttp::ckPostUrlEncoded(http,requestTokenUrl,req)
    If CkHttp::ckLastMethodSuccess(http) <> 1
        Debug CkHttp::ckLastErrorText(http)
        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    If CkHttpResponse::ckStatusCode(resp) >= 400
        Debug "Error response status code = " + Str(CkHttpResponse::ckStatusCode(resp))
        Debug CkHttpResponse::ckBodyStr(resp)
        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    ; If successful, the resp.BodyStr contains this:  
    ; oauth_token=-Wa_KwAAAAAAxfEPAAABV8Qar4Q&oauth_token_secret=OfHY4tZBX2HK4f7yIw76WYdvnl99MVGB&oauth_callback_confirmed=true
    Debug CkHttpResponse::ckBodyStr(resp)

    hashTab1.i = CkHashtable::ckCreate()
    If hashTab1.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkHashtable::ckAddQueryParams(hashTab1,CkHttpResponse::ckBodyStr(resp))

    requestToken.s = CkHashtable::ckLookupStr(hashTab1,"oauth_token")
    requestTokenSecret.s = CkHashtable::ckLookupStr(hashTab1,"oauth_token_secret")
    CkHttp::setCkOAuthTokenSecret(http, requestTokenSecret)

    CkHttpResponse::ckDispose(resp)

    Debug "oauth_token = " + requestToken
    Debug "oauth_token_secret = " + requestTokenSecret

    ; ---------------------------------------------------------------------------
    ; 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.
    sbUrlForBrowser.i = CkStringBuilder::ckCreate()
    If sbUrlForBrowser.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sbUrlForBrowser,authorizeUrl)
    CkStringBuilder::ckAppend(sbUrlForBrowser,"?oauth_token=")
    CkStringBuilder::ckAppend(sbUrlForBrowser,requestToken)
    urlForBrowser.s = CkStringBuilder::ckGetAsString(sbUrlForBrowser)

    ; 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.
    listenSock.i = CkSocket::ckCreate()
    If listenSock.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    backLog.i = 5
    success = CkSocket::ckBindAndListen(listenSock,callbackLocalPort,backLog)
    If success <> 1
        Debug CkSocket::ckLastErrorText(listenSock)
        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        CkHashtable::ckDispose(hashTab1)
        CkStringBuilder::ckDispose(sbUrlForBrowser)
        CkSocket::ckDispose(listenSock)
        ProcedureReturn
    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.
    maxWaitMs.i = 60000
    task.i = CkSocket::ckAcceptNextConnectionAsync(listenSock,maxWaitMs)
    CkTask::ckRun(task)

    ;  At this point, your application should load the URL in a browser.
    ;  For example,
    ;  in C#:  System.Diagnostics.Process.Start(urlForBrowser);
    ;  in Java: Desktop.getDesktop().browse(new URI(urlForBrowser));
    ;  in VBScript: Set wsh=WScript.CreateObject("WScript.Shell")
    ;               wsh.Run urlForBrowser
    ; in Xojo: ShowURL(url)  (see http://docs.xojo.com/index.php/ShowURL)
    ; in Dataflex: Runprogram Background "c:\Program Files\Internet Explorer\iexplore.exe" sUrl        
    ;  The Quickbooks account owner would interactively accept or deny the authorization request.

    ;  Add the code to load the url in a web browser here...
    ;  Add the code to load the url in a web browser here...
    ;  Add the code to load the url in a web browser here...
    ; System.Diagnostics.Process.Start(urlForBrowser);

    ; Wait for the listenSock's task to complete.
    success = CkTask::ckWait(task,maxWaitMs)
    If Not success OR (CkTask::ckStatusInt(task) <> 7) OR (CkTask::ckTaskSuccess(task) <> 1)
        If Not success
            ; The task.LastErrorText applies to the Wait method call.
            Debug CkTask::ckLastErrorText(task)
        Else
            ; The ResultErrorText applies to the underlying task method call (i.e. the AcceptNextConnection)
            Debug CkTask::ckStatus(task)
            Debug CkTask::ckResultErrorText(task)
        EndIf

        CkTask::ckDispose(task)

        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        CkHashtable::ckDispose(hashTab1)
        CkStringBuilder::ckDispose(sbUrlForBrowser)
        CkSocket::ckDispose(listenSock)
        ProcedureReturn
    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.
    CkSocket::ckClose(listenSock,10)

    ; The first thing to do is to get the connected socket.
    sock.i = CkSocket::ckCreate()
    If sock.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkSocket::ckLoadTaskResult(sock,task)
    CkTask::ckDispose(task)

    ; Read the start line of the request..
    startLine.s = CkSocket::ckReceiveUntilMatch(sock,Chr(13) + Chr(10))
    If CkSocket::ckLastMethodSuccess(sock) <> 1
        Debug CkSocket::ckLastErrorText(sock)
        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        CkHashtable::ckDispose(hashTab1)
        CkStringBuilder::ckDispose(sbUrlForBrowser)
        CkSocket::ckDispose(listenSock)
        CkSocket::ckDispose(sock)
        ProcedureReturn
    EndIf

    ; Read the request header.
    requestHeader.s = CkSocket::ckReceiveUntilMatch(sock,Chr(13) + Chr(10) + Chr(13) + Chr(10))
    If CkSocket::ckLastMethodSuccess(sock) <> 1
        Debug CkSocket::ckLastErrorText(sock)
        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        CkHashtable::ckDispose(hashTab1)
        CkStringBuilder::ckDispose(sbUrlForBrowser)
        CkSocket::ckDispose(listenSock)
        CkSocket::ckDispose(sock)
        ProcedureReturn
    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.
    sbResponseHtml.i = CkStringBuilder::ckCreate()
    If sbResponseHtml.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sbResponseHtml,"<html><body><p>Chilkat thanks you!</b></body</html>")

    sbResponse.i = CkStringBuilder::ckCreate()
    If sbResponse.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sbResponse,"HTTP/1.1 200 OK" + Chr(13) + Chr(10))
    CkStringBuilder::ckAppend(sbResponse,"Content-Length: ")
    CkStringBuilder::ckAppendInt(sbResponse,CkStringBuilder::ckLength(sbResponseHtml))
    CkStringBuilder::ckAppend(sbResponse,Chr(13) + Chr(10))
    CkStringBuilder::ckAppend(sbResponse,"Content-Type: text/html" + Chr(13) + Chr(10))
    CkStringBuilder::ckAppend(sbResponse,Chr(13) + Chr(10))
    CkStringBuilder::ckAppendSb(sbResponse,sbResponseHtml)

    CkSocket::ckSendString(sock,CkStringBuilder::ckGetAsString(sbResponse))
    CkSocket::ckClose(sock,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
    sbStartLine.i = CkStringBuilder::ckCreate()
    If sbStartLine.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sbStartLine,startLine)
    numReplacements.i = CkStringBuilder::ckReplace(sbStartLine,"GET /?","")
    numReplacements = CkStringBuilder::ckReplace(sbStartLine," HTTP/1.1","")
    CkStringBuilder::ckTrim(sbStartLine)

    ; oauth_token=qyprdP04IrTDIXtP1HRZz0geQdjXHVlGDxXPexlXZsjZNRcY&oauth_verifier=arx5pj5&realmId=193514465596199&dataSource=QBO
    Debug "startline: " + CkStringBuilder::ckGetAsString(sbStartLine)

    CkHashtable::ckClear(hashTab1)
    CkHashtable::ckAddQueryParams(hashTab1,CkStringBuilder::ckGetAsString(sbStartLine))

    requestToken = CkHashtable::ckLookupStr(hashTab1,"oauth_token")
    authVerifier.s = CkHashtable::ckLookupStr(hashTab1,"oauth_verifier")

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

    CkHttp::setCkOAuthToken(http, requestToken)
    CkHttp::setCkOAuthVerifier(http, authVerifier)
    resp = CkHttp::ckPostUrlEncoded(http,accessTokenUrl,req)
    If CkHttp::ckLastMethodSuccess(http) <> 1
        Debug CkHttp::ckLastErrorText(http)
        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        CkHashtable::ckDispose(hashTab1)
        CkStringBuilder::ckDispose(sbUrlForBrowser)
        CkSocket::ckDispose(listenSock)
        CkSocket::ckDispose(sock)
        CkStringBuilder::ckDispose(sbResponseHtml)
        CkStringBuilder::ckDispose(sbResponse)
        CkStringBuilder::ckDispose(sbStartLine)
        ProcedureReturn
    EndIf

    ; Make sure a successful response was received.
    If CkHttpResponse::ckStatusCode(resp) <> 200
        Debug CkHttpResponse::ckStatusLine(resp)
        Debug CkHttpResponse::ckHeader(resp)
        Debug CkHttpResponse::ckBodyStr(resp)
        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        CkHashtable::ckDispose(hashTab1)
        CkStringBuilder::ckDispose(sbUrlForBrowser)
        CkSocket::ckDispose(listenSock)
        CkSocket::ckDispose(sock)
        CkStringBuilder::ckDispose(sbResponseHtml)
        CkStringBuilder::ckDispose(sbResponse)
        CkStringBuilder::ckDispose(sbStartLine)
        ProcedureReturn
    EndIf

    ; If successful, the resp.BodyStr contains something like this:
    ; oauth_token=12347455-ffffrrlaBdCjbdGfyjZabcdb5APNtuTPNabcdEpp&oauth_token_secret=RxxxxJ8mTzUhwES4xxxxuJyFWDN8ZfHmrabcddh88LmWE
    Debug CkHttpResponse::ckBodyStr(resp)

    hashTab2.i = CkHashtable::ckCreate()
    If hashTab2.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkHashtable::ckAddQueryParams(hashTab2,CkHttpResponse::ckBodyStr(resp))

    accessToken.s = CkHashtable::ckLookupStr(hashTab2,"oauth_token")
    accessTokenSecret.s = CkHashtable::ckLookupStr(hashTab2,"oauth_token_secret")

    CkHttpResponse::ckDispose(resp)

    ; The access token + secret is what should be saved and used for
    ; subsequent REST API calls.
    Debug "Access Token = " + accessToken
    Debug "Access Token Secret = " + accessTokenSecret

    ; Save this access token for future calls.
    json.i = CkJsonObject::ckCreate()
    If json.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::ckAppendString(json,"oauth_token",accessToken)
    CkJsonObject::ckAppendString(json,"oauth_token_secret",accessTokenSecret)

    ; Also save the realmId and dataSource from hashTab1.
    realmId.s = CkHashtable::ckLookupStr(hashTab1,"realmId")
    Debug "realmId = " + realmId
    dataSource.s = CkHashtable::ckLookupStr(hashTab1,"dataSource")
    Debug "dataSource = " + dataSource

    CkJsonObject::ckAppendString(json,"realmId",realmId)
    CkJsonObject::ckAppendString(json,"dataSource",dataSource)

    fac.i = CkFileAccess::ckCreate()
    If fac.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkFileAccess::ckWriteEntireTextFile(fac,"qa_data/tokens/quickbooks.json",CkJsonObject::ckEmit(json),"utf-8",0)

    Debug "Success."


    CkHttp::ckDispose(http)
    CkHttpRequest::ckDispose(req)
    CkHashtable::ckDispose(hashTab1)
    CkStringBuilder::ckDispose(sbUrlForBrowser)
    CkSocket::ckDispose(listenSock)
    CkSocket::ckDispose(sock)
    CkStringBuilder::ckDispose(sbResponseHtml)
    CkStringBuilder::ckDispose(sbResponse)
    CkStringBuilder::ckDispose(sbStartLine)
    CkHashtable::ckDispose(hashTab2)
    CkJsonObject::ckDispose(json)
    CkFileAccess::ckDispose(fac)


    ProcedureReturn
EndProcedure

 

© 2000-2024 Chilkat Software, Inc. All Rights Reserved.