I recently disabled the legacy Cloud Messaging API and switched to the new Firebase Cloud Messaging API (V1) as shown in the screenshot below:
Previously, I used the following code to subscribe a user to a topic and then send messages to the topic, and its work well:
...
@classmethod
def subscribe_to_topic(cls, device_id, topics: list):
success = []
for topic in topics:
try:
url = f'https://iid.googleapis.com/iid/v1/{device_id}/rel/topics/{topic}'
headers = _get_header()
result = requests.post(url, headers=headers)
success.append(True) if result.status_code == 200 else success.append(False)
logger.info(f'subscribe user <{device_id}> in topic <{topic}> with status code: {result.status_code}')
except Exception as e:
logger.error(f'{e}')
return all(success)
After switching to the new API, I tried to update my code as follows, but it didn’t work:
...
@classmethod
def subscribe_to_topic(cls, device_id, topics: list):
"""Subscribes a device to a topic using FCM v1 API."""
payload = {"registrationTokens": [device_id]}
success = []
for topic in topics:
try:
url = (f"https://fcm.googleapis.com/v1/"
f"projects/{environ.get('FCM_PROJECT_NAME')}/topics/{topic}:subscribe")
headers = _get_header()
result = requests.post(url, headers=headers, json=payload)
success.append(True) if result.status_code == 200 else success.append(False)
logger.info(f'subscribe user <{device_id}> in topic <{topic}> with status code: {result.status_code}')
except Exception as e:
logger.error(f'{e}')
return all(success)
I have read the Firebase documentation, but I’m still unsure how to properly migrate my topic subscription and message sending functionality to the new API.
Could someone provide guidance or an example on how to achieve this with the new Firebase Cloud Messaging API (V1)?
Additional Context:
- The previous code subscribes a user to multiple topics and sends messages to those topics.
- The updated code should use the new Firebase Cloud Messaging API (V1).
Any help or examples would be greatly appreciated!