Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phone Verification Bundle Laravel Package

alexgeno/phone-verification-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package** with dependencies:
   ```bash
   composer require alexgeno/phone-verification-bundle snc/redis-bundle predis/predis symfony/vonage-notifier

(Replace symfony/vonage-notifier with your preferred SMS provider, e.g., symfony/twilio-notifier.)

  1. Configure .env with required variables:

    PHONE_VERIFICATION_OTP_LENGTH=4
    PHONE_VERIFICATION_RATE_LIMIT_INITIATE_PERIOD_SECS=86400
    PHONE_VERIFICATION_RATE_LIMIT_INITIATE_COUNT=10
    PHONE_VERIFICATION_RATE_LIMIT_COMPLETE_PERIOD_SECS=300
    PHONE_VERIFICATION_RATE_LIMIT_COMPLETE_COUNT=5
    REDIS_URL=redis://localhost:6379
    
  2. Verify auto-configuration (Flex recipe handles most setup). If not using Flex, manually:

    • Add AlexGeno\PhoneVerificationBundle\AlexGenoPhoneVerificationBundle::class to config/bundles.php.
    • Define routes in config/routes/alex_geno_phone_verification.yaml (or use the default Flex-generated ones).
  3. First use case: Trigger verification via DI:

    use AlexGeno\PhoneVerification\Manager\Initiator;
    
    public function register(Request $request, Initiator $initiator)
    {
        $phone = $request->input('phone');
        $initiator->initiate($phone); // Sends OTP via SMS
    }
    

Implementation Patterns

Core Workflows

  1. Initiation Flow:

    • Dependency Injection: Use Initiator service to trigger OTP generation/sending.
      $initiator->initiate('+1234567890');
      
    • Console Command: For testing/CLI:
      php bin/console phone-verification:initiate --to=+1234567890
      
    • HTTP Endpoint: Default route /phone-verification/initiate/{to} (POST).
  2. Completion Flow:

    • Dependency Injection: Verify OTP with Completer.
      $completer->complete('+1234567890', '1234'); // Returns bool
      
    • Console Command:
      php bin/console phone-verification:complete --to=+1234567890 --otp=1234
      
    • HTTP Endpoint: Default route /phone-verification/complete/{to}/{otp} (POST).
  3. Rate Limiting:

    • Configure per-phone limits in .env (e.g., 10 initiations/day, 5 failed completions/5 mins).
    • Automatically blocks excessive requests; check RateLimitExceededException in logs.
  4. Storage Integration:

    • Redis (Default): Uses snc/redis-bundle for in-memory storage.
      alex_geno_phone_verification:
          storage:
              driver: redis
              redis:
                  connection: default
      
    • MongoDB: Requires doctrine/mongodb-odm-bundle and manual index setup (see MIGRATIONS.md).
      alex_geno_phone_verification:
          storage:
              driver: mongodb
              mongodb:
                  connection: default
      
  5. SMS Provider Switching:

    • Replace vonage in config with your provider (e.g., twilio, messagebird).
      alex_geno_phone_verification:
          sender:
              transport: twilio
      
    • Configure provider-specific DSN in .env (e.g., TWILIO_DSN=...).

Integration Tips

  • User Session Binding: Store the phone number in the user’s session after successful verification:
    $request->session()->put('verified_phone', $phone);
    
  • Event Listeners: Extend functionality by listening to PhoneVerificationSentEvent or PhoneVerificationCompletedEvent:
    use AlexGeno\PhoneVerification\Event\PhoneVerificationSentEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class VerificationLogger implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                PhoneVerificationSentEvent::class => 'logVerification',
            ];
        }
    
        public function logVerification(PhoneVerificationSentEvent $event): void
        {
            // Log or notify (e.g., Slack) when OTP is sent.
        }
    }
    
  • Custom Templates: Override SMS templates by extending the Sender service (see Gotchas).

Gotchas and Tips

Pitfalls

  1. MongoDB Indexes:

    • Manual Setup Required: Unlike Redis, MongoDB needs explicit indexes for OTP expiration and uniqueness.
      db.session.createIndex({"updated": 1}, { expireAfterSeconds: 300 }); // OTP expiry
      
    • Migration Risk: If expireAfterSeconds doesn’t match .env values, OTPs may expire prematurely or persist too long. Fix: Recreate indexes after changing PHONE_VERIFICATION_RATE_LIMIT_COMPLETE_PERIOD_SECS.
  2. Rate Limiting:

    • Global vs. Per-Phone: Limits apply per phone number (to). Test with multiple phones to avoid false positives.
    • Logging: Check Symfony logs for RateLimitExceededException to debug blocked requests.
  3. OTP Expiration:

    • Double-Check .env: The complete rate limit period (PHONE_VERIFICATION_RATE_LIMIT_COMPLETE_PERIOD_SECS) also sets OTP expiry. Example: 300 = 5-minute OTP validity.
  4. Redis Connection:

    • Prefix Collisions: The default Redis key prefix (pv:1) may conflict with other bundles. Customize in config:
      alex_geno_phone_verification:
          storage:
              redis:
                  settings:
                      prefix: myapp_pv:
      
  5. SMS Provider Quirks:

    • Twilio: Requires TWILIO_DSN in .env (format: twilio://ACCOUNT_SID:TOKEN@host).
    • Vonage: Needs VONAGE_DSN (format: vonage://KEY:SECRET@host).
    • Testing: Use mock services (e.g., m6web/redis-mock) in tests to avoid real SMS costs.

Debugging Tips

  1. Enable Debug Mode:

    // config/packages/dev/alex_geno_phone_verification.yaml
    alex_geno_phone_verification:
        debug: true
    

    Logs detailed OTP generation/sending steps to Symfony’s debug log.

  2. Check Storage Directly:

    • Redis: Inspect keys with redis-cli KEYS pv:*.
    • MongoDB: Query collections:
      db.session.find().pretty(); // List pending OTPs
      
  3. Common Errors:

    • "Storage not found": Ensure snc/redis-bundle or doctrine/mongodb-odm-bundle is installed and configured.
    • "Transport not found": Verify the SMS provider package (e.g., symfony/twilio-notifier) is installed.
    • "Invalid phone format": Use E.164 format (e.g., +1234567890), not 1234567890.

Extension Points

  1. Custom Storage: Implement \AlexGeno\PhoneVerification\Storage\I and decorate the service:

    # config/services.yaml
    services:
        AlexGeno\PhoneVerificationBundle\Storage\RedisStorage:
            decorates: 'alex_geno_phone_verification.storage'
            arguments:
                $inner: '@.inner'
    

    Use case: Add analytics to storage operations.

  2. Custom Sender: Implement \AlexGeno\PhoneVerification\Sender\I for non-Symfony Notifier providers (e.g., custom HTTP API):

    class CustomSender implements SenderInterface {
        public function send(string $to, string $message): void {
            // Your logic (e.g., cURL to a SMS API)
        }
    }
    

    Decorate the alex_geno_phone_verification.sender service.

  3. Localization: Add translations for non-English SMS templates:

    # config/packages/alex_geno_phone_verification.yaml
    alex_geno_phone_verification:
        locale: es # or 'fr', 'de', etc.
    

    Note: Only en and es are bundled; extend via

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui