I am trying to send messages through Google Cloud Messaging, using Python sleekXMPP. I tried to follow the sample in the GCM docs. However, I am getting an "InvalidJson : MissingPayload" error response (400) when I call send_command
. What am I missing here? The following is the code that I use.
def random_id():
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
class GcmNotifier(sleekxmpp.ClientXMPP):
def __init__(self, jid, password):
super(GcmNotifier, self).__init__(jid, password)
self.add_event_handler('message', self.on_message_received)
def send_gcm_message(self, message):
body = '<gcm xmlns:"google:mobile:data">%s</gcm>' % json.dumps(message)
print(body)
self.send_message(mto='', mbody=body)
def on_message_received(self, message):
print(message)
def send_command(self, recipient):
self.send_gcm_message({
'to': recipient,
'message_id': random_id(),
'data':
{
'hello': 'world'
}
})
xmpp = GcmNotifier(GCM_SENDER_ID + '@gcm.googleapis.com', GCM_API_KEY)
if xmpp.connect((GCM_SERVER, GCM_PORT), use_ssl=True):
xmpp.process(block=False)
This is the error that I receive:
<message to="REDACTED@gcm.googleapis.com/475DBA7C" type="error" xml:lang="en"><body><gcm xmlns:"google:mobile:data">{"to": "REDACTED", "data": {"hello": "world"}, "message_id": "ZGDZ9QTD"}</gcm></body><error code="400" type="modify"><bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" /><text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">InvalidJson : MissingPayload</text></error></message>
It turns out SleekXMPP was automatically enclosing my message in
<body />
tags, which is not the expected message format by the GCM server. I ended up solving the problem by defining my own stanzas, like this:and then by sending the message like this:
The error you are receiving for
Missing Payload
is because you are not passing any parameter as Key and value format to be recognized as payload.First you have to define a function where you are going to pass the payload and then covert it back to the plain text after the GCm server responds back.
Here is an example:
You can have the exponential Back-Off mechanism if you need to have in your code that would ping the server after some duration.
For the detail code implementation, please read the following document.