LoginSignup
5
3

More than 5 years have passed since last update.

RailsでApp Access TokenとGraph API v2 を使ってシェア数を取得する

Posted at

Graph API v2 を使うのに User Access Token を使った情報をよく見かけるのですが、App Access Token を使った情報をあまり見かけないので実装してみました。

ページのシェア数は URLオブジェクト から取得できます。


APP_ID と APP_SECRET から App Access Token を得るのに fb_graph2 を、Graph APIを叩くのに koala を利用しました。

Gemfile
gem 'fb_graph2'
gem 'koala'

適当にクラスを作って

app/services/facebook.rb
class Facebook
  def initialize(app_id, app_secret)
    @app_id = app_id
    @app_secret = app_secret
    @access_token = nil
  end

  def access_token!
    @access_token ||= FbGraph2::Auth.new(@app_id, @app_secret).access_token!
    @access_token.to_s
  end

  def url(url)
    graph = Koala::Facebook::API.new(access_token!)
    graph.get_object('', { id: url }, api_version: 'v2.5')
  end
end

こんな感じに使う。

facebook = Facebook.new(ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'])
url = facebook.url('http://peraichi.com')
# => {
#    "og_object" => {
#                  "id" => "793236810740460",
#         "description" => "ペライチは専門知識不要で、誰でもカンタンに1枚のWebページを作れるサービスです。ブランディングや商品紹介を、チラシをつくるイメージで作成できます。ブラウザからの操作だけで1枚の売れる商品紹介ページをすぐに作れます。基本無料。もちろんコーディング不要です!",
#               "title" => "ペライチ",
#                "type" => "website",
#        "updated_time" => "2015-11-07T00:36:46+0000",
#                 "url" => "https://peraichi.com/"
#    },
#        "share" => {
#        "comment_count" => 0,
#          "share_count" => 3627
#    },
#           "id" => "http://peraichi.com"
#}
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3