Hello community,
My goal is to send a message from elixir back end server to an android application. I came to the conclusion that google’s firebase is currently the best option.
My problem is related to authorization and sending a message to the console Firebase.
Having downloaded my secret json from console.firebase.google.com
I tried to link elixir with the platform. The problem here is that I struggle dealing with that jwt token - (FunctionClauseError) no function clause matching in :jose_jwk.from/1
defmodule App.Firebase do
@moduledoc """
Module for sending messages through Firebase Cloud Messaging.
"""
@fcm_url "https://fcm.googleapis.com/v1/projects/censored/messages:send"
@service_account_path "priv/firebase/serviceAccountKey.json"
alias JOSE.{JWK, JWS, JWT}
def send_message(token, message) do
service_account = Jason.decode!(File.read!(@service_account_path))
jwt = generate_jwt(service_account)
IO.puts("JWT generated successfully.")
headers = [
{"Authorization", "Bearer #{jwt}"},
{"Content-Type", "application/json"}
]
body = %{
message: %{
token: token,
notification: %{
title: "Notification Title",
body: message
}
}
}
|> Jason.encode!()
IO.puts("Sending message to FCM...")
case HTTPoison.post(@fcm_url, body, headers) do
{:ok, %HTTPoison.Response{status_code: 200, body: response_body}} ->
IO.puts("Message sent successfully!")
IO.inspect(response_body)
{:ok, %HTTPoison.Response{status_code: status_code, body: response_body}} ->
IO.puts("Failed to send message. Status code: #{status_code}")
IO.inspect(re my problem is withsponse_body)
{:error, %HTTPoison.Error{reason: reason}} ->
IO.puts("Error occurred while sending message")
IO.inspect(reason)
end
end
defp generate_jwt(service_account) do
iat = :os.system_time(:second)
exp = iat + 3600 # 1 hour expiration
claims = %{
"iss" => service_account["client_email"],
"sub" => service_account["client_email"],
"aud" => "https://oauth2.googleapis.com/token",
"iat" => iat,
"exp" => exp,
"scope" => "https://www.googleapis.com/auth/firebase.messaging"
}
private_key = service_account["private_key"]
jwk = JWK.from_pem(private_key)
{_, jwt} = claims |> JWT.sign(jwk) |> JWS.compact
jwt
end
end
Have someone encountered with this before? Is this the right way anyway or I am at a dead end