sendfirebase/notificationphp 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

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.

Firebase-Laravel-Flutter

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

  1. Install via Composer:

    composer require sendfirebase/notificationphp
  2. Publish the Configuration:

    php artisan vendor:publish --provider="SendFireBaseNotificationPHP\Providers\FireBaseNotificationServiceProvider" --tag="config"
  3. Configure Your Environment:

    Add these lines to your .env file:

    FIREBASE_PROJECT_ID=your-project-id
    FIREBASE_API_VERSION=v1
  4. 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 in storage/app/firebase and that your Firebase project ID in the .env file matches your Firebase credentials.

  • General Issues:
    Check your Laravel logs for errors and review the configuration in config/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

  1. Add Dependencies:

    Add the following dependencies to your pubspec.yaml:

    dependencies:
      firebase_messaging: ^15.2.1
      flutter_local_notifications: ^18.0.1
  2. 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',
            ),
          ),
        );
      }
    });
  }
}
  1. Platform-Specific Configurations:

    • Android:
      Update your AndroidManifest.xml to 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 in AndroidManifest.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!

  1. Report Issues:
    Use GitHub Issues to report bugs or request new features.

  2. Development Setup:

    git clone https://github.com/YacoubAl-hardari/firebasenotificationphp.git
    cd firebasenotificationphp
    composer install
  3. Testing: Create tests in the tests/ directory and run:

    php artisan test
  4. Coding Standards:
    Follow the PSR-12 coding style, use PHPStan (level 6), and include PHPDoc comments.

  5. 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 我们能提供哪些服务?
定制开发 / 二次开发

基于 sendfirebase/notificationphp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 266
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 10
  • 点击次数: 9
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 10
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-29