DingDingRobot.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Notification;
  3. class DingDingRobot
  4. {
  5. private $accessToken;
  6. private $secret;
  7. public function __construct($accessToken, $secret)
  8. {
  9. $this->accessToken = $accessToken;
  10. $this->secret = $secret;
  11. }
  12. const URL = 'https://oapi.dingtalk.com/robot/send';
  13. public function markdown($title, $text)
  14. {
  15. return TelegramBot::getDefault()->sendMsg($title."\n".$text);
  16. $now = time()*1000;
  17. $sign = $this->sign($now);
  18. $url = self::URL."?access_token={$this->accessToken}&timestamp={$now}&sign={$sign}";
  19. $data = [
  20. 'msgtype' => 'markdown',
  21. 'markdown' => [
  22. 'title' => $title,
  23. 'text' => $text,
  24. ]
  25. ];
  26. $ch = curl_init();
  27. curl_setopt($ch, CURLOPT_URL, $url);
  28. curl_setopt($ch, CURLOPT_POST, 1);
  29. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  30. curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
  31. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  32. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  33. // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
  34. curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
  35. curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
  36. $data = curl_exec($ch);
  37. curl_close($ch);
  38. return $data;
  39. }
  40. private function sign($now)
  41. {
  42. $secret = $this->secret;
  43. $string = "$now\n$secret";
  44. $sign = urlencode(base64_encode(hash_hmac('sha256', $string, $secret, true)));
  45. return $sign;
  46. }
  47. }