Installation: Add the package via Composer:
composer require textmagic/sdk
Or manually clone the repository and include the autoload.php file.
First Use Case: Initialize the client with your credentials:
$client = new \TextmagicRestClient('<YOUR_USERNAME>', '<YOUR_API_TOKEN>');
<YOUR_USERNAME> and <YOUR_API_TOKEN> with your TextMagic account credentials (found in your TextMagic dashboard).Send a Test SMS:
$result = $client->messages->create([
'text' => 'Hello from Laravel!',
'phones' => '1234567890'
]);
success key or an error message.Key Files to Explore:
src/TextmagicRestClient.php: Core client logic.src/Exceptions/RestException.php: Error handling.src/Resources/Message.php: Message-related methods.Sending SMS:
messages->create() for one-time sends or bulk messages.$phones = ['1234567890', '0987654321'];
$result = $client->messages->create([
'text' => 'Your OTP is 1234',
'phones' => implode(',', $phones)
]);
Retrieving Messages:
messages->get():
$sentMessages = $client->messages->get(['limit' => 10]);
Handling Responses:
try-catch to handle RestException:
try {
$result = $client->messages->create([...]);
} catch (\Textmagic\Exceptions\RestException $e) {
Log::error('TextMagic Error: ' . $e->getMessage());
}
Bulk Operations:
messages->create() with comma-separated phone numbers for bulk sends.Webhooks:
Webhook class:
$webhook = new \Textmagic\Webhook($payload);
if ($webhook->isValid()) {
// Process delivery status
}
Laravel Service Provider: Bind the client to the container for dependency injection:
$this->app->singleton(\TextmagicRestClient::class, function ($app) {
return new \TextmagicRestClient(config('services.textmagic.username'), config('services.textmagic.token'));
});
Configure credentials in config/services.php:
'textmagic' => [
'username' => env('TEXTMAGIC_USERNAME'),
'token' => env('TEXTMAGIC_API_TOKEN'),
],
Queued Jobs: Dispatch SMS sends as Laravel jobs for async processing:
SendSmsJob::dispatch($client, $messageData);
Example job:
public function handle(TextmagicRestClient $client, array $data) {
$client->messages->create($data);
}
Logging: Log all API responses/errors for debugging:
try {
$result = $client->messages->create([...]);
Log::info('SMS sent', ['message_id' => $result['id']]);
} catch (\Exception $e) {
Log::error('SMS failed', ['error' => $e->getMessage()]);
}
Rate Limits:
429 Too Many Requests errors gracefully with exponential backoff:
if ($e->getStatusCode() === 429) {
sleep(2); // Retry after delay
}
Phone Number Formatting:
+1234567890).$cleanedPhone = preg_replace('/[^0-9]/', '', $phone);
Character Limits:
text field to confirm.API Token Exposure:
.env:
TEXTMAGIC_USERNAME=your_username
TEXTMAGIC_API_TOKEN=your_token_here
Webhook Validation:
$webhook = new \Textmagic\Webhook($payload, config('services.textmagic.webhook_secret'));
if (!$webhook->isValid()) {
abort(403, 'Invalid webhook');
}
Enable Debug Mode: Set the client’s debug flag to log raw API requests/responses:
$client = new \TextmagicRestClient($username, $token, [
'debug' => true,
'logger' => new \Textmagic\Logger\FileLogger('/path/to/logs.txt')
]);
Common Errors:
401 Unauthorized: Invalid username/token.400 Bad Request: Malformed phone numbers or text.500 Server Error: Contact TextMagic support.Custom Response Handling:
Message class to add domain-specific logic:
class CustomMessage extends \Textmagic\Resources\Message {
public function sendWithTemplate($templateId) {
return $this->create([
'text' => $this->getTemplateText($templateId),
'phones' => $this->phones
]);
}
}
Mocking for Tests:
Mockery to stub API calls:
$mockClient = Mockery::mock(\TextmagicRestClient::class);
$mockClient->shouldReceive('messages->create')
->once()
->andReturn(['id' => '123']);
Adding New Endpoints:
contacts):
$client->contacts->create(['name' => 'John', 'phone' => '123']);
TextmagicRestClient to include the new resource:
$this->contacts = new \Textmagic\Resources\Contact($this);
Retry Logic:
class RetryClient {
public function create($data, $maxRetries = 3) {
$retries = 0;
while ($retries < $maxRetries) {
try {
return $client->messages->create($data);
} catch (\Textmagic\Exceptions\RestException $e) {
if ($e->getStatusCode() !== 429) throw $e;
sleep(2 ** $retries);
$retries++;
}
}
throw new \RuntimeException('Max retries exceeded');
}
}
How can I help you explore Laravel packages today?