问题
I try to use Firebase cloud messaging HTTP v1
Here's the Python code which run under Windows
import json
import requests
from google.oauth2.service_account import Credentials
import google.auth.transport.requests
def _get_access_token():
credentials = Credentials.from_service_account_file(
'C:/yocto/wenote-notification/send_notification/wenote-206215-firebase-adminsdk-9fpls-a3fdd2934c.json',
scopes=['https://www.googleapis.com/auth/firebase.messaging']
)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
access_token = credentials.token
return access_token
def generate_header():
return {'Authorization' : 'Bearer ' + _get_access_token(), 'Content-type' : 'application/json'}
# Header
headers = generate_header()
print(headers)
# Data
string = '{"message":{"token": "cSW75-6OF-w:APA91bE-E6vWucBe8rRijpDLlZGHhyfwoaLJr3R1TZEvieBM-__ZXwXlBS34kUticUN_eSbwvQGTymbmtd7sHT5U9O_v9HePyVn7jnUD9IBdoZZYSQ1CrgxXS1sz9wjAd5pKHIddoKj8", "data": {"sync": false, "sync_device_count": 2}, "fcm_options": {"analytics_label": "wenote_analytics_label"}}}'
request_data = json.loads(string)
print(request_data)
r = requests.post('https://fcm.googleapis.com/v1/projects/wenote-206215/messages:send', headers=headers, json=request_data)
if r.status_code != 200:
r.raise_for_status()
The message I send to Firebase server is
{
"message":{
"token":"cSW75-6OF-w:APA91bE-E6vWucBe8rRijpDLlZGHhyfwoaLJr3R1TZEvieBM-__ZXwXlBS34kUticUN_eSbwvQGTymbmtd7sHT5U9O_v9HePyVn7jnUD9IBdoZZYSQ1CrgxXS1sz9wjAd5pKHIddoKj8",
"data":{
"sync":false,
"sync_device_count":2
},
"fcm_options":{
"analytics_label":"wenote_analytics_label"
}
}
}
However, I'm getting the following error
c:\yocto\wenote-notification\send_notification>python a.py
{'Authorization': 'Bearer ya29.c.Ko8BvQdCd-8US-DzQ-AcuTOURlGTQEvJt4mtofaeM08LRIhXBfC4RFN3QzkAcCdnaqI6uJLQlk1YJg67KQOhF8CtNux9t743nq2NN9uoW2mbQiB2y_2fjRUhiIIM7Wz2nt9rDOM4zFIFwKlHtLPXRLa4IGo0Ho-dq8zzVxQH1qPNGqy_ja8WowQCY5ReAQkmAmE', 'Content-type': 'application/json'}
{'message': {'token': 'cSW75-6OF-w:APA91bE-E6vWucBe8rRijpDLlZGHhyfwoaLJr3R1TZEvieBM-__ZXwXlBS34kUticUN_eSbwvQGTymbmtd7sHT5U9O_v9HePyVn7jnUD9IBdoZZYSQ1CrgxXS1sz9wjAd5pKHIddoKj8', 'data': {'sync': False, 'sync_device_count': 2}, 'fcm_options': {'analytics_label': 'wenote_analytics_label'}}}
Traceback (most recent call last):
File "a.py", line 38, in <module>
r.raise_for_status()
File "C:\Python36\lib\site-packages\requests\models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://fcm.googleapis.com/v1/projects/wenote-206215/messages:send
Any idea why it is so, and how I can resolve this?
I have check my Firebase cloud messaging console. It is enabled.
回答1:
You need to slightly adapt your request_data object, because the schema changed.
Before (legacy http protocol):
{
"to": "/topics/news",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"data": {
"story_id": "story_12345"
}
}
After (HTTP v1 API):
{
"message": {
"topic": "news",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"data": {
"story_id": "story_12345"
}
}
}
Notice the change in the topic parameters, as well the wrap by a message object.
Check out this guide: https://firebase.google.com/docs/cloud-messaging/migrate-v1
You can check out this very clean and structure python based minimal example for FCM: https://github.com/firebase/quickstart-python/blob/688fcfa8068dcac67978a171df828c9e77cd320e/messaging/messaging.py#L57
回答2:
This is the way to debug the above problem.
Use
if r.status_code != 200:
print(r.text)
r.raise_for_status()
instead of
if r.status_code != 200:
r.raise_for_status()
We will get the following error
{
"error": {
"code": 400,
"message": "Invalid value at 'message.data[0].value' (TYPE_STRING), false\nInvalid value at 'message.data[1].value' (TYPE_STRING), 2",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "message.data[0].value",
"description": "Invalid value at 'message.data[0].value' (TYPE_STRING), false"
},
{
"field": "message.data[1].value",
"description": "Invalid value at 'message.data[1].value' (TYPE_STRING), 2"
}
]
}
]
}
}
Look like HTTP v1 is pretty strict on the value type (It need to be String)
Hence, instead of using
string = '{"message":{"token": "cSW75-6OF-w:APA91bE-E6vWucBe8rRijpDLlZGHhyfwoaLJr3R1TZEvieBM-__ZXwXlBS34kUticUN_eSbwvQGTymbmtd7sHT5U9O_v9HePyVn7jnUD9IBdoZZYSQ1CrgxXS1sz9wjAd5pKHIddoKj8", "data": {"sync": false, "sync_device_count": 2}, "fcm_options": {"analytics_label": "wenote_analytics_label"}}}'
We need to use
string = '{"message":{"token": "cSW75-6OF-w:APA91bE-E6vWucBe8rRijpDLlZGHhyfwoaLJr3R1TZEvieBM-__ZXwXlBS34kUticUN_eSbwvQGTymbmtd7sHT5U9O_v9HePyVn7jnUD9IBdoZZYSQ1CrgxXS1sz9wjAd5pKHIddoKj8", "data": {"sync": "false", "sync_device_count": "2"}, "fcm_options": {"analytics_label": "wenote_analytics_label"}}}'
来源:https://stackoverflow.com/questions/60164581/firebase-cloud-messaging-http-v1-send-error-400-client-error-bad-request-for