aping/laravel-ding-robot
Laravel DingTalk Robot SDK for sending messages via one or multiple DingTalk robots. Provides a Ding facade/app('ding') helpers to send Text, Link, Markdown, ActionCard (single/multi), and FeedCard message types, with response helpers to check success and errors.
Installation
composer require aping/laravel-ding-robot
Publish the config file:
php artisan vendor:publish --provider="Aping\DingRobot\DingRobotServiceProvider"
Configuration
Edit config/ding-robot.php with your DingTalk (DingTalk is a Chinese enterprise messaging platform) credentials:
'access_token' => env('DING_ROBOT_ACCESS_TOKEN'),
'webhook' => env('DING_ROBOT_WEBHOOK'),
First Use Case Send a simple text message via Tinker or a controller:
use Aping\DingRobot\Facades\DingRobot;
DingRobot::send([
'text' => 'Hello, DingTalk! This is my first message.',
'isAtAll' => false,
]);
Aping\DingRobot\Facades\DingRobot – The primary entry point for sending messages.config/ding-robot.php – Centralized configuration for tokens, webhooks, and defaults.Aping\DingRobot\DingRobotServiceProvider – Registers the facade and binds the service.Use the facade to send different types of messages (text, markdown, link, etc.):
// Text message
DingRobot::send([
'text' => 'Build <font color=\"warning\">#123</font> failed.',
'isAtAll' => true,
]);
// Markdown message
DingRobot::send([
'markdown' => '### Alert\n> Build failed for project `example`.',
'isAtAll' => false,
]);
// Link message
DingRobot::send([
'link' => [
'text' => 'Click to view',
'url' => 'https://example.com',
'picUrl' => 'https://example.com/image.png',
],
]);
Trigger actions like alerts or reminders:
DingRobot::send([
'action' => 'alert',
'text' => 'Server down!',
'isAtAll' => true,
]);
Use atMobiles to mention specific users:
DingRobot::send([
'text' => 'Hey @13800000000, check this out!',
'isAtAll' => false,
'atMobiles' => ['13800000000', '13900000000'],
]);
Attach files to messages:
DingRobot::send([
'text' => 'Log file attached.',
'file' => [
'name' => 'error.log',
'path' => storage_path('logs/error.log'),
],
]);
Offload DingTalk notifications to a queue (e.g., ding-robot queue) to avoid blocking the request:
DingRobot::queueSend([
'text' => 'This will be sent later.',
]);
Wrap calls in a try-catch block to log failures:
try {
DingRobot::send(['text' => 'Critical alert!']);
} catch (\Exception $e) {
\Log::error('DingTalk notification failed: ' . $e->getMessage());
}
Override defaults per message:
DingRobot::send([
'text' => 'Custom message',
'isAtAll' => false,
], [
'webhook' => 'https://oapi.dingtalk.com/robot/special_webhook',
]);
Trigger DingTalk messages from Laravel events (e.g., job.failed):
use Illuminate\Queue\Events\JobFailed;
Event::listen(JobFailed::class, function (JobFailed $event) {
DingRobot::send([
'text' => 'Job failed: ' . $event->job->payload['command'],
]);
});
Mock the facade in tests:
$this->mock(DingRobot::class)->shouldReceive('send')->once();
Token Expiry
config/ding-robot.php.Webhook URL Limits
Markdown Formatting
<script>) will break rendering.File Size Limits
At-All vs. At-Mobiles
isAtAll mentions all users subscribed to the robot, while atMobiles mentions specific users. Misusing these can spam unintended recipients.atMobiles arrays before sending.Enable Debugging
Add this to config/ding-robot.php to log raw responses:
'debug' => env('APP_DEBUG', false),
Check Raw Responses Inspect the HTTP response from DingTalk to diagnose issues:
try {
$response = DingRobot::send(['text' => 'Test']);
\Log::debug('DingTalk response:', ['response' => $response]);
} catch (\Exception $e) {
\Log::error('DingTalk error:', ['error' => $e->getMessage()]);
}
Validate Webhook URL
Ensure the webhook URL in config/ding-robot.php is correct and accessible. Test it manually via curl:
curl -X POST \
-H 'Content-Type: application/json' \
-d '{"text":"{\"text\":\"Test\"}"}' \
https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN
Custom Message Types
Extend the package by adding new message types (e.g., feedCard):
// In a service or trait
public function feedCard(array $data)
{
return $this->send(array_merge($data, ['msgtype' => 'feedCard']));
}
Middleware for Messages Add validation or transformation logic before sending:
DingRobot::extend(function ($message) {
if (isset($message['text']) && strpos($message['text'], 'URGENT') !== false) {
$message['isAtAll'] = true;
}
return $message;
});
Custom HTTP Client Override the default Guzzle client for logging or retry logic:
// In a service provider
$this->app->bind('dingRobot.httpClient', function () {
return new \GuzzleHttp\Client([
'timeout' => 10,
'on_stats' => function ($event) {
\Log::debug('DingTalk HTTP request', $event->getStats());
},
]);
});
Local Testing with Mock Webhooks Use a local DingTalk mock server (e.g., ding-mock) to test messages without hitting DingTalk’s API.
Environment Variables
Ensure .env has:
DING_ROBOT_ACCESS_TOKEN=your_token_here
DING_ROBOT_WEBHOOK=https://oapi.dingtalk.com/robot/send
Default Values
Override defaults in config/ding-robot.php:
'defaults' => [
'isAtAll' => false, // Default to not @all users
'atMobiles' => [], // No default @mobiles
],
Secure Token Storage
Avoid hardcoding tokens. Use Laravel’s .env
How can I help you explore Laravel packages today?