尝试从传入消息中自动读取OTP以进行本机反应

时间:2019-10-21 08:12:07

标签: javascript reactjs react-native react-native-android

我的目标:我正在尝试从我的react native应用程序中的传入消息(SMS)中自动填充OTP代码。

到目前为止,我仅从后端获取SMS,但无法在我的react本机应用程序中读取SMS(包含OTP)。

在Verification.js(用户输入电话号码)和Otp screen.js(应填充OTP代码)中。

  1. 在Verification.js中,我还添加了从用户读取和接收短信所需的权限。

  2. 在OtpScreen.js中,我们注册了一个sms侦听器,但未执行回调函数(负责读取传入消息)。

//AndroidManifest.xml
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
//Verification.js
useEffect(() => {
    async function requestReadSmsPermission() {
      console.log('the sms');
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_SMS,
          {
            title: ' Read SMS Permission',
            message: 'Allow Our app to read your SMS?',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK'
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('You can Read  the SMS');
        } else {
          console.log('Read SMS permission denied');
        }
      } catch (err) {
        console.warn(err);
      }
    }
    requestReadSmsPermission();
  }, []);

  useEffect(() => {
    async function requestReceiveSmsPermission() {
      console.log('the sms');
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.RECEIVE_SMS,
          {
            title: ' Receive SMS Permission',
            message: 'Allow Our App to receive your SMS?',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK'
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('You can receive  the SMS');
        } else {
          console.log('receive SMS permission denied');
        }
      } catch (err) {
        console.warn(err);
      }
    }
    requestReceiveSmsPermission();
  }, []);

我提供了以下代码段:

//OtpScreen.js
useEffect(() => {
   _onSmsListener = async () => {
     try {
       const registered = await SmsRetriever.startSmsRetriever();
       if (registered) { // this becomes true
         console.log('SMS listener', registered);
         SmsRetriever.addSmsListener(event => {
           console.log(event.message); //I am not able to get the sms message here.
           SmsRetriever.removeSmsListener();
         });
       }
     } catch (error) {
       console.log(JSON.stringify(error));
     }
   };

PS:我使用了react-native-sms-retriever软件包。

是否可以使用本机Android代码实现此目标?

要读取SMS消息是否需要进行任何配置,或者消息必须采用特定格式?如果是,该如何格式化消息?

0 个答案:

没有答案