Created
April 18, 2021 03:13
-
-
Save f3z0/a09ae96b55ba95e117a596fb7e67e279 to your computer and use it in GitHub Desktop.
This is how to use Faraday and GoogleAuth to connect to your FCM instance and push to topics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# if you want or need to move off the legacy FCM HTTP endpoints this will get you started | |
# Use googleauth gem to construct JWT token | |
def construct_payload(topic, data, notification = nil) | |
message = { | |
'topic': "fcm_test", | |
# 'token': token, # OR, if you want to send to a specific device | |
'data': { | |
payload: data.to_json # note we can no longer embed objects within data | |
}, | |
} | |
if notification.present? | |
message['notification'] = notification | |
end | |
{ 'message': message } | |
end | |
def send_to_topic(topic, data) | |
# where fcm-test-a76f2 is your firebase project id | |
response = Faraday.post('https://fcm.googleapis.com/v1/projects/fcm-test-a76f2/messages:send') do |req| | |
req.headers['Content-Type'] = 'application/json' | |
req.headers['Authorization'] = "Bearer #{get_jwt_token}" | |
puts construct_payload(topic, data).to_json | |
req.body = construct_payload(topic, data).to_json | |
end | |
puts response.as_json | |
response | |
end | |
# fcm-test-a76f2-firebase-adminsdk-piqvh-c40188da2a.json is a service key | |
# see: https://firebase.google.com/docs/cloud-messaging/auth-server#provide-credentials-manually | |
def get_jwt_token | |
scope = 'https://www.googleapis.com/auth/firebase.messaging' | |
authorizer = Google::Auth::ServiceAccountCredentials.make_creds( | |
json_key_io: File.open(File.join(Rails.root, 'config', 'secrets', 'fcm-test-a76f2-firebase-adminsdk-piqvh-c40188da2a.json')), | |
scope: scope) | |
token = authorizer.fetch_access_token! | |
token['access_token'] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment