2017-08-30 232 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" 
}