[Functions/Flutter] Firebase Functions 사용해서 FCM 푸시알람 구현하기 3/3 - Http 요청으로 Functions 호출하기

찌니·2023년 7월 25일
1

Fcm+Functions

목록 보기
3/3
post-thumbnail

푸시 알람을 구현했지만 Windows에서는 cloud_functions 라이브러리를 쓰지 못한다...
결론 : 내가 구현한 윈도우용 관리자 어플리케이션(flutter)에서는 호출이 불가능하다! Http api 호출로 구현해야한다!!

시작해보자 .......

http 요청을 보낼 새로운 functions을 배포해보자

const admin = require('firebase-admin');
const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors');

admin.initializeApp(functions.config().firebase);
const db = admin.firestore();

const app = express();
app.use(cors({origin: true}));

exports.pushFcm = functions.https.onRequest(app);

app.post('/update', (req, res) => {
  var tokens=[];

  const payload = {
    notification: {
      title: '공지사항 업데이트',
      body: `공지사항이 업데이트 되었습니다.`,
    },
  };
    // FireStore 에서 데이터 읽어오기
  db.collection('user').get().then((snapshot) => {
    snapshot.forEach((doc) => {
      if (doc.data().fcmToken!=null && doc.data().fcmToken!='' &&
        doc.data().fcmToken!=undefined) {
        tokens.push(doc.data().fcmToken);
      }
    });

    console.log(tokens);

    if (tokens.length > 0) {
      admin.messaging().sendToDevice(tokens, payload)
          .then((response) => {
            console.log('Successfully sent message:', response);
            return true;
          });
    } 
  })
      .catch((err) => {
        console.log('Error getting documents', err);
        tokens.push('Error getting documents');
        return tokens;
      });
});

app.post('/updateAnswer', (req, res) => {
  const payload = {
    notification: {
      title: '답변 업데이트',
      body: `답변이 업데이트 되었습니다.`,
    },
  };

  if (req.param('call') !=null && req.param('call')!='' &&
  req.param('call')!=undefined) {
    db.collection('user').doc(req.param('call')).get()
        .then((snapshot) => {
          console.log(snapshot.data().fcmToken);
          if (snapshot.data().fcmToken!=null && snapshot.data().fcmToken!='' &&
            snapshot.data().fcmToken!=undefined) {
            var token = snapshot.data().fcmToken;

            admin.messaging().sendToDevice(token, payload)
                .then((response) => {
                  console.log('Successfully sent message:', response);
                  return true;
                });
          }
        })
        .catch((err) => {
          console.log('Error getting documents', err);
          return false;
        });
  }
});

firebase deploy --only functions:pushFcm

console창에 들어가보면 요로케 방금 새롭게 만든 functions을 확인할 수 있다

FcmService.dart

final pushFcmUrl = 'https://us-central1-project-56816.....net/pushFcm';

Future<void> pushUpdate(bool update) async {
    try {
      final http.Response response = await http.post(
        Uri.parse('$pushFcmUrl/update'),
        headers: <String, String>{
          'Content-Type': 'application/X-www-form-urlencoded',
        },
      );

      print('pushFCM: success');
    } catch (e) {
      print('pushFAQ: ${e}');
      throw Exception("pushFAQ: $e");
    }
}

Future<void> pushAnswer(String callNum) async {
    try {
      final http.Response response = await http.post(
        Uri.parse('$pushFcmUrl/updateAnswer'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode({'call': callNum}),
      );
      print('pushFCM: success');
    } catch (e) {
      print('pushFAQ: $e');
      throw Exception("pushFAQ: $e");
    }
  }

요로케 모든 구현이 완료되었다
결과는 !!!!

앱에서 직접 호출한 것과 다르지 않다!

profile
찌니's develog

0개의 댓글