sendfirebase/notificationphp
Composer 安装命令:
composer require sendfirebase/notificationphp
包简介
A package for sending Firebase notifications in Laravel.
README 文档
README
A comprehensive solution for sending Firebase Cloud Messaging (FCM) notifications from a Laravel backend to Flutter applications.
Table of Contents
Laravel Integration
This section explains how to set up and use the Laravel package to send notifications.
Laravel Prerequisites
- Laravel Version: 8+
- Firebase Project: Create one in the Firebase Console
- Service Account Key: Download the JSON file from your Firebase project settings
Laravel Installation
-
Install via Composer:
composer require sendfirebase/notificationphp
-
Publish the Configuration:
php artisan vendor:publish --provider="SendFireBaseNotificationPHP\Providers\FireBaseNotificationServiceProvider" --tag="config"
-
Configure Your Environment:
Add these lines to your
.envfile:FIREBASE_PROJECT_ID=your-project-id FIREBASE_API_VERSION=v1
-
Store Firebase Credentials:
Create a directory and move your service account JSON file:
mkdir -p storage/app/firebase mv path/to/your-service-account.json storage/app/firebase/firebase_credentials.json
Laravel Configuration
Ensure your config/firebase.php file contains:
return [ 'project_id' => env('FIREBASE_PROJECT_ID'), 'version' => env('FIREBASE_API_VERSION', 'v1'), 'credentials_file' => storage_path('app/firebase/firebase_credentials.json'), ];
Laravel Usage Examples
1. Send a Notification to a Single User:
use App\Models\User; public function notifyUser(Request $request) { $firebaseService = app(\SendFireBaseNotificationPHP\Services\FirebaseNotificationService::class); $response = $firebaseService->sendNotificationToSingle( new User(), // User model instance $request->user_id, // Target user ID "New Message", // Notification title "You have a new notification!", // Notification body 'fcm_token' // Column name where FCM token is stored ); return response()->json($response); }
2. Broadcast a Notification to All Users:
$firebaseService->sendNotificationToAll( new User(), // User model instance "Global Alert", // Notification title "Important system update!", // Notification body 'fcm_token' // Column name for FCM token );
3. Send a Notification to a Topic:
$firebaseService->sendNotificationToTopic( "all_users", // Topic name "Topic Update", // Notification title "New content available!" // Notification body );
4. Send a Notification with Custom Data (and optional Image):
$firebaseService->sendFirebaseWithData( $deviceToken, // Target device token "New Message", // Notification title "You received a message!", // Notification body ['custom_key' => 'custom_val'], // Custom data payload (optional array) "https://example.com/image.jpg" // Optional image URL (omit or null for none image) );
Laravel Troubleshooting
-
Missing Credentials:
Verify that the service account JSON is located instorage/app/firebaseand that your Firebase project ID in the.envfile matches your Firebase credentials. -
General Issues:
Check your Laravel logs for errors and review the configuration inconfig/firebase.php.
Flutter Integration
This section details the steps for setting up your Flutter application to receive and handle Firebase notifications.
Flutter Prerequisites
- Flutter Version: 3.0+
- Firebase Project: Ensure your Firebase project is configured for both Android and iOS
- Platform-Specific Setup: For iOS, follow the Firebase iOS Setup
Flutter Setup & Dependencies
-
Add Dependencies:
Add the following dependencies to your
pubspec.yaml:dependencies: firebase_messaging: ^15.2.1 flutter_local_notifications: ^18.0.1
-
Basic App Initialization:
In your
main.dart, initialize notifications before running the app:void main() async { WidgetsFlutterBinding.ensureInitialized(); await FbNotifications.initNotifications(); runApp(MyApp()); }
Flutter Notification Initialization and Handling
Implement a mixin to centralize notification setup and handling:
mixin FbNotifications on State<MyApp> { static late AndroidNotificationChannel channel; static late FlutterLocalNotificationsPlugin localNotificationsPlugin; // Background Handler static Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async { print("Handling background message: ${message.messageId}"); } // Initialization: Set up channels and permissions static Future<void> initNotifications() async { FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler); // Android Channel Setup channel = const AndroidNotificationChannel( 'high_importance_channel', 'Important Notifications', importance: Importance.high, playSound: true, ); localNotificationsPlugin = FlutterLocalNotificationsPlugin(); await localNotificationsPlugin .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); // iOS Notification Presentation Options await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( alert: true, badge: true, sound: true, ); } // Request Notification Permissions (especially for iOS) Future<void> requestNotificationPermissions() async { final settings = await FirebaseMessaging.instance.requestPermission( alert: true, badge: true, sound: true, ); if (settings.authorizationStatus == AuthorizationStatus.authorized) { print('Notifications granted'); } } // Foreground Notification Handling for Android void initializeForegroundNotificationForAndroid() { FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = notification?.android; if (notification != null && android != null) { localNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( channel.id, channel.name, icon: '@mipmap/ic_launcher', ), ), ); } }); } }
-
Platform-Specific Configurations:
-
Android:
Update yourAndroidManifest.xmlto include:<application ...> <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="high_importance_channel"/> </application>
-
iOS:
Follow the official Firebase iOS setup guide and ensure push notifications are enabled in Xcode.
-
Flutter Usage Examples
Subscribing to a Topic:
FirebaseMessaging.instance.subscribeToTopic("all_users");
Handling Background Messages:
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
Handling Notification Taps (when the app is opened via a notification):
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { Navigator.pushNamed(context, '/message'); });
Listening for Token Refresh:
FirebaseMessaging.instance.onTokenRefresh.listen((newToken) { // Update your server with the new token });
Flutter Troubleshooting
-
iOS Notifications Not Showing:
Make sure you have completed the iOS setup in Xcode, requested user permissions, and enabled push notifications in your Apple Developer account. -
Android Notifications Silent:
Confirm that the notification channel’s importance is set to high, and verify the metadata inAndroidManifest.xml. -
Token Issues:
Ensure that you handle token refresh correctly to keep the server updated with the latest token.
Contributing
We welcome your contributions to improve the project for both Laravel and Flutter users!
-
Report Issues:
Use GitHub Issues to report bugs or request new features. -
Development Setup:
git clone https://github.com/YacoubAl-hardari/firebasenotificationphp.git cd firebasenotificationphp composer install -
Testing: Create tests in the
tests/directory and run:php artisan test -
Coding Standards:
Follow the PSR-12 coding style, use PHPStan (level 6), and include PHPDoc comments. -
Pull Requests:
Fork the repository, create feature branches, and submit a PR with a detailed description of your changes.
sendfirebase/notificationphp 适用场景与选型建议
sendfirebase/notificationphp 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 266 次下载、GitHub Stars 达 10, 最近一次更新时间为 2025 年 01 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「package」 「notifications」 「laravel」 「push notifications」 「firebase」 「firebase notifications」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 sendfirebase/notificationphp 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 sendfirebase/notificationphp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 sendfirebase/notificationphp 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A Laravel Nova package that adds a notification feed in your Nova app.
Simple ASCII output of array data
Captures outgoing SMS notifications
Alfabank REST API integration
Laravel package to send notifications when some exceptions are thrown.
统计信息
- 总下载量: 266
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 10
- 点击次数: 9
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-01-29