2017-08-30 228 views
1

我正在我的python项目上工作,我需要为apns和fcm/gcm创建我自己的推送通知服务器,它向ios和android发送推送通知同时,我浏览了Firebase文档,但是网站上没有代码示例。任何人都可以给我一个关于如何在Python代码中完成这个的想法吗?Python - 推送通知通过FCM/APN到IOS或Android设备

回答

0

我挣扎了一会儿,所以我想我会发布最终为我工作的代码。所有你需要做的是做从谷歌oauth2client画中画安装(https://github.com/google/oauth2client):

PIP安装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" 
}