Installation:
composer require chaplean/slack-client-bundle
Add to config/bundles.php (Symfony 4+):
return [
// ...
Chaplean\Bundle\SlackClientBundle\ChapleanSlackClientBundle::class => ['all' => true],
];
Configuration:
Add to config/packages/chaplean_slack_client.yaml:
chaplean_slack_client:
access_token: '%env(SLACK_ACCESS_TOKEN)%'
Define the token in .env:
SLACK_ACCESS_TOKEN=xoxb-your-token
First Use Case: Inject the client into a service/controller and send a test message:
use Chaplean\Bundle\SlackClientBundle\Client\SlackClientInterface;
class MyController
{
public function __construct(private SlackClientInterface $slack)
{
}
public function sendTestMessage()
{
$this->slack->chatPostMessage([
'channel' => '#general',
'text' => 'Hello from Laravel!',
]);
}
}
Sending Messages:
$this->slack->chatPostMessage([
'channel' => '#notifications',
'text' => 'New order #12345 created!',
'username' => 'OrderBot',
'icon_emoji' => ':package:',
]);
Handling API Responses:
Use the chatPostMessage response to log or retry:
try {
$response = $this->slack->chatPostMessage([...]);
if ($response->isOk()) {
// Success
}
} catch (SlackApiException $e) {
// Handle error (e.g., rate limit, invalid token)
}
File Uploads:
$filePath = storage_path('app/report.pdf');
$this->slack->filesUpload([
'channels' => '#reports',
'file' => new \CURLFile($filePath),
'title' => 'Monthly Report',
]);
Reactions:
$this->slack->reactionsAdd([
'channel' => 'C12345',
'timestamp' => '1234567890.123456',
'name' => 'thumbsup',
]);
Event-Driven Notifications:
Trigger Slack messages from Laravel events (e.g., OrderCreated):
event(new OrderCreated($order));
// In listener:
$this->slack->chatPostMessage([...]);
Queue Jobs:
Offload Slack messages to a queue (e.g., sendSlackNotificationJob) to avoid timeouts:
dispatch(new SendSlackNotificationJob($message));
Rate Limiting: Implement exponential backoff for retries:
$attempts = 0;
while ($attempts < 3) {
try {
$this->slack->chatPostMessage([...]);
break;
} catch (SlackApiException $e) {
if ($e->getCode() === 429) {
sleep(2 ** $attempts);
$attempts++;
} else {
throw $e;
}
}
}
Token Security:
.env and env() helper.chat:write)..env.Rate Limits:
429 errors.X-RateLimit-Limit and X-RateLimit-Remaining headers in responses to track usage.Channel IDs vs. Names:
C12345) for most endpoints, not names (e.g., #general).$channelId = $this->slack->conversationsList(['types' => 'public_channel'])->getData()['channels'][0]['id'];
Async Operations:
filesInfo to check status:
$fileId = $response->getData()['file_id'];
$status = $this->slack->filesInfo(['file' => $fileId])->getData()['file']['status'];
Deprecation:
Enable Debug Mode:
Add to config/packages/chaplean_slack_client.yaml:
debug: true
This logs raw API requests/responses to var/log/dev.log.
Common Errors:
| Error Code | Cause | Solution |
|---|---|---|
401 |
Invalid token | Regenerate token in Slack app settings. |
404 |
Channel/user not found | Verify channel ID/name. |
429 |
Rate limit exceeded | Implement retries with backoff. |
500 |
Slack server error | Retry or check Slack status page. |
Custom Responses:
Extend the SlackResponse class to add domain-specific methods:
class CustomSlackResponse extends SlackResponse
{
public function getMessageText(): string
{
return $this->getData()['message']['text'];
}
}
Bind it in services.yaml:
Chaplean\Bundle\SlackClientBundle\Client\SlackClientInterface: '@custom_slack_client'
Middleware: Add request/response middleware to log or modify payloads:
$client->getMiddleware()->add(new class implements MiddlewareInterface {
public function handle(Request $request, callable $next) {
// Pre-process request
$response = $next($request);
// Post-process response
return $response;
}
});
Testing:
Mock the SlackClientInterface in PHPUnit:
$mock = $this->createMock(SlackClientInterface::class);
$mock->method('chatPostMessage')->willReturn(new SlackResponse(['ok' => true]));
$this->container->set('chaplean_slack_client.client', $mock);
How can I help you explore Laravel packages today?