Python - 通过FCM / APN向IOS或Android设备推送通知

时间:2017-08-30 04:50:09

标签: python firebase firebase-cloud-messaging

我正在研究我的python项目,我需要为apns和fcm / gcm创建我自己的推送通知服务器,它同时向ios和android发送推送通知,但我查看了Firebase文档但是,网站上没有代码示例。任何人都可以告诉我如何在Python代码中完成此操作吗?

1 个答案:

答案 0 :(得分:0)

我挣扎了一会儿所以我想我最后会发布最适合我的代码。您需要做的就是从Google(https://github.com/google/oauth2client)执行oauth2client的pip安装:

pip install oauth2client

现在,您需要导入服务帐户,该帐户将为您生成可在API中使用的短期令牌,以便您的应用服务器可以与FCM Google服务器进行通信。

按照以下网站的指示行事:

https://firebase.google.com/docs/cloud-messaging/auth-server

from oauth2client.service_account import ServiceAccountCredentials

def _get_access_token():
  """Retrieve a valid access token that can be used to authorize requests.

  :return: Access token.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      'service-account.json', FCM_SCOPE)
  access_token_info = credentials.get_access_token()
  return access_token_info.access_token

现在,一旦你拥有了short_lived令牌,就可以在API调用中使用它来向你的android / IOS设备发送消息:

import requests, json
values = {"message":{"token":"<insert android firebase token id here>","notification":{"body":"This is a Firebase Cloud Messaging Topic Message for testing!","title":"FCM Message!!"}}}
header ={ 'Content-Length': '33333', 'Content-Type': 'application/json; UTF-8', 'Authorization': 'Bearer ' + _get_access_token(), 'User-Agent': 'Mozilla/5.0'}
url = 'https://fcm.googleapis.com/v1/projects/<insert project name here>/messages:send'
print(header)
r = requests.post(url, data=json.dumps(values), headers=header)
print(r.text)

如果通话成功,您将在屏幕上收到刚刚发送的FCM消息参考的打印件:

{
  "name": "projects/<your project name>/messages/0:1519633952417262%0958967209589672"
}