Firebase 기존 HTTP에서 HTTP v1로 마이그레이션 하기

sunn_ni·2024년 6월 7일
0

firebase

목록 보기
1/2
const admin = require('firebase-admin');
const axios = require('axios');
const serviceAccount = require('./path/to/serviceAccountKey.json');

// Firebase Admin SDK 초기화
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
});

// OAuth 2.0 토큰 가져오기
async function getAccessToken() {
    try {
        const tokenResponse = await admin.credential.cert(serviceAccount).getAccessToken();
        return tokenResponse.access_token;
    } catch (error) {
        console.error('Error fetching access token:', error);
        throw error;
    }
}

// HTTP v1 API를 사용하여 푸시 알림 보내기
async function sendPushNotification(token, data) {
    const accessToken = await getAccessToken();
    const url = `https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send`;

    const payload = {
            message: {
                token: token,
                data: data,
                android: {
                    priority: 'high'
                },
                apns: {
                    payload: {
                        aps: {
                            'content-available': 1
                        }
                    },
                    headers: {
                        'apns-priority': '10'
                    }
                }
            }
      };

    try {
        const response = await axios.post(url, payload, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${accessToken}`,
            },
        });

        console.log('Successfully sent message:', response.data);
    } catch (error) {
        console.error('Error sending message:', error.response ? error.response.data : error.message);
    }
}


sendPushNotification(userToken, data);

firebase-admin 라이브러리를 이용해서, token을 발급받고,
firebase cloud messaging api를 활용하여 푸시알람 보내기

*참고문서
https://firebase.google.com/docs/cloud-messaging/migrate-v1?hl=ko
https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages?hl=ko
https://firebase.google.com/docs/admin/setup?hl=ko
https://developer.apple.com/documentation/usernotifications/generating-a-remote-notification

profile
방황중인 서버개발자

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN