laravel中使用極光推送消息


最近需要使用極光推送往客戶端推消息,所以這里記錄下使用過程。

極光推送的服務端文檔:

https://docs.jiguang.cn/jpush/server/push/server_overview/

極光推送服務端PHP代碼:

https://github.com/jpush/jpush-api-php-client

在laravel項目下安裝極光推送

composer require jpush/jpush

我們在config目錄下創建一個jpush.php文件,用於獲取key和secret

<?php

return [
    'app_key' => env('JPUSH_APP_KEY', ''),
    'master_secret' => env('JPUSH_MASTER_SECRET', ''),
    'apns_production' => env('JPUSH_APNS_PRODUCTION', true),
];  

然后在 .env 文件中配置相應參數

JPUSH_APP_KEY=
JPUSH_MASTER_SECRET=
JPUSH_APNS_PRODUCTION=true

然后我們在app目錄下,創建一個 Services目錄,並創建JPushService.php

<?php

namespace App\Services;

use JPush\Client as JPush;
use Log;

class JPushService
{
    protected static $client = null;

    //推送類型
    const PUSH_TYPE_ALL = 1;
    const PUSH_TYPE_TAG = 2;
    const PUSH_TYPE_ALIAS = 3;
    const PUSH_TYPE_REG_ID = 4;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    /**
     * 獲取實例
     */
    public static function getInstance()
    {
        if (!self::$client) {
            self::$client = new JPush(config('jpush.app_key'), config('jpush.master_secret'), null);
        }
        return self::$client;
    }

    /**
     * 給android或ios推送消息
     */
    public static function pushNotify($params)
    {
        //推送平台
        $platform = $params['platform'] ?? 'all';
        //推送標題
        $title = $params['title'] ?? '';
        //推送內容
        $content = $params['content'] ?? '';
        //通知欄樣式ID
        $builder_id = $params['builder_id'] ?? 0;
        //附加字段
        $extras = $params['extras'] ?? '';
        //推送類型
        $type = $params['type'] ?? '';

        //推送目標(注冊ID)
        $reg_id = $params['reg_id'] ?? '';
        //推送目標(標簽)
        $tag = $params['tag'] ?? '';
        //推送目標(別名)
        $alias = $params['alias'] ?? '';

        try {
            $push = self::getInstance()->push();

            //設置平台
            $push->setPlatform($platform);

            switch ($type) {
                case self::PUSH_TYPE_ALL:
                    $push->addAllAudience();
                    break;
                case self::PUSH_TYPE_TAG:
                    $push->addTag($tag);
                    break;
                case self::PUSH_TYPE_ALIAS:
                    $push->addAlias($alias);
                    break;
                case self::PUSH_TYPE_REG_ID:
                    $push->addRegistrationId($reg_id);
                    break;
            }

            $push->androidNotification($content, [
                'title' => $title,
                'builder_id' => $builder_id,
                'extras' => $extras,
            ])->iosNotification($content, [
                'sound' => 'sound',
                'badge' => '+1',
                'extras' => $extras
            ])->options([
                'apns_production' => config('jpush.apns_production', true),
                //表示離線消息保留時長(秒)
                'time_to_live' => 86400,
            ]);

            $response = $push->send();

            if ($response['http_code'] != 200) {
                Log::channel('jpush')->error(json_encode($response, JSON_UNESCAPED_UNICODE));
            } 

            return $response;
        } catch (\Throwable $e) {
            Log::channel('jpush')->error(json_encode([
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'message' => $e->getMessage(),
                'params' => $params,
            ], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 獲取指定設備的別名和標簽
     */
    public static function getDevices($reg_id)
    {
        $response = self::getInstance()->device()->getDevices($reg_id);

        if ($response['http_code'] == 200) {
            return $response['body'];
        }

        return [];
    }

    /**
     * 給指定設備添加標簽
     */
    public static function addTags($reg_id, $tags = [])
    {
        $response = self::getInstance()->device()->addTags($reg_id, $tags);

        if ($response['http_code'] == 200) {
            return true;
        }

        return false;
    }

    /**
     * 清空指定設備的標簽
     */
    public static function clearTags($reg_id)
    {
        $response = self::getInstance()->device()->clearTags($reg_id);

        if ($response['http_code'] == 200) {
            return true;
        }

        return false;
    }

    /**
     * 清空指定設備的標簽
     */
    public static function removeTags($reg_id, $tags = [])
    {
        $response = self::getInstance()->device()->removeTags($reg_id, $tags);

        if ($response['http_code'] == 200) {
            return true;
        }

        return false;
    }

    /**
     * 更新指定設備的別名
     */
    public static function updateAlias($reg_id, $alias)
    {
        $response = self::getInstance()->device()->updateAlias($reg_id, $alias);

        if ($response['http_code'] == 200) {
            return true;
        }

        return false;
    }
}

創建完后,我們就可以在項目中調用 JPushService::pushNotify() 來推消息了。

JPushService::pushNotify([
    //標題
    'title' => '測試',
    //內容
    'content' => '測試',
    //設備標識,跟設備相關
    'reg_id' => 'xxxxxxxxxxx',
    //擴展字段
    'extras' => [
        'key' => 'value',
    ],
    //推送類型
    'type' => JPushService::PUSH_TYPE_REG_ID,
]);

reg_id是前端安卓或IOS獲取到后,傳給PHP后端,然后跟用戶關聯,存起來。

注意,reg_id是跟設備相關的,同一個設備上的APP,當不同用戶登陸時,reg_id是一樣的,這樣會導致一個問題。

A用戶登APP后,又切換到B用戶,那B用戶會收到發送給A用戶的消息,這會造成消息錯亂。

解決方法:

通過別名來發送消息,因為一個設備只能綁定一個別名,當A用戶登陸時,把 reg_id 綁定到別名 user_a,切換用戶或退出時,就把別名置空。

然后B用戶登陸,就把 reg_id 綁定到 user_b 上。推消息時,就通過別名來推送消息。

綁定別名(推薦使用用戶ID來區分不同的別名):

JPushService::updateAlias($user->jpush_reg_id, 'user_id_' . $user->id);

置空別名:

JPushService::updateAlias($user->jpush_reg_id, '');

通過別名發送:

JPushService::pushNotify([
    'title' => '測試',
    'content' => '測試',
    'alias' => 'user_id_' . $message->receive_id,
    'extras' => $extras,
    'type' => JPushService::PUSH_TYPE_ALIAS,
]);

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM