Files
toolbox/app/Services/DingTalkService.php
T
2026-08-12 18:00:09 +08:00

96 lines
2.8 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class DingTalkService
{
private ?string $webhook;
private ?string $secret;
public function __construct()
{
$config = config('services.dingtalk', []);
$this->webhook = $config['webhook'] ?? null;
$this->secret = $config['secret'] ?? null;
}
public function sendText(string $message, array $atMobiles = [], bool $atAll = false): void
{
if (empty($this->webhook)) {
Log::warning('DingTalk webhook is not configured, skip sending alert. Alert content logged below.', [
'message' => $message,
'atMobiles' => $atMobiles,
'atAll' => $atAll,
]);
return;
}
$this->sendTextToWebhook($this->webhook, $message, $atMobiles, $atAll, $this->secret);
}
public function sendTextToToken(string $token, string $message, array $atMobiles = [], bool $atAll = false): bool
{
$token = trim($token);
if ($token === '') {
Log::warning('DingTalk robot token is not configured, skip sending alert.');
return false;
}
return $this->sendTextToWebhook(
'https://oapi.dingtalk.com/robot/send?access_token='.urlencode($token),
$message,
$atMobiles,
$atAll
);
}
private function sendTextToWebhook(string $webhook, string $message, array $atMobiles, bool $atAll, ?string $secret = null): bool
{
$payload = [
'msgtype' => 'text',
'text' => [
'content' => $message,
],
'at' => [
'atMobiles' => $atMobiles,
'isAtAll' => $atAll,
],
];
$url = $webhook;
if (! empty($secret)) {
$timestamp = (int) round(microtime(true) * 1000);
$stringToSign = $timestamp."\n".$secret;
$sign = base64_encode(hash_hmac('sha256', $stringToSign, $secret, true));
$encodedSign = urlencode($sign);
$separator = str_contains($url, '?') ? '&' : '?';
$url .= "{$separator}timestamp={$timestamp}&sign={$encodedSign}";
}
try {
$response = Http::timeout(10)->asJson()->post($url, $payload);
if ($response->successful() && (int) $response->json('errcode', -1) === 0) {
return true;
}
Log::error('DingTalk alert was rejected', [
'status' => $response->status(),
'errcode' => $response->json('errcode'),
]);
} catch (\Throwable $e) {
Log::error('Failed to send DingTalk alert', [
'message' => $e->getMessage(),
]);
}
return false;
}
}