快捷地整合極光推送(JPush)到 Laravel 專案中

medz發表於2019-01-30

file

需求概述

我們在開發 Laravel 應用專案地時候,經常會用到“推送”,Laravel 自帶了 Pusher 進行推送,但是國內環境大家都懂!所以這裡以整合極光推送為例。

依賴極光 SDK

我們進入 Laravel 專案執行 composer require jpush/jpush 進行依賴。

建立配置檔案

現在進入 Laravel 專案地 config/ 目錄,建立一個 jpush.php 配置檔案:

<?php

return [
    'production' => env('JPUSH_PRODUCTION', false), // 是否是正式環境
    'key' => env('JPUSH_APP_KEY', ''),                          // key
    'secret' => env('JPUSH_MASTER_SECRET', ''),       // master secret
    'log' => env('JPUSH_LOG_PATH', storage_path('logs/jpush.log')), // 日誌檔案路徑
];

建立 JPush 單例到容器

為了方便之後在驅動中獲取 JPush 例項,我們開啟 app/Providers/AppServiceProvider.php 檔案,在 register 方法中進行註冊單例:

use JPush\Client as JPushClient;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        // 註冊 JPush 客戶端單例
        $this->app->singleton(JPushClient::class, function ($app) {
            $options = [
                $app->config->get('jpush.key'),
                $app->config->get('jpush.secret'),
                $app->config->get('jpush.log'),
            ];

            return new JPushClient(...$options);
        });
    }
}

建立驅動

我們在 Laravel 應用的 app/Notifications/ 目錄下建立一個 Channels/ 目錄,然後在其目錄下建立一個 JPushChannel.php 檔案 app/Notifications/Channels/JPushChannel.php :

<?php

namespace App\Notifications\Channels;

use JPush\Client as JPushClient;
use Illuminate\Notifications\Notification;

class JPushChannel
{
    protected $client;

    /**
     * Create the notification channel instance.
     *
     * @param \JPush\Client $client
     */
    public function __construct(JPushClient $client)
    {
        $this->client = $client;
    }

    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     */
    public function send($notifiable, Notification $notification)
    {
        $push = $notification->toJPush($notifiable, $this->client->push());

        // 這裡是為了遮蔽極光伺服器沒有找到裝置等情況報錯,
        try {
            $push->send();
        } catch (\Throwable $th) {
            //throw $th;
        }
    }
}

註冊驅動

建立完成驅動後,我們需要註冊驅動。所以我們開啟 app/Providers/AppServiceProvider.php 檔案在 register 新增註冊程式碼:

use App\Notifications\Channels\JPushChannel;
use Illuminate\Notifications\ChannelManager;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        // 新增 JPush 驅動
        $this->app->extend(ChannelManager::class, function ($manager) {
            $manager->extend('jpush', function ($app) {
                return $app->make(JPushChannel::class);
            });
        });
    }
}

場景使用

我們開啟 app/Notifications/ 目錄下需要走極光推送的檔案,錄入我這裡以「評論為例」:

use JPush\PushPayload;

class CommentByMeow extends Notification
{
    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database', 'jpush']; // 表示除了儲存到資料庫外,進行極光推送,`jpush` 就是註冊驅動的時候的 key。
    }

    // 只需要按需設定好 JPush 的 payload 並返回回去就好了了
    public function toJPush($notifiable, PushPayload $payload): PushPayload
    {
        return $payload
            ->setPlatform('all')
            // ... 參考 https://github.com/jpush/jpush-api-php-client/blob/master/doc/api.md#push-api
        ;
    }
}

以我自己使用的為例:

file

其他

宣告:我不是在做 JPush 廣告,只是因為自己產品在使用,特意分享給大家!本人和極光推送沒有任何關係。

Seven 的程式碼太渣,歡迎關注我的新擴充包 medz/cors 解決 PHP 專案程式設定跨域需求。

相關文章