【问题标题】:Python - Push Notification through FCM / APNs to IOS or Android DevicesPython - 通过 FCM / APNs 向 IOS 或 Android 设备推送通知
【发布时间】:2017-08-30 04:50:08
【问题描述】:

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

【问题讨论】:

    标签: python firebase firebase-cloud-messaging


    【解决方案1】:

    我为此苦苦挣扎了一会儿,所以我想我最终会发布对我有用的代码。您需要做的就是从 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"
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多