bilalmardini/firebase-notification

用于发送 Firebase 通知的软件包

v1.0.0 2024-08-28 09:02 UTC

This package is not auto-updated.

Last update: 2024-09-26 07:44:31 UTC


README

Package Image

Packagist Downloads Latest Version

概述

Laravel Firebase 通知 是一个强大的软件包,用于将 Firebase 云消息 (FCM) 集成到 Laravel 应用程序中。它提供了一个直观的界面,用于向用户发送推送通知,针对个人、群体或主题进行广播通知。

特性

  • 推送通知:通过 Firebase 云消息 (FCM) 发送通知。
  • 多语言支持:易于本地化(例如,英语、阿拉伯语)。
  • 基于主题的通知:向订阅者广播消息。
  • 针对特定用户的通知:发送个性化消息。
  • 自定义有效载荷:包含图标、标题、正文和附加数据。
  • 富媒体支持:具有深链接的可定制的消息结构。
  • 安全交付:使用服务账户密钥通过 Firebase 进行身份验证。

要求

  • PHP:7.4 或更高版本
  • Laravel:8.x 或更高版本
  • Firebase:一个启用了云消息的项目
  • 凭证:Firebase 服务账户凭证

安装

通过 Composer 安装此软件包

composer require bilalmardini/firebase-notification

如果您不使用 Laravel 软件包自动发现,请将服务提供者在 config/app.php 中添加

'providers' => [
    // Other Service Providers
    BilalMardini\FirebaseNotification\Providers\FirebaseNotificationServiceProvider::class,
],

发布配置文件以设置您的 Firebase 凭证

php artisan vendor:publish --provider="BilalMardini\FirebaseNotification\Providers\FirebaseNotificationServiceProvider"

配置

在发布的配置文件中设置您的 Firebase 凭证(config/firebase.php

return [
    'credentials_file_path' => base_path('firebase.json'),
    'project_id' => 'your-firebase-project-id'
];

用法

发送通知

1. 基于主题的通知(全局新闻更新)

向所有订阅特定主题的用户发送通知

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use BilalMardini\FirebaseNotification\Facades\FirebaseNotification;

class NewsNotificationController extends Controller
{
    /**
     * Send a global news update to users subscribed to 'global-news'.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendGlobalNewsUpdate()
    {
        $result = FirebaseNotification::setTitle('Breaking News', 'أخبار عاجلة')
                     ->setBody('A major event just happened. Click to read more.', 'حدث كبير وقع للتو. انقر لقراءة المزيد.')
                     ->setIcon('https://news-website.com/news-icon.png') 
                     ->setTopic('global-news')  // Target 'global-news' topic
                     ->setData(['news_id' => 5678, 'category' => 'breaking-news'])
                     ->push();

        return $result
            ? response()->json(['message' => 'News notification sent successfully.'], 200)
            : response()->json(['message' => 'Failed to send news notification.'], 500);
    }
}

要点

  • 向订阅 global-news 主题的用户发送通知。
  • 包括自定义数据,如 news_idcategory

2. 针对特定用户的通知(订单状态)

通知特定用户他们的订单状态

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use BilalMardini\FirebaseNotification\Facades\FirebaseNotification;

class PromotionNotificationController extends Controller
{
    /**
     * Notify users about a new promotional offer.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendPromotionNotification()
    {
        $eligibleUsers = User::whereNotNull('device_token')
                            ->where('is_eligible_for_promo', true)
                            ->get();

        $result = FirebaseNotification::setTitle('Exclusive Promotion Just for You!', 'عرض ترويجي حصري لك!')
                     ->setBody('Unlock your special offer now. Limited time only!', 'افتح عرضك الخاص الآن. لفترة محدودة فقط!')
                     ->setIcon('https://yourstore.com/promo-icon.png') 
                     ->setUsers($eligibleUsers)  // Target specific users
                     ->setData(['promo_code' => 'PROMO2024', 'discount' => '20%'])
                     ->push();

        return $result
            ? response()->json(['message' => 'Promotion notification sent successfully.'], 200)
            : response()->json(['message' => 'Failed to send promotion notification.'], 500);
    }
}

要点

  • 向有资格获得促销活动(is_eligible_for_promo)的用户发送通知。
  • 包括自定义数据,如 promo_codediscount

模型

通知模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    use HasFactory;

    protected $fillable = [
        'title_en',
        'title_ar',
        'description_en',
        'description_ar',
        'is_general',
    ];

    public function userNotifications()
    {
        return $this->hasMany(UserNotification::class);
    }
}

用户通知模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserNotification extends Model
{
    use HasFactory;

    protected $fillable = [
        'notification_id',
        'user_id',
    ];

    public function notification()
    {
        return $this->belongsTo(Notification::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

向用户表添加 device_token

创建迁移以添加 device_token

php artisan make:migration add_device_token_to_users_table --table=users

更新迁移文件

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddDeviceTokenToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('device_token')->nullable()->after('email'); // Adjust 'after' column if needed
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('device_token');
        });
    }
}

运行迁移

php artisan migrate

确保在 User 模型中将 device_token 添加到 $fillable 属性中

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;

    protected $fillable = [
        // other fillable attributes
        'device_token',
    ];
}

联系

如果您有任何问题或需要进一步的帮助,您可以通过以下渠道联系

  • GitHub 问题:通过 提交问题 报告错误、提出功能请求或提出一般性问题。
  • GitHub 讨论:与社区互动并在我们的 讨论 中提问。
  • 电子邮件:对于直接询问,您可以通过 bilal.mardini1999@gmail.com 联系我们。

我们感谢您对我们项目的兴趣和贡献。感谢您成为 Laravel Firebase 通知社区的一员!