2016年8月21日 星期日

Ruby on Rails Facebook graph api 使用 Koala

安裝

首先在FB developer 上註冊一個app

拿到app ID 跟 scecret key 之後

開啟Rails專案

在Gemfile 加上koala

bundle install 完

使用


使用graph api抓取社團的資料(僅限有管理權限的社團)


1.新增一個專案

rails new api_practice
cd api_practice

2.新增一個auth controller 

rails g controller auth

打開app/controller/auth_controller.rb

假設我們的app id 是 123 而 scecret key 是456 
我們讓callback回來的資料給auth的callback 處理

3. 新增index, callback 和 api_demo action


def index
    @oauth = Koala::Facebook::OAuth.new('123','456','http://localhost:3000/auth/callback' )
    @Login_url = @oauth.url_for_oauth_code(:permission => "user_managed_groups")
end

def callback
    @oauth = Koala::Facebook::OAuth.new('123','456','http://localhost:3000/auth/callback' )
    session[:token] = @oauth.get_access_token(params[:code])

    redirect_to :action => 'api_demo'
end

def api_demo
    if( session.has_key?(:token)
        @gapi = Koala::Facebook::API.new(session[:token])
        @groups = @gapi.get_connection('me','groups')
    end
end

4. 新增index和api_demo的html view

/app/view/auth/index.html.erb

<%= link_to "Facebook Login",@Login_url %>

/app/view/auth/api_demo.html.erb

<% groups.each do |group| %>
    <%= group['name'] %>
<% end %>
<%= link_to "Back to index", :controller => 'auth', :action => 'index' %>

5. 加上route

/config/routes.rb

加上

root :as => 'auth#index'
get 'auth/index' => 'auth#index'
get 'auth/callback' => 'auth#callback'
get 'auth/api_demo' => 'auth#api_demo'


6. 打開server

下指令
rails s

打開瀏覽器  瀏覽http://localhost:3000/
就可以囉~

沒有留言:

張貼留言

Go lang 學習筆記 - 17 Pointers

``` package main import "fmt" func zeroval(n int) {         n = 0 } func zeroptr(n *int) {         *n = 0 } func main() {         ...