Creating a message subject in the cloud function

I am trying to create a theme for each newly created group. Therefore, I wrote this function to perform this operation.

exports.createGroupTopic = functions.database.ref("groups/{groupid}/id") .onWrite(event=>{ var groupid = event.params.groupid; request({ url: "https://iid.googleapis.com/iid/v1/my_registration_token/rel/topics/topic_name", headers: { 'Content-Type':'application/json', 'Content-Length': 0, 'Authorization':'my API Key' } }, function (error, response, body){ console.log(response); }); }); 

But when I run this code, I get the following response log in the Firebase console.

 IncomingMessage { _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: null, pipesCount: 0, flowing: true, ended: true, endEmitted: true, reading: false, sync: false, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: false, domain: null, _events: { end: [ [Function: responseOnEnd], [Function] ], close: [ [Function], [Function] ], data: [Function], error: [Function] }, _eventsCount: 4, _maxListeners: undefined, socket: TLSSocket { _tlsOptions: { pipe: null, secureContext: [Object], isServer: false, requestCert: true, rejectUnauthorized: true, session: undefined, NPNProtocols: undefined, ALPNProtocols: undefined, requestOCSP: undefined }, _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, _SNICallback: null, servername: null, npnProtocol: false, alpnProtocol: false, authorized: true, authorizationError: null, encrypted: true, _events: { close: [Object], end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], secure: [Function], free: [Function: onFree], agentRemove: [Function: onRemove], drain: [Function: ondrain], error: [Function: socketErrorListener], data: [Function: socketOnData] }, _eventsCount: 10, connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'iid.googleapis.com', _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: [Object], length: 0, pipes: null, pipesCount: 0, flowing: true, ended: true, endEmitted: true, reading: false, sync: false, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: false, domain: null, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, needDrain: false, ending: true, ended: true, finished: true, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, bufferedRequest: null, lastBufferedRequest: null, pendingcb: 0, prefinished: true, errorEmitted: false, bufferedRequestCount: 0, corkedRequestsFree: [Object] }, writable: false, allowHalfOpen: false, destroyed: true, _bytesDispatched: 468, _sockname: null, _pendingData: null, _pendingEncoding: '', server: undefined, _server: null, ssl: null, _requestCert: true, _rejectUnauthorized: true, parser: null, _httpMessage: ClientRequest { domain: null, _events: [Object], _eventsCount: 5, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: false, sendDate: false, _removedHeader: [Object], _contentLength: 0, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Circular], connection: [Circular], _header: 'GET /iid/v1/my_token_id/rel/topics/TOPIC_NAME HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: 0\r\nAuthorization: api_key\r\nhost: iid.googleapis.com\r\nConnection: close\r\n\r\n', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, timeout: undefined, method: 'GET', path: '/iid/v1/fphzdEcS_D0:APA91b 

Then I ran it locally again and it gave me an Invalid Token error. Then I tested the token to send a direct notification. And it works great.

I do not know where the problem is. SO need help :(

+1
firebase firebase-cloud-messaging
Apr 15 '17 at 0:50
source share
1 answer

This version of your code works for me. I added the POST method and the key= prefix to the authorization value. Try it and see if this works for you.

 exports.createGroupTopic = functions.database.ref("groups/{groupid}/id") .onWrite(event => { var groupid = event.params.groupid; request({ method: 'POST', // <= ADDED // ------------------- device token ------------ url: "https://iid.googleapis.com/iid/v1/cAzme9iGTO4:APA91bE...lRbx1yTei2PNFgTYGUQDUTj/rel/topics/someTopic", headers: { 'Content-Type':'application/json', 'Content-Length': 0, // Note below. Added: 'key=' // ----------------- server key -------------------------- 'Authorization':'key=AAAAXp8june:APA91bF-Nq9pmQKr...HOES6ugO3_Xf-jV472nfn-sb' } }, function (error, response, body){ console.log('error:', error); console.log('statusCode:', response && response.statusCode); }); }); 

I used this function to confirm that a topic subscription has been added. The returned body contains the status for the device, including topics that are subscribed to:

 exports.checkGroupTopic = functions.database.ref("groups/check") .onWrite(event => { const token = 'cAzme9iGTO4:APA91bE...lRbx1yTei2PNFgTYGUQDUTj'; const serverKey = 'AAAAXp8june:APA91bF-Nq9pmQKr...HOES6ugO3_Xf-jV472nfn-sb'; request({ method: 'GET', url: `https://iid.googleapis.com/iid/info/${token}?details=true`, headers: { 'Content-Type':'application/json', 'Content-Length': 0, 'Authorization':`key=${serverKey}` } }, function (error, response, body){ console.log('error:', error); console.log('statusCode:', response && response.statusCode); console.log('body:', body); }); }); 
+2
Apr 19 '17 at 6:16
source share
β€” -



All Articles