DingTalk.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace common\helpers;
  3. class DingTalk
  4. {
  5. private static $webhook = 'https://oapi.dingtalk.com/robot/send?access_token=';
  6. private static function request_by_curl($post_string)
  7. {
  8. $ch = curl_init();
  9. curl_setopt($ch, CURLOPT_URL, self::$webhook . \Yii::$app->params['DingTalk']['accessToken']);
  10. curl_setopt($ch, CURLOPT_POST, 1);
  11. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  12. curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
  13. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  15. // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
  16. curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
  17. curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
  18. $data = curl_exec($ch);
  19. curl_close($ch);
  20. return json_decode($data, true);
  21. }
  22. public static function sendNotice($message)
  23. {
  24. $message['serverAddr'] = $_SERVER['SERVER_ADDR'];
  25. $message['serverName'] = $_SERVER['SERVER_NAME'];
  26. $data = [
  27. 'msgtype' => 'text',
  28. 'text' => ['content' => $message],
  29. "at" => [
  30. 'atMobiles' => \Yii::$app->params['DingTalk']['atMobiles'],
  31. 'atUserIds' => \Yii::$app->params['DingTalk']['atUserIds'],
  32. 'isAtAll' => false,
  33. ]
  34. ];
  35. // 正式环境才发送
  36. if (YII_ENV == YII_ENV_PROD) {
  37. $result = self::request_by_curl(json_encode($data));
  38. if ($result['errcode'] > 0) {
  39. // 重新推送一次,如果失败,写错误日志
  40. $result = self::request_by_curl(json_encode($data));
  41. if (!$result['errcode']) {
  42. LoggerTool::error([$result, $message]);
  43. }
  44. }
  45. }
  46. }
  47. }