Python에서 쉽게 FCM V1 API 사용

Dec 05 2022
안녕 모두들. 새 fcm 프로젝트를 만들 때 더 이상 알다시피 레거시 API를 사용할 수 없습니다.

안녕 모두들. 새 fcm 프로젝트를 만들 때 더 이상 알다시피 레거시 API를 사용할 수 없습니다. V1 API만 사용하면 됩니다. 그리고 이것을 짧고 편리한 방법으로 설정하기 위한 자세한 문서나 문서가 기사에 없습니다. 그래서 이 새로운 API로 많은 고민을 하고 프로젝트를 마무리한 후, SDK가 내 프로젝트에서 허용하지 않는 JWT 버전을 사용하고 있었기 때문에 SDK를 사용하지 않기로 결정했습니다. 그래서 지금부터 우리는 API 자체를 원시 방식으로 계속할 것입니다.

구성 파일 가져오기

FCM 프로젝트를 생성한 후 프로젝트 설정으로 이동하여 서비스 계정을 선택한 다음 새 키 쌍을 생성하고 플랫폼에 저장합니다.

JSON 파일을 다운로드한 후 Vault와 같은 환경에 복사하여 저장할 수 있습니다. 그런 다음 FCM API에서 액세스 토큰을 인증하고 가져오는 데 사용합니다. 코드에서 액세스 토큰을 얻습니다.

creds   = {} # Your credentials dict that you installed above
scopes  = ['https://www.googleapis.com/auth/firebase.messaging']
cred_service = ServiceAccountCredentials.from_json_keyfile_dict(creds, scopes)
access_token = cred_service.get_access_token().access_token

headers = {
        'access_token_auth':'true',
        'Authorization':f'Bearer {access_token}'
    }
# For subscribing to topic

response = requests.post('https://iid.googleapis.com/iid/v1:batchAdd',headers=headers,
    json={
        "to":f"/topics/your_topic",
        "registration_tokens":[user_fcm_token]
    }
)

# For unsubscribing from topic

response = requests.post('https://iid.googleapis.com/iid/v1:batchRemove',headers=headers,
      json={
          "to":f"/topics/your_topic",
          "registration_tokens":[user_fcm_token]
      }
  )

# project_id is in credentials file you have downloaded

base_url = f'https://fcm.googleapis.com/v1/projects/{project_id}/messages:send'
headers = {'Authorization': 'Bearer ' + access_token}
data = {
    "message": {
        "topic": f'user_push_{topic}',
        "notification": {
            "title": title,
            "body": description
        },
        "webpush": {
        "fcm_options": {
            "link": url
            }
        },
        "data": {}
        }
}
resp = requests.post(base_url, json=data, headers=headers)