Minggu, 11 Desember 2016

Tutorial NodeMCU: Twitter Application-only authentication via REST API (ESP8266, WeMos, NodeMCU, Lua)

Tulisan ini membahas tentang application-only-authentication yang disediakan oleh Twitter untuk melakukan aksi seperti:
  • Pull user timelines;
  • Access friends and followers of any account;
  • Access lists resources;
  • Search in tweets;
  • Retrieve any user information;
Dengan application-only-authentication anda tidak dapat melakukan aksi seperti:
  • Post tweets or other resources;
  • Connect in Streaming endpoints;
  • Search for users;
  • Use any geo endpoint;
  • Access DMs or account credentials;
Untuk mencoba koding dibawah ini, anda perlu membuat aplikasi pada Twitter dengan mengunjungi https://apps.twitter.com/, dan kemudian klik pada Create New App

Gambar 1. Pembuatan aplikasi Twitter

Selanjutnya anda perlu melengkapi data yang dibutuhkan.

Gambar 2. Pengisian parameter aplikasi

Setelah aplikasi terbentuk, maka anda perlu membuat token consumer_key dan consumer_secret yang dapat diakses melalui Application Setting dengan klik pada manage key and access tokens.

Gambar 3. Application Settings

Selanjutnya catat consumer_key dan consumer_secret yang nantinya akan digunakan untuk mendapatkan access_token.

Gambar 4. Application Settings (token)

Selanjutnya anda dapat mengakses aplikasi Twitter dengan metode REST secara application-only-authentication sebagaimana dokumentasi pada https://dev.twitter.com/oauth/application-only
Adapun koding pada nodemcu LUA adalah sebagai berikut:

-- by Hendra Soewarno (0119067305) base on https://dev.twitter.com/oauth/application-only
-- documentation
api_base = "https://api.twitter.com"
consumer_key = "wFfeywcbxse5bM7EvTZ******"
consumer_secret = "udECdtpnnUoodCz*******RwLmmHRagMtjpsHuymppGD7VQDA"
access_token = nil

function requestAPIResource()
    if (access_token ~= nil) then
        local path = "/1.1/statuses/user_timeline.json?count=1&screen_name=lgladdy"
        local header =
            "Authorization: Bearer " .. access_token .. "\r\n" ..
            "Accept-Encoding: text/plain\r\n"

        print(header)   
          
        http.get(api_base .. path,
            header,
            function(code, data)
                if (code ~= 200) then
                    print("Failed : HTTP error code : " .. code)
                else
                    print("Succeed : " .. code, data)             
                end
            end)
     end
end

function requestBearerToken(callback)
    local path = "/oauth2/token"
    local bearer_token = consumer_key .. ":" .. consumer_secret
    local bearer_token64 = crypto.toBase64(bearer_token)

    local payload = "grant_type=client_credentials"

    local header =
        "Authorization: Basic " .. bearer_token64 .. "\r\n" ..
        "Content-Type: application/x-www-form-urlencoded;charset=UTF-8\r\n" ..
        "Accept-Encoding: text/plain\r\n"

    print(header)

    http.post(api_base .. path,
        header,
        payload,
        function(code, data)
            if (code ~= 200) then
                print("Failed : HTTP error code : " .. code)
            else
                print("Succeed : " .. code, data)
                local t = cjson.decode(data)
                if (t["token_type"] == "bearer") then
                    access_token = t["access_token"]
                    node.task.post(callback) -- Executing HTTP request followed by another HTTP request
                else
                    print(t["token_type"])
                end
            end
        end)
end

requestBearerToken(requestAPIResource)
Beberapa hal yang perlu menjadi perhatian untuk menjalankan koding diatas, adalah ada membutuhkan kustomisasi pada firmware NodeMCU dengan memasukan beberapa module berikut ini:

NodeMCU custom build by frightanic.com
    branch: master
    commit: 81ec3665cb5fe68eb8596612485cc206b65659c9
    SSL: true
    modules: cjson,crypto,dht,file,gpio,http,net,node,rtctime,sntp,tmr,uart,websocket,wifi
 build     built on: 2016-12-10 10:19
 powered by Lua 5.1.4 on SDK 1.5.4.1(39cb9a32)
