본문으로 건너뛰기
Notifications
Communication
Laravel Go 0.x · 한국어 문서https://laravel.com/go/docs/0.x/notifications

Notifications

Introduction​

고객이 청구서를 결제하면 이메일과 문자 메시지를 보내고 팀의 Slack 채널에 결제 내역을 게시할 수 있습니다. 알림은 이 이벤트를 한 번 정의하고 채널별 메시지를 구성하며, Laravel은 지정한 모든 사용자나 팀에 메시지를 전달합니다.

Laravel은 이메일, SMS, Slack과 Discord 같은 package channels로 알림을 전달합니다. 이메일은 mail, 문자 메시지는 SMS를 사용합니다. 두 채널은 해당 가이드의 설정과 큐를 사용하므로 사용할 채널을 먼저 설정하세요.

알림은 짧고 정보를 전달하는 내용으로 작성하세요. 주문 영수증처럼 자체 레이아웃과 첨부 파일이 있는 이메일 한 통을 보내려면 mailable을 직접 전송하세요.

Writing notifications​

알림은 메시지에 필요한 데이터를 보관하는 타입입니다. Messages 메서드는 notification.Messages를 반환합니다. 이 값은 Mail 필드에 이메일을, Channels 필드에 문자 메시지 등 나머지 모든 채널의 메시지를 담습니다. 알림은 app/notifications 같은 패키지에 각각 별도 파일로 보관할 수 있습니다.

예를 들어 애플리케이션에 Invoice model과 InvoicePaidEmail mailable이 있다고 가정하겠습니다. 다음 알림은 청구서가 결제되면 사용자에게 알립니다.

// notifications/invoice_paid.go
package notifications

import (
"fmt"

"go.laravel.com/notification"
"go.laravel.com/sms"

"app/mails"
"app/models"
)

type InvoicePaid struct {
Invoice models.Invoice
}

func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
return notification.Messages{
Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
Channels: []any{
sms.Text{Body: fmt.Sprintf("Invoice #%d is paid. Thanks!", n.Invoice.ID)},
},
}, nil
}

메서드의 인수는 메시지를 받는 알림 수신 대상이며, 여기서는 *models.User입니다. 이 타입이 알림을 보낼 수 있는 대상을 결정합니다. 같은 소식을 팀에도 보내려면 Slack example처럼 Messages 메서드가 *models.Team을 받는 두 번째 알림 타입을 작성하세요.

Laravel은 알림을 보내는 핸들러나 잡에서 실제 전송 전에 수신 대상마다 Messages를 한 번 호출합니다. Messages는 ctx를 받지 않으므로 데이터베이스를 조회하거나 라우트 URL을 만들 수 없습니다. 알림을 보내기 전에 필요한 관련 모델을 불러오고 URL을 만든 다음 각 값을 알림의 필드로 전달하세요. Messages가 오류를 반환하면 어떤 메시지도 나가기 전에 전송을 중단합니다.

Mail messages​

Mail은 수신 대상 하나가 받을 이메일을 담습니다. 직접 만든 mailable이나 메일러블이기도 한 mail.Message를 사용할 수 있습니다. InvoicePaidEmail은 Name과 InvoiceID로 resources/views/mails/invoice-paid.html을 렌더링하는 메일러블입니다.

// mails/invoice_paid.go
package mails

import (
"fmt"

"go.laravel.com/mail"
)

type InvoicePaidEmail struct {
Name string
InvoiceID int64
}

func (m InvoicePaidEmail) Build() mail.Message {
return mail.Message{
Subject: fmt.Sprintf("Invoice #%d is paid", m.InvoiceID),
View: "mails.invoice-paid",
Data: m,
}
}

Laravel은 이메일 수신자를 알림 수신 대상의 mail address로 자동 설정하므로 메일러블에서는 수신자를 지정하지 않습니다. 뷰, 제목, 첨부 파일에 대한 자세한 내용은 mail guide를 확인하세요.

