#feature: some update
This commit is contained in:
@@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Log;
|
||||
class DingTalkService
|
||||
{
|
||||
private ?string $webhook;
|
||||
|
||||
private ?string $secret;
|
||||
|
||||
public function __construct()
|
||||
@@ -25,9 +26,32 @@ class DingTalkService
|
||||
'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' => [
|
||||
@@ -39,22 +63,33 @@ class DingTalkService
|
||||
],
|
||||
];
|
||||
|
||||
$url = $this->webhook;
|
||||
if (!empty($this->secret)) {
|
||||
$url = $webhook;
|
||||
if (! empty($secret)) {
|
||||
$timestamp = (int) round(microtime(true) * 1000);
|
||||
$stringToSign = $timestamp . "\n" . $this->secret;
|
||||
$sign = base64_encode(hash_hmac('sha256', $stringToSign, $this->secret, true));
|
||||
$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 {
|
||||
Http::timeout(10)->asJson()->post($url, $payload);
|
||||
$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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user