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