###### tags: `5xruby` `Astro Camp` `套件` `API` # 串連Facebook API --- ### (一)到[官方網站](https://developers.facebook.com/)建立自己的API 1、點選「我的應用程式」 ![我的應用程式](https://i.imgur.com/elH4Fqf.png) 2、點選「建立應用程式」 ![建立應用程式](https://i.imgur.com/cESc2Ra.png) 3、進到應用程式後,點選左方的基本設定,將相關資訊填寫齊全。 ![基本設定](https://i.imgur.com/3IMIYuj.png) 4、同上圖藍色方匡,可取得一組專屬你的應用程式的 (1)應用程式編號 = FACEBOOK_APP_ID (2)應用程式密鑰 = FACEBOOK_APP_SECRET ### (二)安裝figaro 因為後續整合Facebook登入時,須管理機密資訊或密碼,所以推薦額外安裝此套件。如果在開發專案時,有一組key不希望公開上傳至github,可以先把資訊存在config/application.yml檔,再使用ENV環境變數的方式存取。 1、到[RubyGems](https://rubygems.org/gems/figaro/versions/1.0.0?locale=zh-TW)複製指令至Gemfile檔案裡 ```gem 'figaro', '~> 1.0'``` 2、執行安裝 ```bundle install``` 3、安裝完成後會自動生成config/application.yml檔案,可在 .gitnore檔案,裡面增加下行指令,將這個檔案引入進來。 ```/config/application.yml``` ### (三)使用Devise整合Facebook登入 1、到[RubyGems](https://rubygems.org/gems/omniauth-facebook)複製指令至Gemfile檔案裡 ```gem 'omniauth-facebook', '~> 8.0''``` 2、執行安裝 ```bundle``` 3、新增一個migration檔 ```rails g migration AddFacebookAPIToUsers``` 4、確定內容後,執行 ```rails db:migrate``` 5、在稍早安裝figaro自動生成的config/application.yml檔裡,放入你申請到的 App ID 和 App Secret 。 ![App ID 和 App Secret](https://i.imgur.com/zn0OEGC.png) 6、在config/initializer/devise.rb檔裡,將稍早封裝的環境變數帶進來。 ``` config.omniauth :facebook, ENV['fb_api'], ENV['fb_secret'], :scope => 'public_profile,email', :info_fields => 'email,name', callback_url: "http://localhost:3000/users/auth/facebook/callback" ``` 7、在app/controller/users/omniauth_callbacks_controller.rb裡,新增此方法。 ``` def facebook @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.persisted? sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format? else session["devise.facebook_data"] = request.env["omniauth.auth"] redirect_to new_user_registration_url end end ``` *** - 按照[官方GitHub文件](https://github.com/heartcombo/devise/wiki/OmniAuth:-Overview),如果看到跳轉後出現「 Could not authenticate (無法驗證)」的訊息,可以在後面加上這個 ``` config.omniauth :facebook, "APP_ID", "APP_SECRET", token_params: { parse: :json } ``` ***