SMS messages​

문자 메시지는 알림의 Channels에 넣는 sms.Text입니다. Laravel은 SMS_FROM 번호에서 Body를 보냅니다. 다른 번호에서 보내려면 문자 메시지의 From을 설정하세요.

sms.Text{Body: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID), From: "+15555550199"}

Slack messages​

Slack 메시지는 알림의 Channels에 넣는 slack.Message이며 섹션과 버튼 같은 블록을 포함합니다. Slack 메시지는 보통 사용자 한 명이 아닌 팀 채널로 보내므로 Messages 메서드가 팀을 받는 알림에 둡니다. 예를 들어 애플리케이션에 slack_channel_id 컬럼이 있는 Team 모델이 있다고 가정하겠습니다. Messages는 라우트 URL을 만들 수 없으므로 핸들러에서 urls.Route(r, "invoices.show", "invoice", invoice.ID)로 청구서 URL을 만들어 전달합니다.

// notifications/team_invoice_paid.go
package notifications

import (
"go.laravel.com/notification"
"go.laravel.com/slack"

"app/models"
)

type TeamInvoicePaid struct {
Invoice models.Invoice
URL string
}

func (n TeamInvoicePaid) Messages(team *models.Team) (notification.Messages, error) {
amount := slack.Markdownf("$%.2f", float64(n.Invoice.Total)/100)

return notification.Messages{
Channels: []any{slack.Message{
Text: slack.Markdownf("Invoice #%d is paid", n.Invoice.ID),
Blocks: []slack.Block{
slack.Section{
Text: "Invoice paid.",
Fields: []slack.Field{{Label: "Amount", Value: amount}},
},
slack.Actions{Elements: []slack.Element{
slack.Button{Label: "View invoice", URL: n.URL},
}},
},
}},
}, nil
}

메시지는 팀의 Slack route로 전송됩니다. Slack 앱 설정과 버튼 클릭 처리는 Slack guide를 참고하세요.

Notifiables​

알림 수신 대상은 *models.User나 *models.Team처럼 알림을 받는 타입입니다. 지원하는 각 채널에 대해 이메일 주소, 전화번호 또는 Slack route를 반환하는 MailAddress, SMSNumber, SlackRoute 메서드를 갖습니다. users 테이블에는 E.164 form의 번호를 담거나 비어 있는 phone 컬럼이 있고, teams 테이블에는 slack_channel_id 컬럼이 있다고 가정하겠습니다.

// models/user.go
func (u User) MailAddress() mail.Address {
return mail.Address{Name: u.Name, Email: u.Email}
}

func (u User) SMSNumber() string {
return u.Phone
}

// models/team.go
func (t Team) SlackRoute() slack.Route {
return slack.Route{Channel: t.SlackChannelID}
}

이 메서드 중 하나가 빈 전화번호 같은 제로 값을 반환하면 해당 수신 대상의 그 채널을 오류 없이 건너뜁니다. 전화번호 없이 가입한 사용자도 이메일은 받습니다.

알림 수신 대상에는 알림이 구성하는 모든 채널에 대응하는 메서드가 필요합니다. User에 SMSNumber 메서드가 없다면 문자 메시지를 구성하는 InvoicePaid를 보낼 때 패닉이 발생하고 구현해야 할 인터페이스를 알려줍니다. 이 경우에는 sms.Notifiable입니다.

Sending notifications​

알림을 보내려면 요청, 알림, 수신 대상들을 notification.Queue 또는 notification.Send에 전달하세요. 대부분의 핸들러에서는 HTTP 응답이 외부 프로바이더를 기다리지 않도록 알림을 queue에 등록해야 합니다. 다음 핸들러는 청구서를 결제하고 고객에게 알립니다.

// handlers/invoices/pay.go
package invoices

