PHP code example of greatcode / otp-reader

1. Go to this page and download the library: Download greatcode/otp-reader library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

greatcode / otp-reader example snippets




reatcode\OtpReader\Mail\MailReader;

// 1. Initialize MailReader under Greatcode\OtpReader namespace in 1 line
$mailReader = MailReader::createGmail(
    storageDirectory: __DIR__ . '/storage/google',
    clientId: getenv('GOOGLE_CLIENT_ID'),
    clientSecret: getenv('GOOGLE_CLIENT_SECRET')
);

// 2. Poll & extract OTP in 1 line
// Automatically retries 5 times with 2s delay, filters last 5 mins, and marks email as READ
$otp = $mailReader->getLatestOtp(
    email: '[email protected]',
    from: 'tokopedia',
    afterTime: time() - 300
);

if ($otp !== null) {
    echo "✅ Extracted OTP: " . $otp;
} else {
    echo "❌ OTP not received within timeout.";
}

use Greatcode\OtpReader\Mail\EmailMessage;

$token = $mailReader->getLatestOtp(
    email: '[email protected]',
    from: 'service.com',
    afterTime: '10 minutes ago',
    parser: function (string $body, EmailMessage $message): ?string {
        if (preg_match('/\[AUTH-(\d{6})\]/', $body, $matches) === 1) {
            return $matches[1];
        }
        return null;
    },
    maxAttempts: 10,
    delaySeconds: 3
);



reatcode\OtpReader\Mail\MailReader;

// Serves HTML page, handles form submissions, and saves OAuth refresh tokens
MailReader::handleRegistration(
    storageDirectory: __DIR__ . '/storage/google',
    clientId: getenv('GOOGLE_CLIENT_ID'),
    clientSecret: getenv('GOOGLE_CLIENT_SECRET')
);
bash
php -S localhost:8080 examples/register_web.php