Using Ruby to send notification to Firebase

Viewed 6173

I am using Ruby version 1.8.7.

I use this FCM gem https://github.com/spacialdb/fcm and want to send notification message to Android client app but it does not work.

In Controller:

fcm = FCM.new(FIREBASE_API_KEY, :timeout => 30)
 options = {:data => {:message => "This is a FCM Topic Message!"}}
 response = fcm.send_to_topic('global', options)

Class FCM:

require 'httparty'
require 'cgi'
require 'json'

class FCM
  include HTTParty
  base_uri 'https://fcm.googleapis.com/fcm'
  default_timeout 30
  format :json

  attr_accessor :timeout, :api_key

  def initialize(api_key, client_options = {})
    @api_key = api_key
    @client_options = client_options
  end

  def send_with_notification_key(notification_key, options = {})
    body = { :to => notification_key }.merge(options)

    params = {
        :body => body.to_json,
        :headers => {
        'Authorization' => "key=#{@api_key}",
        'Content-Type' => 'application/json'
    }
  }

  response = self.class.post('/send', params.merge(@client_options))
  response.parsed_response
  end

  def send_to_topic(topic, options = {})
    if topic =~ /[a-zA-Z0-9\-_.~%]+/
        send_with_notification_key('/topics/' + topic, options)
    end
  end
end
  1. The server key is correct, because I can send notification successfully by PHP code.
  2. The response output as below: {"message_id"=>8885803884270587181}

Could anyone please to point out what wrong with the code. Any help would be greatly appreciated.

5 Answers

I am not sure if this is due to changes in FCM itself but using the syntax from the gem's documentation or using the format from Daniel's answer did not work for me (Daniel's version gives an error response from FCM saying that notification must be a JSON object).

This is what worked for me:

fcm.send_to_topic(topic, notification: { body: "topic notification" })

Unfortunately the fcm library does not provide support to the rubies < 2.0. According to the git history of the repository that was the case already at the start of the project.

Related