rails Railsで Firebase Cloud Messagingを使う

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます
Firebaseから認証keyを取得する



googleの認証モジュールをインストールするのに bigqueryのライブラリをインストールした
gem 'google-cloud-bigquery'
※ Google::Auth::ServiceAccountCredentialsが使えれば別に上記のGemでなくても良い


Push通知を送るためのライブラリを作成した
以下ソース全容
Firebaseから取得した認証keyは 環境変数 “GCP_AUTH_KEY_FILE” にpathを保存している
class Push
  attr_accessor :token, :title, :body
  def initialize(params = {})
    url = "https://fcm.googleapis.com/v1/projects/#{ENV["FIREBASE_PROJECT_ID"]}/messages:send"
    scope = 'https://www.googleapis.com/auth/firebase.messaging'
    @authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open(ENV["GCP_AUTH_KEY_FILE"]),
      scope: scope
    )
    @connection = Faraday.new(url: url)
    @token, @title, @body, @url = params.values_at(:token, :title, :body, :url)
  end


  def access_token
    @authorizer.fetch_access_token!["access_token"].to_s
  end


  def body
    {
      message: {
        token: @token,
        notification: {
          title: @title,
          body: @body,
        },
        data: { url: @url }
      }
    }
  end


  def notify
    @connection.post do |req|
      req.headers['Content-Type'] = 'application/json'
      req.headers['Authorization'] = "Bearer " + access_token
      req.body = body.to_json
    end
  end
end

上記のモジュールを使う
p = Push.new({ token: fcm_token, title: title, body: title, url: url })
p.notify
※ fcm_tokenはアプリから取得してサーバーに送ってもらっている

[参考]
Back