QyWeixinService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace crmeb\services;
  3. /**
  4. * 使用
  5. * $key = Config::get('app.qy_weixin_robot_aristotle');
  6. * $svc = QyWeixinService::instance();
  7. * $svc->key($key)->markdown("### good\n>hhhh")->post();
  8. *
  9. * Class QyWeixinService
  10. * @package crmeb\services
  11. */
  12. class QyWeixinService {
  13. // api addr
  14. protected $addr = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=';
  15. // robot key
  16. protected $key = '';
  17. protected $content = '';
  18. protected $msgtype = 'text';
  19. protected static $inst = null;
  20. public static function instance()
  21. {
  22. if (is_null(self::$inst)) {
  23. self::$inst = new self();
  24. }
  25. return self::$inst;
  26. }
  27. /**
  28. * 指定 key, 一个 key 对应一个机器人
  29. */
  30. public function key(string $key)
  31. {
  32. $this->key = $key;
  33. return $this;
  34. }
  35. /**
  36. * 发送文本消息
  37. */
  38. public function text(string $text)
  39. {
  40. $this->msgtype = 'text';
  41. $this->content = $text;
  42. return $this;
  43. }
  44. /**
  45. * # title
  46. * ###### title6
  47. * **bold**
  48. * [link](url)
  49. * `code`
  50. * > refer
  51. * <font color="info"/"comment"/"warning">words</font>
  52. * @param string $md markdown text
  53. * @return $this
  54. */
  55. public function markdown(string $md)
  56. {
  57. $this->msgtype = 'markdown';
  58. $this->content = $md;
  59. return $this;
  60. }
  61. public function post()
  62. {
  63. $data = [
  64. 'msgtype' => $this->msgtype,
  65. $this->msgtype => [
  66. 'content' => $this->content,
  67. ],
  68. ];
  69. $url = $this->addr . $this->key;
  70. $ret = json_decode(self::post_json($url, $data), true);
  71. //$ret = json_decode(HttpService::postRequest($url, $data), true);
  72. return isset($ret['errcode']) && $ret['errcode'] == 0;
  73. }
  74. public static function post_json(string $url, array $data, array $headers=[], int $timeout=15)
  75. {
  76. $h = curl_init();
  77. curl_setopt($h, CURLOPT_URL, $url);
  78. curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
  79. curl_setopt($h, CURLOPT_POST, true);
  80. if ($headers && count($headers) > 0) {
  81. curl_setopt($h, CURLOPT_HTTPHEADER, $headers);
  82. }
  83. if ($timeout > 0) {
  84. curl_setopt($h, CURLOPT_CONNECTTIMEOUT, $timeout);
  85. curl_setopt($h, CURLOPT_TIMEOUT, $timeout);
  86. }
  87. $js = json_encode($data);
  88. curl_setopt($h, CURLOPT_POSTFIELDS, $js);
  89. $ret = curl_exec($h);
  90. curl_close($h);
  91. return $ret;
  92. }
  93. }