承接 humamkerdiah/fcm-notifications 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

humamkerdiah/fcm-notifications

Composer 安装命令:

composer require humamkerdiah/fcm-notifications

包简介

A Laravel package for sending Firebase Cloud Messaging (FCM) push notifications with support for both legacy API and FCM HTTP v1 API. Features OAuth 2.0 authentication, batch processing, and comprehensive error handling.

README 文档

README

A Laravel package for sending Firebase Cloud Messaging (FCM) notifications with support for both legacy API and the new FCM HTTP v1 API.

About

Laravel FCM Notifications is a powerful package for integrating Firebase Cloud Messaging (FCM) into your Laravel application. It supports both the legacy FCM API and the new FCM HTTP v1 API (recommended). Send push notifications to individual users or groups, manage topics, and more with simple configuration and seamless integration.

Table of Contents

Features

  • FCM HTTP v1 API Support - OAuth 2.0 authentication with service account keys
  • Legacy API Support - Backwards compatibility with server key authentication
  • ✅ Easy integration with Laravel notifications
  • ✅ Send notifications to single or multiple users
  • ✅ Topic-based messaging for targeted notifications
  • ✅ Batch processing for multiple device tokens
  • ✅ Comprehensive error handling and retry mechanisms
  • ✅ Support for both mobile and web push notifications
  • ✅ Laravel 8, 9, 10, and 11 compatibility

Installation

You can install the package via composer:

composer require humamkerdiah/fcm-notifications

Configuration

After installation, publish the config file:

php artisan vendor:publish --tag=fcm-config

This will create a config/fcm.php file where you can configure your FCM settings.

FCM HTTP v1 API (Recommended)

The v1 API uses OAuth 2.0 authentication and is Google's recommended approach for FCM.

Setup for v1 API

  1. Get Service Account Key:

    • Go to Firebase Console
    • Select your project → Project Settings → Service Accounts
    • Click "Generate new private key" and download the JSON file
  2. Update your .env file:

FCM_API_VERSION=v1
FCM_PROJECT_ID=your-firebase-project-id
FCM_SERVICE_ACCOUNT_KEY_PATH=/path/to/your/service-account-key.json

Alternatively, you can use the GOOGLE_APPLICATION_CREDENTIALS environment variable:

GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json
FCM_API_VERSION=v1
FCM_PROJECT_ID=your-firebase-project-id

Legacy API Support

The package still supports the legacy server key authentication for backwards compatibility.

Setup for Legacy API

Update your .env file:

FCM_API_VERSION=legacy
FCM_SERVER_KEY=your-server-key-here

Usage

Using Laravel Notifications

There are two ways to use FCM notifications in your Laravel application:

1. Using the FCM Channel Class

use Humamkerdiah\FcmNotifications\Channels\FcmChannel;

class NewMessage extends Notification
{
    public function via($notifiable)
    {
        return [FcmChannel::class];
    }

    public function toFcm($notifiable)
    {
        return (new FcmMessage())
            ->setTitle('New Message')
            ->setBody('You have a new message!')
            ->setData([
                'message_id' => '123',
                'url' => '/messages/123'
            ]);
    }
}

2. Using the Channel Name

class NewMessage extends Notification
{
    public function via($notifiable)
    {
        return ['fcm'];  // Use the registered channel name
    }

    public function toFcm($notifiable)
    {
        return (new FcmMessage())
            // ... same as above
    }
}

Setting Up Your Model

Make your model use FCM notifications by implementing the routeNotificationForFcm method:

use Illuminate\Notifications\Notifiable;

class User extends Model
{
    use Notifiable;

    public function routeNotificationForFcm($notification)
    {
        return $this->device_token; // Return a single token
        // Or return multiple tokens:
        // return $this->device_tokens->pluck('token')->toArray();
    }
}

Sending Notifications

// To a single user
$user->notify(new NewMessage());

// To multiple users
Notification::send($users, new NewMessage());

// Using the facade for direct FCM operations
use Humamkerdiah\FcmNotifications\Facades\FcmNotification;

// Send to specific devices
$message = new FcmMessage();
$message->setTitle('Hello')
       ->setBody('This is a test notification')
       ->setData(['key' => 'value'])
       ->setTokens(['device-token-1', 'device-token-2']);

FcmNotification::sendToDevices($message);

// Or send to a topic
$message->setTopic('news');
FcmNotification::sendToTopic($message);

Topic Management

// Subscribe tokens to a topic
FcmNotification::subscribeToTopic('news', ['device-token-1', 'device-token-2']);

// Unsubscribe tokens from a topic
FcmNotification::unsubscribeFromTopic('news', ['device-token-1', 'device-token-2']);

Error Handling

The package provides comprehensive error handling for both API versions:

v1 API Response Format

try {
    $result = FcmNotification::sendToDevices($message);
    
    echo "Success count: " . $result['success_count'];
    echo "Failure count: " . $result['failure_count'];
    
    // Handle successful sends
    foreach ($result['results'] as $result) {
        echo "Token: " . $result['token'] . " - Message ID: " . $result['message_id'];
    }
    
    // Handle failures
    foreach ($result['errors'] as $error) {
        echo "Failed token: " . $error['token'] . " - Error: " . $error['error'];
    }
    
} catch (\Humamkerdiah\FcmNotifications\Exceptions\FcmNotificationException $e) {
    Log::error('FCM Notification failed: ' . $e->getMessage());
}

Legacy API Response Format

try {
    $result = FcmNotification::sendToDevices($message);
    
    echo "Success: " . $result['success'];
    echo "Failure: " . $result['failure'];
    echo "Canonical IDs: " . $result['canonical_ids'];
    
} catch (\Exception $e) {
    Log::error('FCM Notification failed: ' . $e->getMessage());
}

Migration Guide

If you're upgrading from the legacy API to v1 API, see our Migration Guide for detailed instructions.

Testing

When testing your application, you can mock the FCM notifications:

use Mockery;
use Humamkerdiah\FcmNotifications\Contracts\FcmNotificationSender;

public function test_it_sends_fcm_notification()
{
    $mock = Mockery::mock(FcmNotificationSender::class);
    
    // For v1 API
    $mock->shouldReceive('sendToDevices')->once()->andReturn([
        'success_count' => 1,
        'failure_count' => 0,
        'results' => [['token' => 'test-token', 'success' => true, 'message_id' => 'test-message-id']],
        'errors' => []
    ]);
    
    $this->app->instance(FcmNotificationSender::class, $mock);

    // Your test code here
}

Requirements

  • PHP 7.4 or higher
  • Laravel 8.0 or higher
  • GuzzleHTTP 7.0 or higher
  • Google Auth Library (for v1 API)

Security Considerations

  • Store service account keys securely and never commit them to version control
  • Use environment variables for all sensitive configuration
  • Consider using Google Cloud Secret Manager in production
  • Regularly rotate your service account keys

License

The MIT License (MIT). Please see License File for more information.

humamkerdiah/fcm-notifications 适用场景与选型建议

humamkerdiah/fcm-notifications 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 12 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 04 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「notifications」 「oauth 2.0」 「laravel」 「push」 「push notifications」 「firebase」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 humamkerdiah/fcm-notifications 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 humamkerdiah/fcm-notifications 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-04-20