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

Php Laravel Package

chaboksms/php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chaboksms/php:1.0.5
    

    Or add to composer.json:

    "require": {
        "chaboksms/php": "1.0.5"
    }
    

    Run composer update.

  2. First Use Case: Initialize the API with your credentials and send an SMS:

    use Chaboksms\ChaboksmsApi;
    
    $api = new ChaboksmsApi('your_username', 'your_password');
    $sms = $api->sms();
    $response = $sms->send('09123456789', '5000123', 'Test message');
    $json = json_decode($response);
    echo $json->Value; // Outputs RecId or Error Number
    
  3. Where to Look First:

    • Official Webservice Docs for API parameters and responses.
    • The ChaboksmsApi class methods for available services (sms, ticket, branch, users, contacts).

Implementation Patterns

Core Workflows

  1. SMS Sending:

    • Basic: Use sms()->send($to, $from, $text) for REST or SOAP.
    • Advanced: Use sms('soap')->send2($to, $from, $text, $isFlash, $udh) for UDH support.
    • Scheduled: Use sms('soap')->sendSchedule($to, $from, $text, $isFlash, $scheduleDateTime, $period).
  2. Bulk SMS:

    • Create a branch (bank of numbers):
      $branch = $api->branch();
      $branch->add('MyBranch', 'owner_username');
      
    • Add numbers to the branch:
      $branch->addNumber(['09123456789', '09123456788'], 1);
      
    • Send bulk SMS:
      $branch->sendBulk('5000123', 'Title', 'Message', 1, null, 1, 'normal', 0, 0, 0);
      
  3. Asynchronous Operations:

    • Initialize async services:
      $smsAsync = $api->sms('async');
      $ticketAsync = $api->ticket('async');
      
    • Execute operations in parallel:
      $smsAsync->send(...)->execute();
      $ticketAsync->add(...)->execute();
      
  4. User Management:

    • Add a new user:
      $users = $api->users();
      $users->add(['username' => 'new_user', 'password' => 'password123']);
      
    • Update user credit:
      $users->changeCredit(1000, 'Top-up', 'new_user', true);
      
  5. Contact Management:

    • Add a contact:
      $contacts = $api->contacts();
      $contacts->add(['mobileNumber' => '09123456789', 'name' => 'John Doe']);
      
    • Fetch contacts by group:
      $contacts->get(1, 'keyword', 0, 10);
      

Integration Tips

  • Error Handling: Wrap API calls in try-catch blocks to handle exceptions gracefully.
    try {
        $response = $sms->send(...);
    } catch (Exception $e) {
        Log::error('SMS Error: ' . $e->getMessage());
        return response()->json(['error' => 'Failed to send SMS'], 500);
    }
    
  • Rate Limiting: Monitor credit balance with $sms->getCredit() to avoid overages.
  • Logging: Log responses for debugging:
    Log::info('SMS Response', ['response' => $json]);
    
  • Configuration: Store credentials in Laravel's .env file and use the config helper or a service provider to inject them:
    $api = new ChaboksmsApi(config('services.chaboksms.username'), config('services.chaboksms.password'));
    

Gotchas and Tips

Pitfalls

  1. Authentication:

    • Ensure credentials are correct; incorrect credentials will throw exceptions without descriptive errors.
    • Use HTTPS for API calls to avoid credential leaks.
  2. SOAP vs REST:

    • REST is limited to basic operations. Use SOAP for advanced features like scheduled sends or bulk operations.
    • SOAP methods often accept arrays (e.g., $smsSoap->send(['09123456789', '09123456788'], ...)), while REST methods do not.
  3. Asynchronous Operations:

    • Async methods require explicit execution with ->execute(). Forgetting this will not trigger the API call.
    • Async operations run in parallel but may not guarantee order. Use callbacks or queues for dependent operations.
  4. Character Encoding:

    • Ensure text messages are UTF-8 encoded to avoid garbled characters in Persian or special symbols.
  5. Credit Management:

    • Always check credit balance ($sms->getCredit()) before bulk operations to avoid failed sends.
    • Some methods (e.g., sendWithSpeech) consume more credit than standard SMS.
  6. Number Formats:

    • Iranian phone numbers must include the 0 prefix (e.g., 09123456789), not +989123456789.
  7. Rate Limits:

    • Chaboksms may throttle requests during peak hours. Implement exponential backoff in your retry logic.

Debugging Tips

  1. Enable SOAP Debugging:

    • For SOAP errors, enable debugging in the ChaboksmsApi class or use a SOAP client library like php-soap with debug options:
      $client = new SoapClient($wsdl, ['trace' => 1]);
      
    • Check $client->__getLastRequest() and $client->__getLastResponse() for raw SOAP traffic.
  2. Log Raw Responses:

    • Log JSON/response objects to identify malformed requests or unexpected responses:
      Log::debug('Raw Response', ['response' => $response]);
      
  3. Validate Inputs:

    • Sanitize inputs (e.g., phone numbers, text) before passing them to the API to avoid invalid parameter errors.
  4. Test in Sandbox:

    • Use the provided 200 free credits for testing. Avoid using production credentials in development.

Extension Points

  1. Custom Request/Response Handling:

    • Extend the ChaboksmsApi class to add middleware for logging, retries, or request transformations:
      class CustomChaboksmsApi extends ChaboksmsApi {
          public function send($to, $from, $text) {
              $text = $this->sanitizeText($text); // Custom logic
              return parent::send($to, $from, $text);
          }
      }
      
  2. Queue Async Operations:

    • Dispatch async operations to Laravel queues for better performance:
      dispatch(new SendSmsJob($to, $from, $text))->onQueue('sms');
      
  3. Webhook Integration:

    • Poll the API for delivery status ($sms->isDelivered($recId)) or use Chaboksms webhooks (if supported) to receive real-time updates.
  4. Caching:

    • Cache frequent queries like credit balance or user details:
      $credit = Cache::remember('chaboksms_credit', 300, function() {
          return $sms->getCredit();
      });
      
  5. Fallback Mechanisms:

    • Implement fallback logic for failed requests (e.g., retry with exponential backoff or switch to a backup SMS provider).

Configuration Quirks

  1. Time Zones:

    • Scheduled sends (sendSchedule) use the server's time zone. Ensure your server's time zone matches expectations (e.g., config(['app.timezone' => 'Asia/Tehran'])).
  2. Base Numbers:

    • For sendByBaseNumber, ensure the bodyId (shared service body) is correctly created via $smsSoap->sharedServiceBodyAdd().
  3. Async Execution Order:

    • Async operations may not execute in the order they are called. Use unique identifiers (e.g., recId) to track individual requests.
  4. SOAP WSDL:

    • The SOAP WSDL URL is hardcoded in the package. If Chaboksms updates their endpoint, you may need to override it:
      $api = new ChaboksmsApi($username, $password, 'https://new-wsdl-url.com');
      
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