在云function上创build消息传递主题

我正在尝试为每个新创build的组创build主题。 所以我写这个函数来做这个操作。

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); }); }); 

但是,当我运行此代码时,我在Firebase控制台上获得了以下响应日志。

 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 

然后我再次在本地运行,它给了我无效的令牌错误。 然后我testing了令牌发送直接通知。 它的工作完美。

我不知道问题在哪里。 所以需要帮助:(

你的代码的这种变化适用于我。 我在授权值中添加了POST方法和前缀key= 。 尝试一下,看看它是否适合你。

 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); }); }); 

我使用这个函数来确认主题订阅被添加了。 返回的主体包含设备的状态,包括订阅的主题:

 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); }); });