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

melipayamak/php

PHP client for the MeliPayamak SMS platform. Send SMS and manage messaging features via API with a simple, lightweight wrapper you can drop into any PHP app, including Laravel, for quick integration and delivery.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require melipayamak/php
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Melipayamak\MelipayamakServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Melipayamak\MelipayamakServiceProvider"
    

    Update config/melipayamak.php with your API credentials (username, password, endpoint).

  3. First Use Case: Sending an SMS

    use Melipayamak\Melipayamak;
    
    $melipayamak = new Melipayamak(config('melipayamak.username'), config('melipayamak.password'));
    
    $response = $melipayamak->sendSms([
        'to' => '5511987654321',
        'message' => 'Hello from Laravel!',
    ]);
    
    dd($response);
    
  4. Async Support For asynchronous requests (e.g., SOAP/REST):

    $melipayamak->sendSmsAsync([
        'to' => '5511987654321',
        'message' => 'Async test',
    ]);
    

Implementation Patterns

Core Workflows

  1. Synchronous Requests Use for immediate responses (e.g., balance checks, real-time SMS delivery confirmation):

    $balance = $melipayamak->getBalance();
    $smsResponse = $melipayamak->sendSms($data);
    
  2. Asynchronous Requests Use for fire-and-forget operations (e.g., bulk SMS, notifications):

    $melipayamak->sendSmsAsync($data); // Returns immediately
    
  3. Batch Processing Loop through a collection of recipients:

    $users = User::where('needs_notification', true)->get();
    foreach ($users as $user) {
        $melipayamak->sendSmsAsync([
            'to' => $user->phone,
            'message' => "Your code: {$user->verification_code}",
        ]);
    }
    
  4. Error Handling Wrap calls in try-catch blocks:

    try {
        $response = $melipayamak->sendSms($data);
    } catch (\Melipayamak\Exceptions\MelipayamakException $e) {
        Log::error("Melipayamak error: " . $e->getMessage());
        // Retry logic or fallback
    }
    

Integration Tips

  1. Laravel Queues for Async Dispatch async jobs to Laravel queues for reliability:

    use Melipayamak\Jobs\SendSmsJob;
    
    SendSmsJob::dispatch($data)->onQueue('melipayamak');
    
  2. Service Container Binding Bind the client to Laravel’s IoC container for dependency injection:

    $this->app->bind(Melipayamak::class, function ($app) {
        return new Melipayamak(
            config('melipayamak.username'),
            config('melipayamak.password')
        );
    });
    

    Then inject via constructor:

    public function __construct(private Melipayamak $melipayamak) {}
    
  3. Logging Responses Extend the client to log responses automatically:

    $melipayamak = new Melipayamak($username, $password);
    $melipayamak->setLogger(app(\Psr\Log\LoggerInterface::class));
    
  4. Testing Mock the client in tests:

    $mock = Mockery::mock(Melipayamak::class);
    $mock->shouldReceive('sendSms')->andReturn(['success' => true]);
    $this->app->instance(Melipayamak::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Methods Avoid sendByBaseNumber (mentioned in release notes) as it may not be maintained. Use sendSms or sendSmsAsync instead.

  2. Rate Limiting The API may throttle requests. Implement exponential backoff in retries:

    $attempts = 0;
    while ($attempts < 3) {
        try {
            $response = $melipayamak->sendSms($data);
            break;
        } catch (\Melipayamak\Exceptions\RateLimitException $e) {
            $attempts++;
            sleep(2 ** $attempts);
        }
    }
    
  3. Character Limits SMS messages are limited to 160 characters (or 70 for Unicode). Truncate long messages:

    $message = Str::limit($longMessage, 160);
    
  4. SOAP vs REST The package supports both, but REST is generally preferred for simplicity. SOAP may require additional XML configuration.


Debugging

  1. Enable Verbose Logging Set the log level to debug in config/melipayamak.php:

    'log_level' => 'debug',
    
  2. Raw Response Inspection Access raw responses for debugging:

    $response = $melipayamak->sendSms($data);
    \Log::debug("Raw response: " . print_r($response->getRawData(), true));
    
  3. Common Exceptions

    • MelipayamakException: Generic errors (check getMessage()).
    • AuthenticationException: Invalid credentials (verify config/melipayamak.php).
    • InvalidParameterException: Malformed request data (validate inputs).

Extension Points

  1. Custom Requests Extend the base client to add custom endpoints:

    class CustomMelipayamak extends Melipayamak {
        public function customEndpoint($data) {
            return $this->request('POST', '/custom-endpoint', $data);
        }
    }
    
  2. Middleware Add request/response middleware:

    $melipayamak->addMiddleware(function ($request) {
        $request->setHeader('X-Custom-Header', 'value');
    });
    
  3. Webhook Handling For async responses, set up a webhook endpoint in your Laravel app to listen for callbacks from Melipayamak’s API.

  4. Configuration Overrides Override config values dynamically:

    $melipayamak = new Melipayamak($username, $password, [
        'endpoint' => 'https://custom-api.melipayamak.com',
    ]);
    

Tips

  1. Use Laravel Facades Create a facade for cleaner syntax:

    // app/Facades/Melipayamak.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class Melipayamak extends Facade {
        protected static function getFacadeAccessor() {
            return 'melipayamak';
        }
    }
    

    Bind in a service provider:

    $this->app->singleton('melipayamak', function ($app) {
        return new \Melipayamak\Melipayamak(
            config('melipayamak.username'),
            config('melipayamak.password')
        );
    });
    

    Now use:

    \App\Facades\Melipayamak::sendSms($data);
    
  2. Environment-Specific Config Use Laravel’s environment variables for credentials:

    'username' => env('MELIPAYAMAK_USERNAME'),
    'password' => env('MELIPAYAMAK_PASSWORD'),
    
  3. Monitoring Track API usage with Laravel Horizon or a monitoring tool by logging all requests/responses.

  4. Fallback Mechanisms Implement fallback providers (e.g., Twilio) if Melipayamak fails:

    try {
        $melipayamak->sendSms($data);
    } catch (\Exception $e) {
        $twilio->sendSms($data); // Fallback
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
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