zitadel/internal/notification/channels/twilio/channel.go

54 lines
1.8 KiB
Go
Raw Normal View History

package twilio
import (
newTwilio "github.com/twilio/twilio-go"
openapi "github.com/twilio/twilio-go/rest/api/v2010"
verify "github.com/twilio/twilio-go/rest/verify/v2"
"github.com/zitadel/logging"
2022-06-13 06:34:11 +00:00
"github.com/zitadel/zitadel/internal/notification/channels"
"github.com/zitadel/zitadel/internal/notification/messages"
"github.com/zitadel/zitadel/internal/zerrors"
)
func InitChannel(config Config) channels.NotificationChannel {
client := newTwilio.NewRestClientWithParams(newTwilio.ClientParams{Username: config.SID, Password: config.Token})
2022-06-13 06:34:11 +00:00
logging.Debug("successfully initialized twilio sms channel")
return channels.HandleMessageFunc(func(message channels.Message) error {
twilioMsg, ok := message.(*messages.SMS)
if !ok {
return zerrors.ThrowInternal(nil, "TWILI-s0pLc", "message is not SMS")
}
if config.VerifyServiceSID != "" {
params := &verify.CreateVerificationParams{}
params.SetTo(twilioMsg.RecipientPhoneNumber)
params.SetChannel("sms")
resp, err := client.VerifyV2.CreateVerification(config.VerifyServiceSID, params)
if err != nil {
return zerrors.ThrowInternal(err, "TWILI-0s9f2", "could not send verification")
}
logging.WithFields("sid", resp.Sid, "status", resp.Status).Debug("verification sent")
twilioMsg.VerificationID = resp.Sid
return nil
}
content, err := twilioMsg.GetContent()
if err != nil {
return err
}
params := &openapi.CreateMessageParams{}
params.SetTo(twilioMsg.RecipientPhoneNumber)
params.SetFrom(twilioMsg.SenderPhoneNumber)
params.SetBody(content)
m, err := client.Api.CreateMessage(params)
if err != nil {
return zerrors.ThrowInternal(err, "TWILI-osk3S", "could not send message")
}
2022-06-13 06:34:11 +00:00
logging.WithFields("message_sid", m.Sid, "status", m.Status).Debug("sms sent")
return nil
})
}