Arbee
Arbee

Reputation: 35

Send notifications through Cloudflare workers using Firebase Cloud Messaging REST Api

I've been trying to make a Cloudflare Worker, that sends notifications to my Android App. I was able to make it send them, but only by manually going through the "sign in" Process each time, because when I use the oauth2 token I get from https://accounts.google.com/o/oauth2/v2/auth it becomes invalid and I can't reuse it to get a new access_token from https://oauth2.googleapis.com/token. And if I use the refresh_token I get together with the access_token, to refresh it each time, it'd still break after a year when the refresh token expires. Is there some way to get a permanent token to repeatedly use and send notifications?

Current code I have:

export default {
  async fetch(request, env, ctx) {
    const { searchParams } = new URL(request.url)
    let auth_token = searchParams.get('code')
    const req1 = await fetch(`https://oauth2.googleapis.com/token`
      + `?code=${auth_token}`
      + `&redirect_uri=${REDIRECT_URI}`
      + `&client_id=${CLIENT_ID}`
      + `&client_secret=${env.CLIENT_SECRET}`
      + `&grant_type=authorization_code`
      + `&scope=${SCOPE}`,
      { method: "POST" }
    );
    const reqJson = await req1.json()
    const respBody = {
      "message": {
        "token": APP_TOKEN,
        "notification": {
          "body": "This is an FCM notification message!",
          "title": "FCM Message"
        }
      }
    }
    const respHeaders = new Headers({
      "Authorization": "Bearer " + reqJson.access_token,
      "Content-Type": "application/json"
    })
    const notificationResp = fetch(
      `https://fcm.googleapis.com/v1/projects/${PROJECT_NAME}/messages:send`,
      {
        method: "POST",
        body: JSON.stringify(respBody),
        headers: respHeaders
      }
    )

    return new Response(JSON.stringify(reqJson) + "\n" + JSON.stringify((await notificationResp).json()))
  },
};

const APP_TOKEN = "[REDACTED]"
const PROJECT_NAME = "[REDACTED]"
const CLIENT_ID = '[REDACTED]'
const SCOPE = '[REDACTED]'
const REDIRECT_URI = '[REDACTED]'

Upvotes: 2

Views: 772

Answers (0)

Related Questions