在云功能上创建消息传递主题



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

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.1rnContent-Type: application/jsonrnContent-Length: 0rnAuthorization: api_keyrnhost: iid.googleapis.comrnConnection: closernrn',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/iid/v1/fphzdEcS_D0:APA91b

然后我在本地再次运行它,它给了我无效令牌错误。然后我测试了令牌以发送直接通知。而且它运行良好。

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

你的代码的这种变体对我有用。我将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);
        });
    });

相关内容

  • 没有找到相关文章

最新更新