跳至正文

SMS ​

Introduction ​

Text messages reach users who aren't looking at their email, which makes them a good fit for sign-in codes and urgent alerts. The sms package sends text messages through Telnyx in production, and writes them to your log in development.

When you want to reach users on more than one channel, such as an email and a text message about the same paid invoice, send a notification instead. Notifications send their text messages with the configuration on this page.

Configuration ​

Laravel reads its SMS configuration from these environment variables:

VariableSetsDefault
SMS_SENDERThe default senderlog
SMS_FROMThe number, short code, or sender ID that messages come fromNone
SMS_QUEUE_CONNECTION, SMS_QUEUEWhere queued messages goThe default queue connection and queue

By default, Laravel uses the log sender so new applications never send real text messages until you configure Telnyx. It logs each recipient at info and the message text at debug. To view message text locally without turning on debug logs everywhere, raise the sms package's log level:

ini
LOG_LEVEL=info,sms=debug

Telnyx ​

Create an API key in the Telnyx portal, then select the telnyx sender:

ini
SMS_SENDER=telnyx
SMS_FROM=+15555550100
TELNYX_KEY=KEY0123

Telnyx needs to know which number a message comes from, so set SMS_FROM, TELNYX_MESSAGING_PROFILE_ID, or both. With only a messaging profile, Telnyx picks a number from the profile's number pool.

Send returns once Telnyx accepts a message, but a carrier may still refuse to deliver it. US carriers, for example, block messages from numbers that aren't registered for 10DLC. You'll find those failures in the message's status in the Telnyx portal, not in an error from Send.

Adding senders ​

If your application needs a second Telnyx account or messaging profile, such as separating on-call alerts from customer messages, add a named sender in your options' Configure function in bootstrap/app.go:

go
func configure(cfg *config.Config, env *config.Env) {
	cfg.SMS.Senders = map[string]config.Telnyx{
		"alerts": {
			Key:                env.String("TELNYX_ALERTS_KEY", ""),
			MessagingProfileID: "40017f8e-49bd-4f6a-a7a2-9c1b5d7a2f61",
			From:               "+15555550150",
		},
	}
}

A sender's From number replaces SMS_FROM for its messages, falling back to SMS_FROM when empty. Setting a number on the message itself overrides both.

To send through the alerts sender, name it with sms.Use. It works with Send and Queue:

go
err := sms.Use("alerts").To("+15555550123").Send(ctx, "The deploy finished.")

Sending messages ​

To send a text message, pass the recipient's number to sms.To, then pass the request and the text to Send. For example, suppose your application has an Order model and a phone column on users that may be empty. This handler texts the customer when their order ships:

go
package orders

import (
	"fmt"

	"go.laravel.com/model"
	"go.laravel.com/sms"
	"go.laravel.com/web"

	"app/models"
)

func Ship(r *web.Request) *web.Response {
	order, err := model.FromRoute[models.Order](r, "order")
	if err != nil {
		return web.Fail(err)
	}

	customer, err := model.Find[models.User](r, order.UserID)
	if err != nil {
		return web.Fail(err)
	}

	// Ship the order...

	if customer.Phone != "" {
		text := fmt.Sprintf("Order #%d has shipped.", order.ID)
		if err := sms.To(customer.Phone).Send(r, text); err != nil {
			return web.Fail(err)
		}
	}

	return web.Back()
}

Send waits for the provider to accept the message. A command, a job, or a listener passes the ctx it received in place of r. To send from a number other than SMS_FROM, call From before Send:

go
err := sms.To("+15555550123").From("+15555550199").Send(r, "Your order shipped.")

Laravel validates the recipient and text before calling Telnyx, so an invalid number or empty message returns an error from Send right away. Messages are not automatically truncated: Telnyx splits long messages into multiple segments and bills per segment (up to 160 characters for GSM text, or 70 characters when emoji or non-GSM characters are included), so keep alerts and verification codes concise.

Phone numbers ​

Recipient phone numbers must be in E.164 format with a leading + and country code, such as +15555550123. sms.To strips formatting characters such as spaces, dashes, dots, and parentheses, so +1 (555) 555-0123 is valid.

Numbers without a country code, such as 555-0123, fail validation because national numbers are ambiguous across countries, so store user phone numbers in E.164 format when you collect them. sms.Normalize returns a number in that format, or an error, so a handler that saves a user's settings may check the number and tell the user what to fix:

go
phone, err := sms.Normalize(form.Phone)
if err != nil {
	return web.Invalid(
		"phone",
		"Enter your phone number with its country code, such as +1 555 555 0123.",
	)
}

Queueing messages ​

Sending SMS synchronously during a request adds external network latency and ties the request's success to Telnyx availability. Call Queue instead to deliver messages through a queue worker with automatic retries on failure. Before calling Queue, you may delay delivery with Delay, or pick a specific queue with OnQueue and a connection with OnConnection:

go
err := sms.To("+15555550123").
	Delay(5*time.Minute).
	OnQueue("sms").
	Queue(r, "Your order shipped.")

The job holds the message encrypted with your application key, so you may queue sign-in codes. Like every job, it waits for the current database transaction to commit, and a rollback discards it. A retry doesn't text the customer twice, because every attempt sends Telnyx the same idempotency key.

Testing ​

You don't want your test suite texting real phones. smstest.New installs a fake in your test's application that records messages instead of sending them, and checks each one as a real send would, so an invalid number still fails the test:

go
package feature_test

import (
	"fmt"
	"strings"
	"testing"

	"go.laravel.com/model"
	"go.laravel.com/sms"
	"go.laravel.com/smstest"

	"app/models"
	"app/tests"
)

func TestCustomersHearWhenTheirOrderShips(t *testing.T) {
	client := tests.New(t)
	texts := smstest.New(client)

	user := models.User{Name: "Taylor", Email: "taylor@laravel.com", Phone: "+15555550123"}
	if err := model.Create(client.Context(), &user); err != nil {
		t.Fatal(err)
	}

	order := models.Order{UserID: user.ID, Total: 2500}
	if err := model.Create(client.Context(), &order); err != nil {
		t.Fatal(err)
	}

	page := fmt.Sprintf("/orders/%d", order.ID)
	client.From(page).Post(page+"/ship", nil).AssertRedirectBack()

	texts.AssertSent(func(message sms.Message) bool {
		return message.To == "+15555550123" && strings.Contains(message.Text, "has shipped")
	})
}

The fake counts Send as sent and Queue as queued, and has assertions for each:

MethodAsserts or returns
AssertSent(match), AssertQueued(match)A sent, or queued, message matches match
AssertSentTimes(count), AssertQueuedTimes(count)Exactly count messages were sent, or queued
AssertNothingSent()No message was sent or queued
Sent(), Queued()Each sent, or queued, message, in order

AssertSent passes match an sms.Message, with To, From, and Text fields. AssertQueued passes an sms.QueuedMessage, which also has Sender, Connection, Queue, and Delay fields, so you may check where its job would go:

go
texts.AssertQueued(func(message sms.QueuedMessage) bool {
	return message.Queue == "sms" && message.Delay == 5*time.Minute
})