Plugin.Maui.OtpReader
provides the ability to do automatically retrieve one-time passcodes from SMS messages in .NET MAUI.
Available on NuGet.
Install with the dotnet CLI: dotnet add package Plugin.Maui.OtpReader
, or through the NuGet Package Manager in Visual Studio.
Platform | Minimum Version Supported |
---|---|
iOS | 12+ |
macOS | Not Supported |
Android | 5.0 (API 21) |
Windows | Not Supported |
Unfortunately, the usage between Android and iOS differs, but both can be easily implemented within the same project.
The code will be automatically parsed and displayed above the keyboard, but it cannot be auto-filled. To display the code above the keyboard, set up an Entry box using the SetContentTypeAsOtp
extension:
<Entry x:Name="OtpEntry" />
OtpEntry.SetContentTypeAsOtp();
Alternatively, in C#:
var OtpEntry = new Entry();
OtpEntry.SetContentTypeAsOtp();
Although setting up on Android requires a bit more work, it offers greater flexibility in handling the code.
You can use OtpReader as a static class, e.g., OtpReader.Default;
, or with dependency injection: builder.Services.AddSingleton<IOtpReader>(OtpReader.Default);
.
Once you have access to OtpReader
, you can subscribe to the OtpReceived
event, which is triggered when the SMS message is received.
private readonly IOtpReader _otpReader;
public MainPage(IOtpReader otpReader)
{
_otpReader = otpReader;
}
protected override void OnAppearing()
{
_otpReader.OtpReceived += OnOtpReceivedFromSms
base.OnAppearing();
}
private void OnOtpReceivedFromSms(string? otp)
{
// Do something with the otp code here. For example, set an Entry's text to the otp code.
}
To trigger the OtpReceived
event, you must first call the StartSmsListener
method to begin listening for the SMS message. The listener will timeout after 5 minutes if no message is received, so start it right before you send the SMS message.
You can optionally supply a regex to parse the code from the message. If no regex is supplied, the entire message contents will be returned.
private void StartListenerClicked(object sender, EventArgs e)
{
var otpRegex = @"\d{6}" // Matches exactly 6 consecutive digits
_otpReader.StartSmsListener(OtpRegex);
}
For the listener to read your SMS message, the message must contain a hash unique to your app. See Google's documentation for computing your apps hash. Alternatively, you can get your app's hash with the AppHashHelper class from the sample app.