import (
"go.laravel.com/model"
"go.laravel.com/notification"
"go.laravel.com/web"

"app/models"
"app/notifications"
)

func Pay(r *web.Request) *web.Response {
invoice, err := model.FromRoute[models.Invoice](r, "invoice")
if err != nil {
return web.Fail(err)
}
customer, err := model.Find[models.User](r, invoice.UserID)
if err != nil {
return web.Fail(err)
}

// Charge the invoice...

if err := notification.Queue(r, notifications.InvoicePaid{Invoice: invoice}, &customer); err != nil {
return web.Fail(err)
}

return web.Back()
}

Send는 메시지를 즉시 전달하고 각 프로바이더가 수락할 때까지 기다립니다. command, 잡, 리스너에서는 r 대신 받은 ctx를 전달합니다. 두 함수는 수신 대상을 개수 제한 없이 받습니다. 쿼리로 얻은 []models.Team 같은 모델 슬라이스가 있다면 notification.QueueAll 또는 notification.SendAll에 직접 전달하세요.

err := notification.SendAll(ctx, notifications.WeeklySummary{Report: report}, teams)

Queueing notifications​

Queue는 queue worker에서 메시지를 보냅니다. 워커는 프로바이더에 실패가 발생하면 각 메시지를 재시도하므로 알림을 큐에 등록하기 전에 워커를 시작하세요. notification.Delay, notification.OnQueue, notification.OnConnection 중 하나로 시작하고 Queue 전에 나머지를 연결하면 메시지를 지연하거나 잡을 보낼 큐를 선택할 수 있습니다.

err := notification.OnQueue("notifications").
Delay(5*time.Minute).
Queue(r, notifications.InvoicePaid{Invoice: invoice}, &customer)

Queue는 모든 메시지를 즉시 구성하고 렌더링하므로 템플릿 오류가 있으면 아무것도 큐에 등록하지 않습니다. 그런 다음 queued mail과 queued SMS처럼 수신 대상과 채널의 조합마다 잡 하나를 디스패치합니다. 사용자 세 명과 채널 두 개라면 잡 여섯 개가 만들어집니다. 문자 메시지가 실패하면 그 문자 메시지만 재시도하고 이메일은 다시 보내지 않습니다.

OnConnection과 OnQueue를 지정하지 않으면 이메일 잡은 MAIL_QUEUE_CONNECTION과 MAIL_QUEUE, 문자 메시지 잡은 SMS_QUEUE_CONNECTION과 SMS_QUEUE를 사용합니다. Slack과 패키지 채널의 잡은 기본 연결과 큐를 사용합니다.

database transaction 안에서 트랜잭션의 ctx를 전달하여 알림을 큐에 등록하면 Laravel은 트랜잭션이 커밋될 때까지 잡 디스패치를 기다립니다. 트랜잭션이 롤백되면 대기 중인 알림을 폐기하여 저장되지 않은 변경 사항을 사용자에게 알리지 않습니다. Send는 커밋을 기다리지 않으므로 트랜잭션 안에서 보내는 알림은 큐에 등록하세요.

On-demand notifications​

운영팀의 메일함처럼 모델이 아닌 대상에게 알림을 보내야 할 때도 있습니다. notification.Routes는 각 채널의 이름을 그 채널의 주소에 매핑하는 알림 수신 대상입니다. 예를 들어 데이터를 가져오는 command에서 가져오기가 끝나면 운영팀에 알릴 수 있습니다.

ops := notification.Routes{
"mail": mail.Addr("[email protected]", "Operations"),
"slack": slack.Route{Channel: "C0123ABCDEF"},
}

err := notification.Send(ctx, notifications.ImportFinished{Rows: count}, ops)

"mail"에는 mail.Address, "sms"에는 전화번호 문자열, "slack"에는 slack.Route를 사용하세요. Laravel은 라우트에 지정되지 않은 채널을 건너뜁니다. 필요에 따라 보내는 알림은 Messages의 인수로 notification.Routes를 받습니다.

func (n ImportFinished) Messages(ops notification.Routes) (notification.Messages, error) {
return notification.Messages{
Mail: mail.Message{Subject: fmt.Sprintf("Imported %d rows", n.Rows)},
Channels: []any{slack.Message{Text: slack.Markdownf("Imported %d rows", n.Rows)}},
}, nil
}

Choosing channels for each notifiable​

기본적으로 알림 수신 대상은 Messages에서 채운 모든 채널로 메시지를 받습니다. 하지만 사용자가 특정 채널을 선택하거나 해제하도록 하거나, 알림 데이터에 따라 사용할 채널을 결정하고 싶을 수 있습니다. Messages는 수신 대상을 받으므로 그 대상에 대한 채널 메시지를 생략할 수 있습니다. 예를 들어 users 테이블에 설정 페이지에서 변경하는 sms_alerts 컬럼이 있다고 가정하겠습니다.

func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
messages := notification.Messages{
Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
}

if user.SMSAlerts && n.Invoice.Total >= 10_000 {
text := sms.Text{Body: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID)}
messages.Channels = append(messages.Channels, text)
}

return messages, nil
}

이 예제에서는 모든 사용자가 이메일을 받습니다. 문자 알림을 켠 사용자만 문자 메시지를 받으며, 청구서 금액이 100달러 이상인 경우에만 받습니다.

Package channels​

사용자는 Discord처럼 Laravel에 기본 채널이 없는 곳에서 알림을 받고 싶을 수 있습니다. 패키지로 채널을 추가하면 이메일과 문자 메시지 옆에 해당 채널의 메시지도 구성할 수 있습니다.

Sending through a package channel​

패키지 채널로 보내려면 알림의 Channels에 해당 채널의 메시지를 추가하세요. Laravel은 메시지 타입으로 채널을 찾습니다. 예를 들어 github.com/example/discord 패키지가 웹훅 URL로 discord.Message를 보내는 채널을 제공한다고 가정하겠습니다.

func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
return notification.Messages{
Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
Channels: []any{
discord.Message{Content: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID)},
},
}, nil
}

알림 수신 대상은 패키지의 discord.Notifiable 인터페이스를 구현합니다. 이 인터페이스의 DiscordWebhookURL 메서드는 웹훅 URL을 반환합니다. users 테이블에 null을 허용하는 discord_webhook_url 컬럼이 있다고 가정하겠습니다.

// models/user.go
func (u User) DiscordWebhookURL() string {
if u.DiscordWebhook == nil {
return ""
}

return *u.DiscordWebhook
}

기본 채널과 마찬가지로 DiscordWebhookURL이 URL을 반환하면 사용자가 Discord 메시지를 받습니다. 사용자가 choose their channels에서 채널을 선택할 수 있게 하려면 Discord 알림을 끈 사용자의 Channels에서 Discord 메시지를 제외하세요.

Writing a channel​

채널에는 이름, 수신 대상이 목적지를 제공하기 위해 구현하는 메서드, 목적지 하나로 메시지 하나를 보내고 프로바이더가 수락하면 반환하는 함수가 있습니다. notification.NewChannel은 이 세 요소로 채널을 만듭니다. 다음은 패키지가 제공할 Discord 채널이며 Laravel의 HTTP client로 각 메시지를 POST합니다.

// Package discord sends Laravel notifications to Discord webhooks.
package discord

import (
"context"
"errors"

"go.laravel.com/httpclient"
"go.laravel.com/notification"
)

// Notifiable receives Discord notifications at a webhook URL.
type Notifiable interface {
DiscordWebhookURL() string
}

// Message is a Discord message.
type Message struct {
Content string `json:"content"`
}

// Validate checks the message against Discord's limits.
func (m Message) Validate() error {
if len([]rune(m.Content)) > 2000 {
return errors.New("a Discord message holds at most 2,000 characters")
}

return nil
}

