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

Devcode Sms Bundle Laravel Package

devcodesms/devcode-sms-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Run composer require devcodesms/devcode-sms-bundle in your Symfony 6/7 project.
  2. Configuration: Add the bundle to config/bundles.php (Symfony Flex handles this automatically) and define .env with DEVCODE_SMS_API_KEY.
  3. Basic Usage: Inject DevcodeSmsClient into a service/controller and call sendSms() with recipient, message, and sender ID.

First Use Case

Send a one-time password (OTP) to a user:

use DevcodeSms\Bundle\DevcodeSmsClient;

class AuthController
{
    public function __construct(private DevcodeSmsClient $smsClient) {}

    public function sendOtp(string $phoneNumber): void
    {
        $this->smsClient->sendSms(
            $phoneNumber,
            'Your OTP is: 123456',
            'DevCode' // Sender ID
        );
    }
}

Implementation Patterns

Core Workflows

  1. Message Sending:

    • Use sendSms() for basic SMS delivery.
    • Chain with getResponse() to verify success:
      $response = $this->smsClient->sendSms($phone, $message, $sender)->getResponse();
      if ($response->isSuccess()) { /* Handle success */ }
      
  2. Balance Checks:

    • Integrate getBalance() in critical paths (e.g., pre-sending):
      $balance = $this->smsClient->getBalance();
      if ($balance->getRemainingCredit() < 1) {
          throw new \RuntimeException('Insufficient SMS credits');
      }
      
  3. Batch Processing:

    • Loop through users and send SMS in bulk (with rate-limiting):
      foreach ($users as $user) {
          $this->smsClient->sendSms($user->phone, $user->message, 'SenderID');
          sleep(1); // Avoid API throttling
      }
      

Integration Tips

  • Event-Driven: Trigger SMS after user actions (e.g., UserRegisteredEvent):
    public function onUserRegistered(UserRegisteredEvent $event): void
    {
        $this->smsClient->sendSms($event->getUser()->phone, 'Welcome!');
    }
    
  • Queue Jobs: Offload SMS sending to Symfony Messenger:
    $this->messageBus->dispatch(new SendSmsMessage($phone, $message));
    
  • Templating: Use Twig to dynamically generate messages:
    $message = $this->twig->render('emails/sms_template.txt.twig', ['user' => $user]);
    $this->smsClient->sendSms($user->phone, $message, 'SenderID');
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never hardcode DEVCODE_SMS_API_KEY in config files. Use .env strictly.
    • Restrict .env file permissions (chmod 600 .env).
  2. Character Limits:

    • DevCode SMS API enforces a 160-character limit per SMS. Longer messages auto-split but may incur extra charges.
    • Test with strlen($message) > 160 before sending.
  3. Rate Limiting:

    • Default timeout (10s) may fail under high load. Adjust timeout in devcode_sms.yaml if needed.
    • Monitor DevcodeSmsException for HTTP 429 (Too Many Requests).
  4. Sender ID Validation:

    • Sender IDs must be pre-approved by DevCode. Use getValidSenderIds() to check:
      $validSenders = $this->smsClient->getValidSenderIds();
      if (!in_array('MySender', $validSenders)) {
          throw new \InvalidArgumentException('Sender ID not approved');
      }
      

Debugging

  • Enable Logging: Add to config/packages/devcode_sms.yaml:

    devcode_sms:
        debug: true
    

    Logs appear in var/log/dev_sms.log.

  • Mocking for Tests: Use dependency injection to swap DevcodeSmsClient with a mock:

    $this->container->set(DevcodeSmsClient::class, new MockSmsClient());
    

Extension Points

  1. Custom Responses: Extend DevcodeSmsResponse to add domain-specific logic:

    class ExtendedSmsResponse extends DevcodeSmsResponse {
        public function isDelivered(): bool {
            return $this->getStatus() === 'DELIVERED';
        }
    }
    
  2. Webhook Handling: Implement a controller to process DevCode SMS delivery reports:

    #[Route('/devcode/sms/webhook', name: 'devcode_sms_webhook', methods: ['POST'])]
    public function handleWebhook(Request $request): Response {
        $webhookData = json_decode($request->getContent(), true);
        // Process $webhookData['status'], $webhookData['messageId']
    }
    
  3. Fallback Mechanisms: Decorate DevcodeSmsClient to retry failed sends or fall back to email:

    class FallbackSmsClient implements DevcodeSmsClientInterface {
        public function sendSms(string $phone, string $message, string $sender): self {
            try {
                return $this->innerClient->sendSms($phone, $message, $sender);
            } catch (DevcodeSmsException $e) {
                $this->fallbackToEmail($phone, $message);
            }
        }
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor