Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3/4TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

PureBasic Web API Examples

Primary Categories

AWS Translate
Activix CRM
Adyen
Amazon MWS
Azure Maps
Azure Monitor
Azure OAuth2
Azure Storage Accounts
Bluzone
CardConnect
ClickBank
Clickatell
Cloudfare
DocuSign
ETrade
Etsy
Facebook
GeoOp
GetHarvest
Jira
MYOB

Magento
Microsoft Calendar
Microsoft Group
Microsoft Tasks and Plans
Okta OAuth/OIDC
OneLogin OIDC
PayPal
Peoplevox
Populi
QuickBooks
SOAP finkok.com
Shippo
Shopify
Stripe
SugarCRM
Trello
Twitter
VoiceBase
Vonage
Walmart
Walmart v3
Xero
eBay
effectconnect

 

 

 

(PureBasic) Xero OAuth1 Authorization (3-legged)

Demonstrates 3-legged OAuth1 authorization for Xero

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 = "XERO_CONSUMER_KEY"
    consumerSecret.s = "XERO_CONSUMER_SECRET"

    requestTokenUrl.s = "https://api.xero.com/oauth/RequestToken"
    authorizeUrl.s = "https://api.xero.com/oauth/Authorize"
    accessTokenUrl.s = "https://api.xero.com/oauth/AccessToken"

    ; 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 successful, the resp.BodyStr contains something like this:  
    ; oauth_token=-Wa_KwAAAAAAxfEPAAABV8Qar4Q&oauth_token_secret=OfHY4tZBX2HK4f7yIw76WYdvnl99MVGB&oauth_callback_confirmed=true
    Debug CkHttpResponse::ckBodyStr(resp)

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

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

    requestToken.s = CkHashtable::ckLookupStr(hashTab,"oauth_token")
    requestTokenSecret.s = CkHashtable::ckLookupStr(hashTab,"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 Xero 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(hashTab)
        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 Xero 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(hashTab)
        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...
    ; Stop listening on port 3017.
    CkSocket::ckClose(listenSock,10)

    ; First 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(hashTab)
        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(hashTab)
        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 something like this:
    ;  GET /?oauth_token=abcdRQAAZZAAxfBBAAABVabcd_k&oauth_verifier=9rdOq5abcdCe6cn8M3jabcdj3Eabcd&org=mUkIZabcdKEababcd189t0 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=abcdRQAAZZAAxfBBAAABVabcd_k&oauth_verifier=9rdOq5abcdCe6cn8M3jabcdj3Eabcd&org=mUkIZabcdKEababcd189t0
    Debug "startline: " + CkStringBuilder::ckGetAsString(sbStartLine)

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

    requestToken = CkHashtable::ckLookupStr(hashTab,"oauth_token")
    authVerifier.s = CkHashtable::ckLookupStr(hashTab,"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(hashTab)
        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(hashTab)
        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=85123455-fF41296Bi3daM8eCo9Y5vZabcdxXpRv864plYPOjr&oauth_token_secret=afiYJOgabcdSfGae7BDvJVVTwys8fUGpra5guZxbmFBZo&oauth_expires_in=1800&xero_org_muid=abcdecNhPKabcdNjz189t0
    Debug CkHttpResponse::ckBodyStr(resp)

    CkHashtable::ckClear(hashTab)
    CkHashtable::ckAddQueryParams(hashTab,CkHttpResponse::ckBodyStr(resp))

    accessToken.s = CkHashtable::ckLookupStr(hashTab,"oauth_token")
    accessTokenSecret.s = CkHashtable::ckLookupStr(hashTab,"oauth_token_secret")
    orgMuid.s = CkHashtable::ckLookupStr(hashTab,"xero_org_muid")
    expiresIn.s = CkHashtable::ckLookupStr(hashTab,"oauth_expires_in")

    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
    Debug "xero_org_muid = " + orgMuid
    Debug "oauth_expires_in  = " + expiresIn

    ; Save this access token for future calls.
    ; Just in case we need xero_org_muid and oauth_expires_in, save those also..
    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)
    CkJsonObject::ckAppendString(json,"xero_org_muid",orgMuid)
    CkJsonObject::ckAppendString(json,"oauth_expires_in",expiresIn)

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

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

    Debug "Success."


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


    ProcedureReturn
EndProcedure

 

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