// Channel sends Discord messages to each notifiable's webhook URL.
var Channel = notification.NewChannel("discord", Notifiable.DiscordWebhookURL, send)

func send(ctx context.Context, webhookURL string, message Message) error {
_, err := httpclient.JSON(message).EnsureSuccessful().Post(ctx, webhookURL)

return err
}

전송 함수의 인수 타입이 채널의 목적지와 메시지 타입이 됩니다. 큐의 잡은 둘 다 JSON으로 저장하므로 문자열과 json 태그가 있는 구조체처럼 JSON으로 인코딩하고 다시 디코딩할 수 있어야 합니다. 전송 함수는 워커 또는 발신자의 ctx를 받으므로 API 토큰 같은 설정과 애플리케이션 서비스에 접근할 수 있습니다.

Message처럼 메시지 타입에 Validate() error 메서드가 있으면 Laravel은 알림을 구성할 때 각 메시지에 대해 호출합니다. 그러면 프로바이더가 거부할 메시지는 큐 워커가 아닌 전송 코드와 테스트에서 실패합니다. Discord의 2,000자 제한처럼 프로바이더가 문서화한 제한에 사용하세요.

전송 함수가 실패하면 오류에 true를 반환하는 Permanent() bool 메서드가 없는 한 큐의 잡을 재시도합니다. 삭제된 웹훅의 404에 대해 EnsureSuccessful이 반환하는 오류에는 이미 이 메서드가 있으므로 위의 Discord 채널은 별도 코드 없이 재시도를 중단합니다.

패키지 채널의 알림을 큐에 등록하면 Laravel은 워커가 호출할 전송 함수를 알 수 있도록 채널 이름을 잡에 기록합니다. 여기서는 "discord"입니다. 이미 큐에 있는 잡이 계속 실행되도록 패키지를 사용하기 시작한 뒤에는 이름을 유지하세요.

패키지는 Register 메서드에서 채널을 등록하며, 패키지를 설치한 모든 애플리케이션은 해당 채널로 보낼 수 있습니다.

func (p *Package) Register(app *laravel.Registrar) error {
app.NotificationChannels(Channel)

return nil
}

애플리케이션 내부에 채널을 작성한다면 NotificationChannels: []notification.Channel{discord.Channel}처럼 bootstrap/app.go의 애플리케이션 옵션에 추가하세요. 두 채널이 이름이나 메시지 타입을 공유하면 애플리케이션 시작에 실패합니다.

Testing​

대부분의 테스트는 프로바이더가 전달했는지가 아니라 코드가 알림을 보냈는지 확인해야 합니다. notificationtest.Fake는 알림을 보내는 대신 기록합니다. 클라이언트를 만든 뒤 notificationtest.New에 전달하면 클라이언트의 애플리케이션에 페이크가 설치됩니다. 페이크도 실제 전송과 동일하게 각 메시지를 구성하고 렌더링하며 유효성을 검증하므로 템플릿 오류나 너무 긴 Discord 메시지는 테스트를 실패시킵니다.

package feature_test

import (
"fmt"
"testing"

"go.laravel.com/model"
"go.laravel.com/notificationtest"

"app/models"
"app/notifications"
"app/tests"
)

func TestPayingAnInvoiceNotifiesTheCustomer(t *testing.T) {
client := tests.New(t)
sent := notificationtest.New(client)

customer := models.User{Name: "Taylor", Email: "[email protected]"}
if err := model.Create(client.Context(), &customer); err != nil {
t.Fatal(err)
}

invoice := models.Invoice{UserID: customer.ID, Total: 120_000}
if err := model.Create(client.Context(), &invoice); err != nil {
t.Fatal(err)
}

client.Post(fmt.Sprintf("/invoices/%d/pay", invoice.ID), nil).AssertRedirectBack()

sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
return paid.Notification.Invoice.ID == invoice.ID && paid.Mail != nil
})
}

