FCM v1, token

arkive dev·2024년 10월 17일

1. system architecture

@startuml
== phase 1 ==
app -> fcm : get token
app -> server : save token

== phase 2 ==
app -> server : business req
server --> app : business rsp
server -> server : check
server -> fcm : push req
fcm --> server : push rsp

@enduml

2. FCM info(json)

2.1. FCM : Firebase Cloud Messaging

2.2. FCM Console > 프로젝트 설정
2.2.1. 내 프로젝트 > Project number (for fcm url)

2.2.1. 내 앱 > google-services.json (for google req token)

2.2.3. fcm url (+project number)
https://fcm.googleapis.com/v1/projects/{APP_PROJECT_NUMBER}/messages:send

3. push data

  • state : is_check(대상 확인), is_send(전송 여부), reserved_at(예약일시)
  • push_token : target
  • push message : title, content, result

4. send push

4.1. get token

def get_access_token():
    global bearer_token, token_expiry

    try:
        # check expired or not exist token
        if bearer_token is None or token_expiry is None or time.time() >= token_expiry:
            SERVICE_ACCOUNT_FILE = os.path.join(os.path.dirname(__file__), 'tool', 'service_account.json')
            scheduler_logger.debug(f"SERVICE_ACCOUNT_FILE({SERVICE_ACCOUNT_FILE})")

            with open(SERVICE_ACCOUNT_FILE, 'r') as file:
                SERVICE_ACCOUNT_JSON = json.load(file)

            # create credentials
            credentials = service_account.Credentials.from_service_account_info(
                SERVICE_ACCOUNT_JSON, scopes=[GOOGLE_APPLICATION_CREDENTIALS_URL]
            )
            credentials.refresh(Request())

            # set expired date
            bearer_token = credentials.token
            scheduler_logger.debug(f"bearer_token({bearer_token})")
            token_expiry = time.time() + 1800  # 1800초 = 30min
    except Exception as e:
        print(f"Failed to generate Bearer Token: {e}")
        raise e
    return bearer_token

4.2. send push

def send_push_fcm(push_token, title, body):
    try:
        access_token = get_access_token()
        scheduler_logger.info(f"access_token({access_token})")

        fcm_url = f"https://fcm.googleapis.com/v1/projects/{APP_PROJECT_NUMBER}/messages:send"
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json"
        }

        fcm_message = {
            "message": {
                "token": push_token,
                "data": {
                    "title": title,
                    "message": body,
                    "priority": "high"
                },
                "notification": {
                    "title": title,
                    "body": body
                }
            }
        }
        response = requests.post(fcm_url, headers=headers, data=json.dumps(fcm_message))
        scheduler_logger.debug(f"response({response})")

        return response
    except Exception as e:
        scheduler_logger.exception(f"Failed to send push notification: {e}")
        return e

write by chris

0개의 댓글