Firebase
付费插件
此插件需要购买。价格:$99(一次性购买)
概述
PushNotifications API 处理 Firebase Cloud Messaging 的设备注册以接收推送通知。
安装
shell
composer require nativephp/mobile-firebase配置
Android 设置
- 在 Firebase Console 创建 Firebase 项目
- 将你的 Android 应用添加到项目中
- 下载
google-services.json并放置在项目根目录 - 插件编译器会自动将其复制到 Android 项目
iOS 设置
- 在你的 Firebase 项目中添加 iOS 应用
- 下载
GoogleService-Info.plist并放置在项目根目录 - 在 Apple Developer 账户中启用推送通知功能
- 插件编译器会处理配置
使用
PHP (Livewire/Blade)
php
use Native\Mobile\Facades\PushNotifications;
// 注册推送通知
PushNotifications::enroll();
// 获取当前 token
$token = PushNotifications::getToken();JavaScript (Vue/React/Inertia)
js
import { pushNotifications, on, off, Events } from '#nativephp';
// 基本注册
await pushNotifications.enroll();
// 带有用于跟踪的标识符
await pushNotifications.enroll()
.id('main-enrollment')
.remember();
// 获取当前 token
const result = await pushNotifications.getToken();
const token = result.token; // iOS 上是 APNS token,Android 上是 FCM token事件
TokenGenerated
当推送通知 token 成功生成时触发。
php
use Native\Mobile\Attributes\OnNative;
use Native\Mobile\Events\PushNotification\TokenGenerated;
#[OnNative(TokenGenerated::class)]
public function handlePushToken(string $token)
{
// 将 token 发送到后端
$this->sendTokenToServer($token);
}js
import { on, off, Events } from '#nativephp';
import { onMounted, onUnmounted } from 'vue';
const handleTokenGenerated = (payload) => {
const { token } = payload;
// 将 token 发送到后端
sendTokenToServer(token);
};
onMounted(() => {
on(Events.PushNotification.TokenGenerated, handleTokenGenerated);
});
onUnmounted(() => {
off(Events.PushNotification.TokenGenerated, handleTokenGenerated);
});jsx
import { on, off, Events } from '#nativephp';
import { useEffect } from 'react';
const handleTokenGenerated = (payload) => {
const { token } = payload;
// 将 token 发送到后端
sendTokenToServer(token);
};
useEffect(() => {
on(Events.PushNotification.TokenGenerated, handleTokenGenerated);
return () => {
off(Events.PushNotification.TokenGenerated, handleTokenGenerated);
};
}, []);权限流程
- 用户点击"启用通知"
- 应用调用
enroll() - 系统显示权限对话框
- 如果授权,FCM 生成 token
TokenGenerated事件触发并携带 token- 应用将 token 发送到后端
- 后端为用户存储 token
- 服务器现在可以向此设备发送通知
最佳实践
- 在适当的时机请求权限(不要在应用启动时立即请求)
- 向用户解释通知的价值
- 优雅地处理权限拒绝 (推送通知)