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

Dtone Php Api Laravel Package

kstmostofa/dtone-php-api

Laravel package that wraps the DT One (Dtone) API, providing a simple interface to authenticate and interact with DT One services from your Laravel app. Includes a publishable config and helper resources (with GIFs in docs).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require kstmostofa/dtone-php-api
    php artisan vendor:publish --provider="Kstmostofa\DtonePhpApi\DtoneServiceProvider" --tag="config"
    
    • Publish the config file to config/dtone.php and update API credentials (client_id, client_secret, redirect_uri).
  2. First Use Case:

    • Send an OTP (most common entry point):
      use Kstmostofa\DtonePhpApi\Facades\Dtone;
      
      $response = Dtone::otp()->send([
          'to' => '+880123456789', // Recipient number
          'message' => 'Your OTP is 123456',
      ]);
      
    • Check the response for success status and otp_id for future reference.
  3. Where to Look First:

    • Facade: Kstmostofa\DtonePhpApi\Facades\Dtone (primary entry point).
    • Config: config/dtone.php (API keys, endpoints, and defaults).
    • Documentation: Dtone API Docs (for payload structures).

Implementation Patterns

Core Workflows

  1. OTP Management:

    • Send OTP:
      Dtone::otp()->send($payload);
      
    • Verify OTP:
      Dtone::otp()->verify($otpId, $otpCode);
      
    • Resend OTP:
      Dtone::otp()->resend($otpId);
      
  2. Voice Calls:

    • Initiate Call:
      Dtone::voice()->call([
          'to' => '+880123456789',
          'from' => '+1234567890',
          'url' => 'https://example.com/voice-callback',
      ]);
      
    • Use url for server-side callback handling (e.g., call status updates).
  3. GIFs (Unique Feature):

    • Send GIF:
      Dtone::gif()->send([
          'to' => '+880123456789',
          'gif_id' => '12345', // From Dtone's GIF library
      ]);
      
  4. Error Handling:

    • Wrap API calls in try-catch:
      try {
          $response = Dtone::otp()->send($payload);
      } catch (\Exception $e) {
          Log::error("Dtone API Error: " . $e->getMessage());
          return response()->json(['error' => 'Failed to send OTP'], 500);
      }
      

Integration Tips

  1. Service Container Binding:

    • Bind the Dtone client to Laravel’s container for dependency injection:
      $this->app->bind('dtone', function () {
          return new \Kstmostofa\DtonePhpApi\DtoneClient(config('dtone'));
      });
      
  2. Middleware for Auth:

    • Use middleware to validate Dtone responses before processing:
      public function handle($request, Closure $next) {
          $response = $next($request);
          if ($response->getData()->success === false) {
              abort(500, 'Dtone API Error');
          }
          return $response;
      }
      
  3. Logging:

    • Log all Dtone API requests/responses for debugging:
      Dtone::setLogger(function ($message) {
          Log::debug($message);
      });
      
  4. Testing:

    • Mock the Dtone facade in tests:
      $this->mock(Dtone::class)->shouldReceive('otp')->andReturnSelf()
          ->shouldReceive('send')->andReturn((object) ['success' => true]);
      

Gotchas and Tips

Pitfalls

  1. API Credentials:

    • Hardcoded Secrets: Avoid committing config/dtone.php to version control. Use environment variables:
      'client_id' => env('DTONE_CLIENT_ID'),
      'client_secret' => env('DTONE_CLIENT_SECRET'),
      
    • Redirect URI: Must match exactly what’s registered in the Dtone Developer Portal.
  2. Rate Limiting:

    • Dtone enforces rate limits (e.g., 1 OTP per second per number). Handle 429 Too Many Requests gracefully:
      if ($response->getStatusCode() === 429) {
          sleep(2); // Retry after delay
      }
      
  3. OTP Expiry:

    • OTPs expire after 5 minutes. Design your flow to handle timeouts:
      if (time() - $otpSentAt > 300) { // 5 minutes
          return redirect()->route('resend.otp');
      }
      
  4. GIF Limitations:

    • GIF IDs must be fetched from Dtone’s library via their GIF API. Hardcoding IDs may fail if the library updates.

Debugging

  1. Enable Verbose Logging:

    • Set the debug flag in config/dtone.php:
      'debug' => env('APP_DEBUG', false),
      
    • Logs will include raw request/response payloads.
  2. Common Errors:

    • Invalid Credentials: Verify client_id/client_secret in the Dtone portal.
    • Invalid Number: Ensure numbers are in E.164 format (e.g., +880123456789).
    • Missing Parameters: Validate payloads against Dtone’s API specs.
  3. Testing Locally:

    • Use Dtone’s sandbox environment (if available) to test without real charges. Check the config for sandbox URLs:
      'base_url' => env('DTONE_SANDBOX_URL', 'https://api.dtone.com'),
      

Extension Points

  1. Custom Responses:

    • Extend the facade to add domain-specific methods:
      // app/Providers/AppServiceProvider.php
      public function boot() {
          Dtone::macro('sendWelcomeOTP', function ($phone) {
              return $this->otp()->send([
                  'to' => $phone,
                  'message' => 'Welcome! Your OTP is ' . Str::random(6),
              ]);
          });
      }
      
  2. Webhook Handling:

    • For voice call callbacks, create a route to handle Dtone’s webhook payloads:
      Route::post('/dtone/callback', function (Request $request) {
          $payload = $request->json()->all();
          // Process call status (e.g., answered, failed)
      });
      
    • Verify webhook signatures using Dtone’s signature header.
  3. Batch Processing:

    • Use Laravel’s queues to handle high-volume OTPs/voice calls:
      Dtone::otp()->send($payload)->onQueue('dtone-jobs');
      
  4. Fallback Mechanisms:

    • Implement fallback logic if Dtone fails (e.g., email or alternative SMS provider):
      try {
          Dtone::otp()->send($payload);
      } catch (\Exception $e) {
          Mail::to($user->email)->send(new OTPFallbackMail($otpCode));
      }
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle