2022-01-06 08:00:24 +00:00
|
|
|
package twilio
|
|
|
|
|
|
|
|
import (
|
2024-09-26 07:14:33 +00:00
|
|
|
newTwilio "github.com/twilio/twilio-go"
|
|
|
|
openapi "github.com/twilio/twilio-go/rest/api/v2010"
|
|
|
|
verify "github.com/twilio/twilio-go/rest/verify/v2"
|
2022-04-26 23:01:45 +00:00
|
|
|
"github.com/zitadel/logging"
|
2022-06-13 06:34:11 +00:00
|
|
|
|
2022-04-26 23:01:45 +00:00
|
|
|
"github.com/zitadel/zitadel/internal/notification/channels"
|
|
|
|
"github.com/zitadel/zitadel/internal/notification/messages"
|
2023-12-08 14:30:55 +00:00
|
|
|
"github.com/zitadel/zitadel/internal/zerrors"
|
2022-01-06 08:00:24 +00:00
|
|
|
)
|
|
|
|
|
2023-03-28 22:09:06 +00:00
|
|
|
func InitChannel(config Config) channels.NotificationChannel {
|
2024-09-26 07:14:33 +00:00
|
|
|
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")
|
2022-01-06 08:00:24 +00:00
|
|
|
|
|
|
|
return channels.HandleMessageFunc(func(message channels.Message) error {
|
|
|
|
twilioMsg, ok := message.(*messages.SMS)
|
|
|
|
if !ok {
|
2023-12-08 14:30:55 +00:00
|
|
|
return zerrors.ThrowInternal(nil, "TWILI-s0pLc", "message is not SMS")
|
2022-01-06 08:00:24 +00:00
|
|
|
}
|
2024-09-26 07:14:33 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-03-28 22:09:06 +00:00
|
|
|
content, err := twilioMsg.GetContent()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-09-26 07:14:33 +00:00
|
|
|
params := &openapi.CreateMessageParams{}
|
|
|
|
params.SetTo(twilioMsg.RecipientPhoneNumber)
|
|
|
|
params.SetFrom(twilioMsg.SenderPhoneNumber)
|
|
|
|
params.SetBody(content)
|
|
|
|
m, err := client.Api.CreateMessage(params)
|
2022-01-06 08:00:24 +00:00
|
|
|
if err != nil {
|
2023-12-08 14:30:55 +00:00
|
|
|
return zerrors.ThrowInternal(err, "TWILI-osk3S", "could not send message")
|
2022-01-06 08:00:24 +00:00
|
|
|
}
|
2022-06-13 06:34:11 +00:00
|
|
|
logging.WithFields("message_sid", m.Sid, "status", m.Status).Debug("sms sent")
|
2022-01-06 08:00:24 +00:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|