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.
Installation
composer require melipayamak/php
Add the service provider to config/app.php:
'providers' => [
// ...
Melipayamak\MelipayamakServiceProvider::class,
],
Configuration Publish the config file:
php artisan vendor:publish --provider="Melipayamak\MelipayamakServiceProvider"
Update config/melipayamak.php with your API credentials (username, password, endpoint).
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);
Async Support For asynchronous requests (e.g., SOAP/REST):
$melipayamak->sendSmsAsync([
'to' => '5511987654321',
'message' => 'Async test',
]);
Synchronous Requests Use for immediate responses (e.g., balance checks, real-time SMS delivery confirmation):
$balance = $melipayamak->getBalance();
$smsResponse = $melipayamak->sendSms($data);
Asynchronous Requests Use for fire-and-forget operations (e.g., bulk SMS, notifications):
$melipayamak->sendSmsAsync($data); // Returns immediately
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}",
]);
}
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
}
Laravel Queues for Async Dispatch async jobs to Laravel queues for reliability:
use Melipayamak\Jobs\SendSmsJob;
SendSmsJob::dispatch($data)->onQueue('melipayamak');
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) {}
Logging Responses Extend the client to log responses automatically:
$melipayamak = new Melipayamak($username, $password);
$melipayamak->setLogger(app(\Psr\Log\LoggerInterface::class));
Testing Mock the client in tests:
$mock = Mockery::mock(Melipayamak::class);
$mock->shouldReceive('sendSms')->andReturn(['success' => true]);
$this->app->instance(Melipayamak::class, $mock);
Deprecated Methods
Avoid sendByBaseNumber (mentioned in release notes) as it may not be maintained. Use sendSms or sendSmsAsync instead.
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);
}
}
Character Limits SMS messages are limited to 160 characters (or 70 for Unicode). Truncate long messages:
$message = Str::limit($longMessage, 160);
SOAP vs REST The package supports both, but REST is generally preferred for simplicity. SOAP may require additional XML configuration.
Enable Verbose Logging
Set the log level to debug in config/melipayamak.php:
'log_level' => 'debug',
Raw Response Inspection Access raw responses for debugging:
$response = $melipayamak->sendSms($data);
\Log::debug("Raw response: " . print_r($response->getRawData(), true));
Common Exceptions
MelipayamakException: Generic errors (check getMessage()).AuthenticationException: Invalid credentials (verify config/melipayamak.php).InvalidParameterException: Malformed request data (validate inputs).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);
}
}
Middleware Add request/response middleware:
$melipayamak->addMiddleware(function ($request) {
$request->setHeader('X-Custom-Header', 'value');
});
Webhook Handling For async responses, set up a webhook endpoint in your Laravel app to listen for callbacks from Melipayamak’s API.
Configuration Overrides Override config values dynamically:
$melipayamak = new Melipayamak($username, $password, [
'endpoint' => 'https://custom-api.melipayamak.com',
]);
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);
Environment-Specific Config Use Laravel’s environment variables for credentials:
'username' => env('MELIPAYAMAK_USERNAME'),
'password' => env('MELIPAYAMAK_PASSWORD'),
Monitoring Track API usage with Laravel Horizon or a monitoring tool by logging all requests/responses.
Fallback Mechanisms Implement fallback providers (e.g., Twilio) if Melipayamak fails:
try {
$melipayamak->sendSms($data);
} catch (\Exception $e) {
$twilio->sendSms($data); // Fallback
}
How can I help you explore Laravel packages today?