cleentfaar/slack
PHP Slack API client that maps Slack Web API methods to dedicated payload and response objects. Uses JMS Serializer for spec-aligned data models, supports OAuth/tokens, and provides examples plus event hooks around the ApiClient.
Installation
composer require cleentfaar/slack
Ensure ext-curl is enabled in your PHP environment.
Configure API Token
Generate a Slack API token (or OAuth token) from Slack API Dashboard.
Store it securely (e.g., Laravel .env):
SLACK_TOKEN=your_bot_or_user_token_here
Initialize Client
use CL\Slack\ApiClient;
$apiClient = new ApiClient(config('slack.token'));
First Use Case: Send a Message
$chat = $apiClient->chatPostMessage([
'channel' => '#general',
'text' => 'Hello from Laravel!'
]);
beforeRequest, afterResponse).Use dedicated payload classes for each API method (e.g., ChatPostMessagePayload, UsersListPayload).
// Create
$response = $apiClient->chatPostMessage($payload);
// Read
$users = $apiClient->usersList()->getUsers();
// Update (e.g., update user profile)
$response = $apiClient->usersProfileSet($payload);
// Delete (e.g., delete a message)
$response = $apiClient->chatDelete($payload);
Responses are serialized as PHP objects (e.g., ChatPostMessageResponse).
$response = $apiClient->chatPostMessage($payload);
if ($response->isOk()) {
$ts = $response->getTs(); // Timestamp of the message
}
Attach listeners to the ApiClient for pre/post-request logic:
$apiClient->addListener('beforeRequest', function ($event) {
$event->setData(['custom_field' => 'value']);
});
Check isRateLimited() and handle 429 responses:
try {
$response = $apiClient->chatPostMessage($payload);
} catch (\CL\Slack\Exception\RateLimitExceededException $e) {
sleep($e->getRetryAfter());
retry();
}
Service Provider Binding
Bind the client in AppServiceProvider for dependency injection:
public function register()
{
$this->app->singleton('slack', function ($app) {
return new ApiClient(config('slack.token'));
});
}
Config File
Define Slack config in config/slack.php:
return [
'token' => env('SLACK_TOKEN'),
'default_channel' => '#general',
];
Artisan Commands
Use the package’s CLI tools (via cleentfaar/slack-cli) or build custom commands:
use CL\Slack\ApiClient;
use Illuminate\Console\Command;
class SendSlackMessage extends Command
{
protected $apiClient;
public function __construct(ApiClient $apiClient)
{
parent::__construct();
$this->apiClient = $apiClient;
}
public function handle()
{
$this->apiClient->chatPostMessage([
'channel' => $this->argument('channel'),
'text' => $this->argument('message'),
]);
}
}
Queue Jobs Offload Slack API calls to queues (e.g., send notifications asynchronously):
use CL\Slack\ApiClient;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SendSlackNotification implements ShouldQueue
{
use Dispatchable, Queueable;
public function __construct(private ApiClient $apiClient, private string $message)
{
}
public function handle()
{
$this->apiClient->chatPostMessage([
'channel' => '#notifications',
'text' => $this->message,
]);
}
}
Custom Payloads
Extend Payload classes for domain-specific logic:
use CL\Slack\Payload\PayloadInterface;
class CustomSlackPayload implements PayloadInterface
{
public function getMethod()
{
return 'custom.method';
}
public function getData()
{
return ['key' => 'value'];
}
}
Webhook Integration
Use the package to parse incoming Slack events (via Events\EventsPayload):
$event = new EventsPayload($request->all());
$apiClient->eventsHandle($event);
Testing
Mock the ApiClient in tests:
$mockApiClient = Mockery::mock(ApiClient::class);
$mockApiClient->shouldReceive('chatPostMessage')
->once()
->andReturn(new ChatPostMessageResponse(['ok' => true]));
$this->app->instance('slack', $mockApiClient);
Deprecated Methods
The package is archived (last release: 2016). Some Slack API methods (e.g., files.delete, reactions.*) are missing. Check the missing methods list before use.
SSL/CURL Errors
CURLE_SSL_CACERT (e.g., on Windows/OS X).$client = new \GuzzleHttp\Client(['verify' => false]);
$apiClient = new ApiClient($token, $client);
Note: Disabling verification is unsafe for production.Token Permissions
Ensure your Slack token has the required scopes (e.g., chat:write for posting messages). Test with a bot token first.
Rate Limiting
Slack enforces rate limits. Handle 429 responses gracefully:
try {
$response = $apiClient->chatPostMessage($payload);
} catch (\CL\Slack\Exception\RateLimitExceededException $e) {
sleep($e->getRetryAfter());
// Retry or notify admin
}
JMS Serializer Dependency The package uses JMS Serializer for (de)serialization. If you encounter issues, ensure:
jms/serializer package is installed (composer require jms/serializer).Enable Guzzle Debugging Attach a middleware to log requests/responses:
$client = new \GuzzleHttp\Client([
'middleware' => [
new \GuzzleHttp\Middleware::tap(function ($request) {
\Log::debug('Slack Request:', $request->getBody());
}),
new \GuzzleHttp\Middleware::tap(function ($response) {
\Log::debug('Slack Response:', $response->getBody());
}),
],
]);
$apiClient = new ApiClient($token, $client);
Validate Payloads
Use PayloadValidator to check payloads before sending:
use CL\Slack\Payload\PayloadValidator;
$validator = new PayloadValidator();
$errors = $validator->validate($payload);
if (!empty($errors)) {
throw new \InvalidArgumentException('Payload validation failed');
}
Handle Exceptions Catch specific exceptions for better error handling:
try {
$response = $apiClient->chatPostMessage($payload);
} catch (\CL\Slack\Exception\SlackException $e) {
\Log::error('Slack API Error:', ['error' => $e->getMessage()]);
}
How can I help you explore Laravel packages today?