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
Hungary NAV Invoicing
IBM Text to Speech
Ibanity
IntakeQ
Jira
Lightspeed
MYOB
Magento
Mailgun
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
SendGrid
Shippo
Shopify
Shopware
Shopware 6
SimpleTexting
Square
Stripe
SugarCRM
TicketBAI
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) Twitter OAuth1 Authorization (3-legged)

Demonstrates 3-legged OAuth1 authorization for Twitter.

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 = "TWITTER_CONSUMER_KEY"
    consumerSecret.s = "TWITTER_CONSUMER_SECRET"

    requestTokenUrl.s = "https://api.twitter.com/oauth/request_token"
    authorizeUrl.s = "https://api.twitter.com/oauth/authorize"
    accessTokenUrl.s = "https://api.twitter.com/oauth/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)

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

    CkHttpRequest::ckAddParam(req,"oauth_callback",callbackUrl)

    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)

    If CkHttpResponse::ckStatusCode(resp) <> 200
        Debug "Failed response status code: " + Str(CkHttpResponse::ckStatusCode(resp))
        CkHttpResponse::ckDispose(resp)

        CkHttp::ckDispose(http)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    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)
    url.s = CkStringBuilder::ckGetAsString(sbUrlForBrowser)

    ; At this point, your application should load the URL in a browser.
    ; For example, 
    ; in C#: System.Diagnostics.Process.Start(url);
    ; in Java: Desktop.getDesktop().browse(new URI(url));
    ; in VBScript: Set wsh=WScript.CreateObject("WScript.Shell")
    ;              wsh.Run url
    ; 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 Microsoft 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...

    ; When the url is loaded into a browser, the response from Twitter 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(url);
    ; in Java: Desktop.getDesktop().browse(new URI(url));
    ; in VBScript: Set wsh=WScript.CreateObject("WScript.Shell")
    ;              wsh.Run url
    ; 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 Twitter 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(url);

    ; 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 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=abcdRQAAZZAAxfBBAAABVabcd_k&oauth_verifier=9rdOq5abcdCe6cn8M3jabcdj3Eabcd
    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)

    ; We don't need the "Authorization: OAuth ..." header for this POST.
    CkHttp::setCkOAuth1(http, 0)
    CkHttpRequest::ckRemoveParam(req,"oauth_callback")
    CkHttpRequest::ckAddParam(req,"oauth_verifier",authVerifier)
    CkHttpRequest::ckAddParam(req,"oauth_token",requestToken)

    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&user_id=85612355&screen_name=chilkatsoft&x_auth_expires=0
    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")
    userId.s = CkHashtable::ckLookupStr(hashTab,"user_id")
    screenName.s = CkHashtable::ckLookupStr(hashTab,"screen_name")

    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 "user_id = " + userId
    Debug "screen_name  = " + screenName

    ; Save this access token for future calls.
    ; Just in case we need user_id and screen_name, 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,"user_id",userId)
    CkJsonObject::ckAppendString(json,"screen_name",screenName)

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

    CkFileAccess::ckWriteEntireTextFile(fac,"qa_data/tokens/twitter.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-2024 Chilkat Software, Inc. All Rights Reserved.