페이크는 수신 대상마다 notificationtest.Sent 하나를 기록합니다. Notification 필드는 원래 알림이며, Queued 필드는 즉시 전송했는지 큐에 등록했는지를 나타냅니다. Mail 필드에서 렌더링된 이메일을 확인하고 Mailable로 이메일을 구성한 메일러블을 추출할 수도 있습니다.

sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
if !paid.Queued || paid.Mail == nil {
return false
}
email, ok := paid.Mailable[mails.InvoicePaidEmail]()

return ok &&
paid.Mail.Subject == fmt.Sprintf("Invoice #%d is paid", invoice.ID) &&
email.Name == customer.Name
})

수신 대상이 이메일을 받지 않았다면 Mail은 nil입니다. 다른 모든 채널에서는 Message가 수신 대상이 받은 메시지를 반환하며 채널을 건너뛰었다면 false를 반환합니다. 예를 들어 위의 Taylor는 전화번호가 없으므로 문자 메시지를 보내지 않았습니다. 전화번호가 있는 고객은 다음과 같이 본문을 확인하세요.

sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
text, ok := paid.Message[sms.Text]()

return ok && strings.Contains(text.Body, "Thanks!")
})

Slack이나 패키지 채널의 메시지를 확인할 때도 해당 메시지 타입으로 Message를 호출하세요.

sent.AssertSentTo(&team, func(paid notificationtest.Sent[notifications.TeamInvoicePaid]) bool {
message, ok := paid.Message[slack.Message]()

return ok && strings.Contains(string(message.Text), fmt.Sprintf("Invoice #%d", invoice.ID))
})

sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
message, ok := paid.Message[discord.Message]()

return ok && strings.Contains(message.Content, fmt.Sprintf("Invoice #%d", invoice.ID))
})

페이크의 어서션은 알림 타입을 받습니다. AssertSent와 AssertSentTo는 각 notificationtest.Sent를 받는 선택적 함수도 받으며, 함수를 전달하면 위 예제처럼 Go가 타입을 추론합니다. 함수가 없다면 sent.AssertSentTo[notifications.InvoicePaid](&customer)처럼 타입을 명시하세요. 페이크는 다음 어서션을 제공합니다.

메서드검증 또는 반환 내용
AssertSent[T](match...)T 타입 알림이 한 번 이상 전송되거나 큐에 등록되었으며, match를 전달했다면 일치함
AssertSentTo[T](notifiable, match...)이 수신 대상에게 T 타입 알림이 전송되거나 큐에 등록되었으며, match를 전달했다면 일치함
AssertNotSentTo[T](notifiable)이 수신 대상에게 T 타입 알림이 전송되거나 큐에 등록되지 않음
AssertSentTimes[T](count)T 타입 알림이 정확히 count개의 수신 대상에게 전달됨
AssertNotSent[T]()T 타입 알림이 전송되거나 큐에 등록되지 않음
AssertNothingSent()전송되거나 큐에 등록된 알림이 없음
Sent[T]()알림을 포함한 T 타입의 각 notificationtest.Sent를 순서대로 반환

페이크는 주소와 목적지로 수신 대상을 구분하므로 테스트의 customer는 핸들러가 불러온 사용자와 일치합니다. 알림을 실제 큐에 등록하지 않고 기록하므로 테스트에 워커가 필요하지 않습니다. 트랜잭션 안에서 큐에 등록한 알림은 트랜잭션이 커밋될 때 기록합니다. 즉시 전송한 알림과 큐에 등록한 알림은 Queued 필드로 구분하세요.

알림 페이크가 활성화되어 있는 동안 알림은 mail fake나 SMS fake에 도달하지 않습니다. 알림 페이크가 없으면 메일과 SMS 페이크가 다른 이메일 및 문자 메시지와 함께 알림 메시지도 기록합니다.