LoginSignup
7
4

More than 5 years have passed since last update.

FacebookAPIをgo言語から呼ぶ

Posted at

この記事はWACUL Advent Calendar の22日目です。

はじめに

FacebookのAPIをgo言語から扱いたいと思います。
FacebookのAPIはOauthの認証をする必要があります。ユーザの認証を経て、トークンを取得し、そのトークンを使用してAPIを呼びます。

下準備

適当にFacebookアプリを登録し、アプリIDとapp secret を控えておきます。
そして、Reidirect URL に http://localhost:8080を登録しておきます。

test_―_Facebookログイン_-_開発者向けFacebook.png

APIを呼ぶ

以下の手順を実装します。

  1. 認証ページのURLを表示
  2. コールバックされたときのために:8080でサーバを起動
  3. ユーザはURLをコピーしてブラウザに貼り付け
  4. 認証するとlocalhost:8080にコールバック
  5. コールバックの実装では、パラメータで渡ってくるコードからトークンに変換し、トークンを使ってAPIを呼ぶ

ソースコードは以下です。

package main

import (
    "fmt"
    "log"
    "net/http"

    fb "github.com/huandu/facebook"
    "golang.org/x/oauth2"
    fbauth "golang.org/x/oauth2/facebook"
)

var conf *oauth2.Config

func main() {
    conf = &oauth2.Config{
        ClientID:     "11111111111111",
        ClientSecret: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
        Endpoint:     fbauth.Endpoint,
        RedirectURL:  "http://localhost:8080/",
    }
    //認証ページのURL
    url := conf.AuthCodeURL("")
    fmt.Println(url)
    fmt.Println("Please access the URL")
    //リダイレクトURLで指定したサーバを起動しておく
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    code := r.FormValue("code") //codeが返ってくるので取得
    //codeを使ってAccessTokenを取得する
    token, err := conf.Exchange(oauth2.NoContext, code)
    if err != nil {
        log.Fatal("exchange error", err.Error())
    }
    client := conf.Client(oauth2.NoContext, token)

    session := &fb.Session{
        Version:    "v2.8",
        HttpClient: client,
    }

    //APIを使って自身の情報を取得
    res, err := session.Get("/me?fields=id,name", nil)
    if err != nil {
        log.Fatal("api get error", err.Error())
    }
    fmt.Println(res["name"])  // your facebook name
}

以上で、facebook APIを呼ぶことができました。

7
4
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
7
4