Untuk menjalankan perintah HTTP request yang diikuti dengan perintah HTTP request selanjutnya, maka anda perlu menggunakan perintah node.task.post(callback), dimana callback adalah fungsi HTTP request lanjutan yang diperlukan.

Hasil eksekusi:

> dofile("app.lua");
Authorization: Basic d0ZmZXl3Y2J4c2U1Yk03RXZUWkhsa3FIZDp1ZEVDZHRwbm5Vb29kQ3p5dmMzTEFId1J3TG1tSFJhZ010anBzSHV5bXBwR0Q3VlFEQQ==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Accept-Encoding: text/plain

> Succeed : 200    {"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAALZ***AAAAAAwk8%2FhVZPVptCvXdJJ11JMVAZNzs%3DSMOagw0LfgVtJzTSdF8a8iQjlPb5tkOW4MHGJ9EgCEiXfSwCOp"}
Authorization: Bearer AAAAAAAAAAAAAAAAAAAAALZ***AAAAAAwk8%2FhVZPVptCvXdJJ11JMVAZNzs%3DSMOagw0LfgVtJzTSdF8a8iQjlPb5tkOW4MHGJ9EgCEiXfSwCOp
Accept-Encoding: text/plain

Succeed : 200    [{"created_at":"Sun Dec 11 09:27:20 +0000 2016","id":807879432073580545,"id_str":"807879432073580545","text":"That\u2019s certainly an\u2026 impressive jacket, Diana Abbott. #Marr","truncated":false,"entities":{"hashtags":[{"text":"Marr","indices":[54,59]}],"symbols":[],"user_mentions":[],"urls":[]},"source":"\u003ca href=\"http:\/\/tapbots.com\/tweetbot\" rel=\"nofollow\"\u003eTweetbot for i\u039fS\u003c\/a\u003e","in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":5394402,"id_str":"5394402","name":"Liam Gladdy","screen_name":"lgladdy","location":"Bath, England","description":"I make parts of the internet. I play the video games too, and watch too much TV. I'm basically just a geek.","url":"https:\/\/t.co\/gRIFHbUGmf","entities":{"url":{"urls":[{"url":"https:\/\/t.co\/gRIFHbUGmf","expanded_url":"http:\/\/www.gladdy.co.uk","display_url":"gladdy.co.uk","indices":[0,23]}]},"description":{"urls":[]}},"protected":false,"followers_count":1569,"friends_count":322,"listed_count":85,"created_at":"Sun Apr 22 07:47:17 +0000 2007","favourites_count":50,"utc_offset":0,"time_zone":"London","geo_enabled":true,"verified":false,"statuses_count":91616,"lang":"en-gb","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"000000","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/662558757\/7rxa1rvaq99ve6wjm6ig.jpeg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/662558757\/7rxa1rvaq99ve6wjm6ig.jpeg","profile_background_tile":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/625205033672536064\/hVNRDCjs_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/625205033672536064\/hVNRDCjs_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/5394402\/1398195550","profile_link_color":"042242","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"E0EBFF","profile_text_color":"042242","profile_use_background_image":true,"has_extended_profile":false,"default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null,"translator_type":"none"},"geo":null,"coordinates":null,"place":{"id":"1db4f0a70fc5c9db","url":"https:\/\/api.twitter.com\/1.1\/geo\/id\/1db4f0a70fc5c9db.json","place_type":"city","name":"Bath","full_name":"Bath, England","country_code":"GB","country":"United Kingdom","contained_within":[],"bounding_box":{"type":"Polygon","coordinates":[[[-2.4113744,51.350545],[-2.322492,51.350545],[-2.322492,51.408754],[-2.4113744,51.408754]]]},"attributes":{}},"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"favorited":false,"retweeted":false,"lang":"en"}]

Tidak ada komentar:

Posting Komentar