yale-user-access/packages/backend/Services/SMSService.cs

36 lines
1.1 KiB
C#
Raw Normal View History

2025-01-10 08:37:18 +11:00
using Microsoft.Extensions.Options;
using Serilog;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using YaleAccess.Models.Options;
namespace YaleAccess.Services
{
public class SMSService
{
private readonly TwiloOptions _twiloOptions;
public SMSService(IOptions<TwiloOptions> twiloOptions)
{
_twiloOptions = twiloOptions.Value;
}
public async Task SendCodeViaSMSAsync(string code, string phoneNumber)
{
// Create a Twilio client
TwilioClient.Init(_twiloOptions.AccountSid, _twiloOptions.AuthToken);
// Send the message
var message = await MessageResource.CreateAsync(
body: $"{_twiloOptions.Message} {code}",
from: new Twilio.Types.PhoneNumber(_twiloOptions.FromNumber),
to: new Twilio.Types.PhoneNumber(phoneNumber)
);
// Log the message
Log.Logger.Information("SMS sent to {PhoneNumber} with message SID {MessageSid}.", phoneNumber, message.Sid);
Log.Logger.Debug("SMS message: {MessageBody}", message.Body);
}
}
}