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

Twitter OAuth1 Authorization (3-legged)

See more OAuth1 Examples

Demonstrates 3-legged OAuth1 authorization for Twitter.

This example is deprecated and no longer valid.

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 oHashTab
LOCAL cRequestToken
LOCAL cRequestTokenSecret
LOCAL oSbUrlForBrowser
LOCAL cUrl
LOCAL oOauth2
LOCAL oListenSock
LOCAL nBackLog
LOCAL oSock
LOCAL nMaxWaitMs
LOCAL oTask
LOCAL cStartLine
LOCAL cRequestHeader
LOCAL oSbResponseHtml
LOCAL oSbResponse
LOCAL oSbStartLine
LOCAL nNumReplacements
LOCAL cAuthVerifier
LOCAL cAccessToken
LOCAL cAccessTokenSecret
LOCAL cUserId
LOCAL cScreenName
LOCAL oJson
LOCAL oFac

nSuccess := 0

cConsumerKey := "TWITTER_CONSUMER_KEY"
cConsumerSecret := "TWITTER_CONSUMER_SECRET"

cRequestTokenUrl := "https://api.twitter.com/oauth/request_token"
cAuthorizeUrl := "https://api.twitter.com/oauth/authorize"
cAccessTokenUrl := "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..
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

oReq := CreateObject("Chilkat.HttpRequest")
oReq:AddParam("oauth_callback", cCallbackUrl)

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 successful, the resp.BodyStr contains something like this:  
//  oauth_token=-Wa_KwAAAAAAxfEPAAABV8Qar4Q&oauth_token_secret=OfHY4tZBX2HK4f7yIw76WYdvnl99MVGB&oauth_callback_confirmed=true
? oResp:BodyStr

IF (oResp:StatusCode != 200)
    ? "Failed response status code: " + Str(oResp:StatusCode)
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    RETURN
ENDIF

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

cRequestToken := oHashTab:LookupStr("oauth_token")
cRequestTokenSecret := oHashTab: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()

//  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()
    oHashTab:destroy()
    oSbUrlForBrowser:destroy()
    oOauth2:destroy()
    RETURN
ENDIF

//  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.
oListenSock := CreateObject("Chilkat.Socket")

nBackLog := 5
nSuccess := oListenSock:BindAndListen(nCallbackLocalPort, nBackLog)
IF (nSuccess == 0)
    ? oListenSock:LastErrorText
    oHttp:destroy()
    oReq:destroy()
    oResp:destroy()
    oHashTab:destroy()
    oSbUrlForBrowser:destroy()
    oOauth2: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()

//  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()
    oHashTab:destroy()
    oSbUrlForBrowser:destroy()
    oOauth2:destroy()
    oListenSock:destroy()
    oSock: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...
//  Stop 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()
    oHashTab:destroy()
    oSbUrlForBrowser:destroy()
    oOauth2:destroy()
    oListenSock:destroy()
    oSock: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()
    oHashTab:destroy()
    oSbUrlForBrowser:destroy()
    oOauth2:destroy()
    oListenSock:destroy()
    oSock: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=abcdRQAAZZAAxfBBAAABVabcd_k&oauth_verifier=9rdOq5abcdCe6cn8M3jabcdj3Eabcd
? "startline: " + oSbStartLine:GetAsString()

oHashTab:Clear()
oHashTab:AddQueryParams(oSbStartLine:GetAsString())

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

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

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

//  We don't need the "Authorization: OAuth ..." header for this POST.
oHttp:OAuth1 := 0
oReq:RemoveParam("oauth_callback")
oReq:AddParam("oauth_verifier", cAuthVerifier)
oReq:AddParam("oauth_token", cRequestToken)

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()
    oHashTab:destroy()
    oSbUrlForBrowser:destroy()
    oOauth2:destroy()
    oListenSock:destroy()
    oSock: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()
    oHashTab:destroy()
    oSbUrlForBrowser:destroy()
    oOauth2:destroy()
    oListenSock:destroy()
    oSock:destroy()
    oSbResponseHtml:destroy()
    oSbResponse:destroy()
    oSbStartLine:destroy()
    RETURN
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
? oResp:BodyStr

oHashTab:Clear()
oHashTab:AddQueryParams(oResp:BodyStr)

cAccessToken := oHashTab:LookupStr("oauth_token")
cAccessTokenSecret := oHashTab:LookupStr("oauth_token_secret")
cUserId := oHashTab:LookupStr("user_id")
cScreenName := oHashTab:LookupStr("screen_name")

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

//  Save this access token for future calls.
//  Just in case we need user_id and screen_name, save those also..
oJson := CreateObject("Chilkat.JsonObject")
oJson:AppendString("oauth_token", cAccessToken)
oJson:AppendString("oauth_token_secret", cAccessTokenSecret)
oJson:AppendString("user_id", cUserId)
oJson:AppendString("screen_name", cScreenName)

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

? "Success."

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