OTP (One Time Password) is a kind of passwordless authentication, which enables user identity verification, granting access to an app/website without the need to remember passwords.
As of now reading incoming OTP SMS on native Android applications is available out of the box, that is not the case for applications developed in Expo targeting Android platform.
Note: Our focus with this article is strictly to reading incoming OTP SMS in Expo on Android.
@maniac-tech/react-native-expo-read-sms has been developed to resolve this very limitation on Expo on Android.
Read incoming OTP SMS:
We will make use of @maniac-tech/react-native-expo-read-sms to read incoming SMS in apps built using Expo on Android. These SMS will then be matched with our regex to derive the OTP value if any. You can find the sample app repo mentioned at the end of the article.
The Code
Step 1. Import the library with the following functions into your app:
import {
checkIfHasSMSPermission,
requestReadSMSPermission,
startReadSMS,
} from “@maniac-tech/react-native-expo-read-sms”;
Step 2. Check if the app has required SMS Permissions (READ_SMS, RECEIVE_SMS):
const permissionState = await checkIfHasSMSPermission();
The return value of checkIfHasSMSPermission is either false (when permissions are not present), or an object (when permissions are present)
Step 3. Considering that the initial value of the permission will be false, we need to request for user permission:
requestReadSMSPermission();
This function will show the native UI seeking SMS Permissions, like this:
Step 4: Once the user has allowed the permissions, we can start listening to incoming SMS:
startReadSMS(successCallbackFn, errorCallbackFn)
As per the documentation of the library:
The function startReadSMS, accepts two parameters a success & a error callback.
const successCallbackFn( status, sms, error) {
if (status === “success”) {
console.log(“Success in success callback”);
// Run a regex of your OTP Message and process it as per your application logic
if (OTPRegex.test(sms)){
// OTP matched
}
} else {
console.log(“Error in success callback”);
console.log(error);
}
}
const errorCallbackFn = (status, sms, error) => {
console.log(“Error Callback!”);
console.log(“Start Read SMS failed”);
};
Step 5: Voila!! We can now read incoming OTP SMS in Expo on Android !!
You can find the sample app using the library on GitHub here.
Find the library on npmjs here.
Feel free to contribute and raise issues/feature tickets on GitHub.
Top comments (0)