# expo-otp-retriever

An Expo module for retrieving OTP codes on Android using Google's SMS Retriever API.

## Features

- No SMS permissions required
- Uses Google's SMS Retriever API
- Automatic OTP detection
- App hash generation for SMS format
- Simple JavaScript API
- TypeScript support

## Installation

```bash
npm install expo-otp-retriever
# or
yarn add expo-otp-retriever
```

## Requirements

- Expo SDK 46 or higher
- Android device with Google Play Services

## Usage

### 1. Import the module

```javascript
import OtpRetriever, { OtpRetrieverEvents } from 'expo-otp-retriever';
```

### 2. Get the app hash for SMS format

You need to include the app hash in the SMS message for the API to detect it. Send this hash to your backend so it can be included in the SMS.

```javascript
async function getAppHash() {
  try {
    const hash = await OtpRetriever.getAppHash();
    console.log('App Hash:', hash);
    // Send this hash to your backend
    return hash;
  } catch (error) {
    console.error('Failed to get app hash:', error);
  }
}
```

### 3. Start listening for OTP messages

```javascript
async function startListeningForOtp() {
  try {
    // Start listening with a timeout of 60 seconds
    await OtpRetriever.startListener(60);
    console.log('Started listening for OTP');
  } catch (error) {
    console.error('Failed to start OTP listener:', error);
  }
}
```

### 4. Set up event listeners

```javascript
import { useEffect } from 'react';
import OtpRetriever, { OtpRetrieverEvents } from 'expo-otp-retriever';

function OtpScreen() {
  useEffect(() => {
    // Set up listeners
    const otpReceivedSubscription = OtpRetriever.addListener(
      OtpRetrieverEvents.OTP_RECEIVED,
      (event) => {
        console.log('OTP received:', event.otp);
        // Use the OTP code in your app
      }
    );

    const otpTimeoutSubscription = OtpRetriever.addListener(
      OtpRetrieverEvents.OTP_TIMEOUT,
      (event) => {
        console.log('OTP timeout:', event.message);
        // Handle timeout, e.g., show manual input
      }
    );

    const otpErrorSubscription = OtpRetriever.addListener(
      OtpRetrieverEvents.OTP_ERROR,
      (event) => {
        console.log('OTP error:', event.code, event.message);
        // Handle error
      }
    );

    // Start listening
    OtpRetriever.startListener(60).catch(console.error);

    // Clean up
    return () => {
      otpReceivedSubscription.remove();
      otpTimeoutSubscription.remove();
      otpErrorSubscription.remove();
      OtpRetriever.stopListener().catch(console.error);
    };
  }, []);

  return (
    // Your component rendering
  );
}
```

### 5. SMS Format

For the SMS Retriever API to detect the message, it must follow this format:

```
<#> Your verification code is: 123456
FA+9qCX9VSu
```

Where:
- The message must begin with `<#>`
- Include the OTP code (4-6 digits)
- End with the app hash you generated

## API Reference

### Methods

#### `startListener(timeoutSeconds?: number): Promise<void>`

Starts listening for OTP SMS messages.

- `timeoutSeconds`: Optional timeout in seconds, defaults to 60 seconds.

#### `stopListener(): Promise<void>`

Stops listening for OTP SMS messages and cleans up resources.

#### `getAppHash(): Promise<string>`

Generates an app signature hash needed for SMS OTP format.

#### `addListener(eventName: OtpRetrieverEvents, listener: (event: any) => void): Subscription`

Adds a listener for OTP events.

### Events

#### `OtpRetrieverEvents.OTP_RECEIVED`

Fired when an OTP code is successfully received and extracted.

Event data:
```javascript
{
  otp: "123456" // The extracted OTP code
}
```

#### `OtpRetrieverEvents.OTP_TIMEOUT`

Fired when the OTP listener times out.

Event data:
```javascript
{
  message: "SMS retrieval timed out"
}
```

#### `OtpRetrieverEvents.OTP_ERROR`

Fired when an error occurs during OTP retrieval.

Event data:
```javascript
{
  code: "ERROR_CODE",
  message: "Error message",
  details: {} // Optional additional details
}
```

### Error Codes

- `LISTENER_ERROR`: Error in the SMS listener
- `HASH_GENERATION_ERROR`: Error generating the app hash
- `UNSUPPORTED_PLATFORM`: The platform is not supported (iOS or web)
- `PLAY_SERVICES_UNAVAILABLE`: Google Play Services is not available on the device

## Troubleshooting

### OTP not being detected

1. Ensure the SMS format is correct:
   - Starts with `<#>`
   - Contains a 4-6 digit OTP code
   - Ends with the correct app hash

2. Verify Google Play Services is available and up to date on the device.

3. If testing in development, make sure you're using the app hash from the debug build. The hash is different for production builds.

### App hash issues

For production apps, you need to get your hash from the Google Play Console after uploading your app. The locally generated hash only works for debug builds.

## License

MIT