2

我正在使用Ruby版本1.8.7。使用Ruby将通知发送到Firebase

我使用此FCM宝石https://github.com/spacialdb/fcm并希望发送通知消息到Android客户端应用程序,但它不起作用。

在控制器:

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

类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. 服务器密钥是正确的,因为我可以通过PHP代码成功发送通知。
  2. 响应输出如下: { “MESSAGE_ID”=> 8885803884270587181}

任何人都可以请指出有什么不好的代码。 任何帮助将不胜感激。

+0

do'params.to_json' –

+0

response = self.class.post('/ send',params.merge(@client_options).to_json)产生错误TypeError(无法将String转换为散列)。 – Jimy25

+0

您的代码有效。没有错误消息。我不知道你在问什么。 –

回答

3

根据Firebase API documentation,您得到的响应是成功排队的消息的预期响应。

,你得到一个message_id的事实有这个意思:

当FCM已成功接收到请求,并会尝试发送到所有订阅设备中的主题消息ID。

它看起来像你的代码工作,即问题必须在别的地方。

编辑: 您发送数据消息。 (因为没有notification密钥,只是一个data密钥)也许你的客户期望通知消息呢?

请参阅documentation以区分这两种消息类型。

你可以尝试,只是添加通知关键要求:

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

我的Android客户端应用程序可以接收通过PHP代码发送时的通知。但不能用上面的Ruby代码。 – Jimy25

+0

太棒了!它工作。你拯救了我的一天。谢谢。 – Jimy25

1

我有这个问题之前

尝试添加priority: "high"notification: "your message"

在FCM类instatiation选项

0

试试这个

request = HTTParty.post('http://fcm.googleapis.com/fcm/send', :body => { "to" => "#{token}", "priority" => "high", "data" => { "title" =>title,"body"=>message,'massage_type'=>'text'}}.to_json, :headers => { 'Content-Type' => 'application/json', 'Authorization' => "key=#{server_token}" })