Ionic 3如何通过Firebase实现设备间推送通知发送?
当然可以实现!你要的设备到设备推送通知,核心思路是借助Firebase Cloud Messaging(FCM)的后台能力做中转(毕竟直接在设备端用FCM密钥太不安全)。下面是针对Ionic 3的完整实现方案:
核心原理说明
FCM不允许直接从客户端设备发起推送请求(因为需要用到仅能在服务器端保存的服务器密钥),所以我们需要一个中间层:要么自己搭建后端服务,要么用Firebase自带的Cloud Functions(推荐,不用自己维护服务器)。流程大概是:
- 每个设备安装应用后,获取自己的FCM令牌并存储到Firebase数据库(比如Firestore)
- 发送方设备调用Cloud Functions函数,传入目标用户ID、通知标题和内容
- Cloud Functions从数据库拿到目标用户的FCM令牌,调用FCM官方API发送通知
- 接收方设备通过FCM插件监听并处理通知
具体实现步骤
1. 确保项目已集成FCM
首先确认你的Ionic 3项目已经安装了合适的FCM插件,推荐用cordova-plugin-fcm-with-dependecy-updated(适配Ionic 3的稳定版本):
ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated npm install @ionic-native/fcm
同时要确保Firebase的配置文件(Android的google-services.json、iOS的GoogleService-Info.plist)已经正确添加到项目中。
2. 获取并存储FCM令牌
每个设备会生成唯一的FCM令牌,需要把它和用户绑定存储到Firebase数据库(这里用Firestore举例):
// 在app.component.ts或者用户登录后的页面中 import { FCM } from '@ionic-native/fcm'; import { AngularFirestore } from 'angularfire2/firestore'; import { AuthService } from '../services/auth.service'; // 假设你有用户认证服务 constructor( private fcm: FCM, private afs: AngularFirestore, private authService: AuthService ) {} ionViewDidLoad() { // 获取当前登录用户ID(根据你的认证方式调整) const currentUserId = this.authService.getCurrentUserId(); // 获取FCM令牌 this.fcm.getToken().then(token => { // 存储令牌到Firestore的users集合 this.afs.collection('users').doc(currentUserId).set( { fcmToken: token }, { merge: true } // 合并现有数据,不覆盖其他字段 ); }); // 监听令牌更新(FCM令牌可能会变化) this.fcm.onTokenRefresh().subscribe(newToken => { this.afs.collection('users').doc(currentUserId).update({ fcmToken: newToken }); }); }
3. 编写Firebase Cloud Functions中转函数
创建一个Callable类型的云函数,负责处理推送请求:
- 先在本地初始化Firebase Functions(如果没弄过的话):
firebase init functions - 打开
functions/index.js,写入以下代码:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); // 发送推送通知的Callable函数 exports.sendPushNotification = functions.https.onCall(async (data, context) => { // 验证用户身份(可选但强烈推荐,防止未授权调用) if (!context.auth) { throw new functions.https.HttpsError('unauthenticated', '请先登录'); } const { targetUserId, title, body } = data; // 从Firestore获取目标用户的FCM令牌 const userDoc = await admin.firestore().collection('users').doc(targetUserId).get(); if (!userDoc.exists) { throw new functions.https.HttpsError('not-found', '目标用户不存在'); } const targetToken = userDoc.data().fcmToken; if (!targetToken) { throw new functions.https.HttpsError('failed-precondition', '目标用户未开启推送权限'); } // 构建FCM通知消息 const message = { notification: { title: title, body: body }, token: targetToken }; // 调用FCM API发送通知 try { await admin.messaging().send(message); return { success: true, msg: '通知发送成功' }; } catch (err) { console.error('推送失败:', err); throw new functions.https.HttpsError('internal', '发送通知失败,请稍后重试'); } });
- 部署云函数到Firebase:
firebase deploy --only functions
4. 在Ionic应用中调用云函数发送通知
发送方设备调用刚才部署的Callable函数,传入推送参数:
// 在发送通知的页面组件中 import { AngularFireFunctions } from 'angularfire2/functions'; constructor(private fns: AngularFireFunctions) {} // 调用此方法发送通知 sendNotification(targetUserId: string, title: string, content: string) { const sendNotificationFn = this.fns.httpsCallable('sendPushNotification'); sendNotificationFn({ targetUserId: targetUserId, title: title, body: content }).subscribe( result => { console.log('通知发送成功:', result); // 这里可以添加成功提示,比如Toast }, error => { console.error('发送失败:', error); // 处理错误,比如显示错误提示 } ); }
5. 处理接收通知的逻辑
确保应用在前台、后台都能接收并处理通知:
// 在app.component.ts中 this.fcm.onNotification().subscribe(data => { if (data.wasTapped) { // 通知在后台时被点击,这里可以跳转到对应页面 console.log('通知被点击:', data); // 比如跳转到消息详情页 this.navCtrl.push('MessageDetailPage', { notificationData: data }); } else { // 应用在前台时收到通知,这里可以弹出提示框 console.log('前台收到通知:', data); this.alertCtrl.create({ title: data.title, message: data.body, buttons: ['确定'] }).present(); } });
关键注意事项
- iOS配置:iOS需要额外配置推送证书,在Xcode中开启
Push Notifications能力,确保Provisioning Profile包含推送权限。 - 权限控制:云函数中的身份验证一定要加上,避免恶意调用消耗你的FCM配额。
- 令牌有效性:FCM令牌可能会过期或变更,所以一定要监听
onTokenRefresh事件及时更新数据库中的令牌。 - FCM配额:Firebase免费版有推送配额限制,如果是高流量应用可能需要升级付费方案。
内容的提问来源于stack exchange,提问作者Nafis Abdullah Bin Azad
相关产品推荐
相关产品推荐

