QyWeixinService.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. public function key(string $key)
  28. {
  29. $this->key = $key;
  30. return $this;
  31. }
  32. public function text(string $text)
  33. {
  34. $this->msgtype = 'text';
  35. $this->content = $text;
  36. return $this;
  37. }
  38. /**
  39. * # title
  40. * ###### title6
  41. * **bold**
  42. * [link](url)
  43. * `code`
  44. * > refer
  45. * <font color="info"/"comment"/"warning">words</font>
  46. * @param string $md markdown text
  47. * @return $this
  48. */
  49. public function markdown(string $md)
  50. {
  51. $this->msgtype = 'markdown';
  52. $this->content = $md;
  53. return $this;
  54. }
  55. public function post()
  56. {
  57. $data = [
  58. 'msgtype' => $this->msgtype,
  59. $this->msgtype => [
  60. 'content' => $this->content,
  61. ],
  62. ];
  63. $url = $this->addr . $this->key;
  64. $ret = json_decode(QyWeixinService::post_json($url, $data), true);
  65. return isset($ret['errcode']) && $ret['errcode'] == 0;
  66. }
  67. public function post_json(string $url, array $data, array $headers=[], int $timeout=15)
  68. {
  69. $h = curl_init();
  70. curl_setopt($h, CURLOPT_URL, $url);
  71. curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
  72. curl_setopt($h, CURLOPT_POST, true);
  73. $js = json_encode($data);
  74. curl_setopt($h, CURLOPT_POSTFIELDS, $js);
  75. $ret = curl_exec($h);
  76. curl_close($h);
  77. return $ret;
  78. }
  79. }