duotek/unisender-go-notification-channel

Notification channel for Laravel. Integration with the Unisender Go service (https://go.unisender.ru)

0.0.5 2023-12-07 13:57 UTC

This package is auto-updated.

Last update: 2024-05-07 19:34:49 UTC


README

Общая информация

Документация Unisender Go. WebAPI v1.52:https://godocs.unisender.ru/web-api-ref#web-api

При использовании локально, письма доходят довольно долго.

По умолчанию from_email берется из config('mail.from.address')
По умолчанию from_name берется из config('mail.from.name')

Установка

  1. composer require duotek/unisender-go-notification-channel
  2. В config/services.php добавляем наш сервис:
    $baseUrl = 'https://go1.unisender.ru/ru/transactional/api/v1/';
    

// либо // $baseUrl = 'https://go2.unisender.ru/ru/transactional/api/v1/';

return [

'unisender_go' => [
    'api_key' => env('UNISENDER_GO_API_KEY'),
    'base_url' => env('UNISENDER_GO_BASE_URL', $baseUrl)
],

];


## <a name="howToUse">Как использовать?</a>

### <a name="base">Базовый способ</a>

Создаем уведомление

<?php

namespace App\Notifications;

use Duotek\UnisenderGoNotificationChannel\UnisenderGoChannel; use Duotek\UnisenderGoNotificationChannel\UnisenderGoMessage;; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification;

class TestNotification extends Notification {

use Queueable;

public function via($notifiable)
{
    return [UnisenderGoChannel::class];
}

public function toUnisenderGo($notifiable): UnisenderGoMessage
{
    /** Персональные подстановки, если необходимы */
    $substitutions = ['first_name' => $notifiable->first_name];
    
    /** Персональные метаданные, если необходимы */
    $metadata = ['meta1' => 'value1'];
    
    /** С шаблоном Unisender */
    return (new UnisenderGoMessage)
        ->addRecipient($notifiable->email, $substitutions, $metadata)
        ->setTemplateId('f0d762a2-9296-11ee-8abe-62f7586ed56e')
        ->setGlobalSubstitutions([
            'substitution1' => 'val1',    
            'substitution2' => 'val2',    
        ]);
        
    /** Без шаблона */
    return (new UnisenderGoMessage)
        ->addRecipient($notifiable->email, $substitutions, $metadata)
        ->setSubject('Подтверждите email')
        ->setBody('sample text', 'body');
        
    /** С шаблоном Laravel */
    return (new UnisenderGoMessage)
        ->addRecipient($notifiable->email, $substitutions, $metadata)
        ->addRecipient($notifiable->email)
        ->setBody(view('emails.email_confirmation', ['confirmLink' => $confirmLink]));
}

}


Вызываем уведомление

use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Auth; use App\Notifications\TestNotification; use App\Models\Customers\Customer;

/ @var $currentUser Customer / $currentUser = Auth::user();

Notification::send([$currentUser], new TestNotification);


### <a name="notify">Метод вызова уведомления `notify`</a>
Указываем трейт в модели

namespace App\Models\Customers;

use Illuminate\Notifications\Notifiable;

class Customer {

use Notifiable;

}

Вызываем уведомление

use Illuminate\Support\Facades\Auth; use App\Notifications\TestNotification; use App\Models\Customers\Customer;

/ @var $currentUser Customer / $currentUser = Auth::user(); $currentUser->notify(new TestNotification);


### <a name="withoutRecipient">Без указывания получателя в уведомлении</a>

Нужно добавить метод `routeNotificationForUnisenderGo` в модель,  
тогда не придется указывать получателей в письме

namespace App\Models\Customers;

class Customer {

/**
 * Отсюда будет забираться email получателя и прочие данные
 **/
public function routeNotificationForUnisenderGo($method, $parameters): array
{
    return [
        $this->email, 
        ['first_name' => $this->first_name], // Подстановки, если необходимо 
        ['external_id' => $this->external_id] // Метаданные, если необходимо
    ];
}

}


Создаем уведомление

<?php

namespace App\Notifications;

use Duotek\UnisenderGoNotificationChannel\UnisenderGoChannel; use Duotek\UnisenderGoNotificationChannel\UnisenderGoMessage;; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification;

class TestNotification extends Notification {

use Queueable;

public function via($notifiable)
{
    return [UnisenderGoChannel::class];
}

public function toUnisenderGo($notifiable): UnisenderGoMessage
{
    /** Не указываем получателей */
    return (new UnisenderGoMessage)
        ->setSubject('Подтверждите email')
        ->setBody('sample text', 'body');
}

}


### <a name="anonymous">Вызов анонимного уведомления</a>
Создание уведомления

<?php

namespace App\Notifications;

use Duotek\UnisenderGoNotificationChannel\UnisenderGoMessage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; use Duotek\UnisenderGoNotificationChannel\UnisenderGoChannel; use Illuminate\Notifications\AnonymousNotifiable;

class NewTicket extends Notification implements ShouldQueue {

use Queueable;

public function via($notifiable): array
{
    return [UnisenderGoChannel::class];
}

public function toUnisenderGo($notifiable): UnisenderGoMessage
{
    /* @var $notifiable AnonymousNotifiable */
    $email = $notifiable->routes[UnisenderGoChannel::class];

    return (new UnisenderGoMessage)
        ->addRecipient($email)
        ->setSubject("Новый тикет")
        ->setBody("Sample Text");
}

}

Вызов уведомление

use Duotek\UnisenderGoNotificationChannel\UnisenderGoChannel; use App\Notifications\InvoicePaid;

Notification::route(UnisenderGoChannel::class, config('common.manager_email'))->notify(new InvoicePaid);