WechatNotify.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace crmeb\services\async\task;
  3. use crmeb\utils\Beanstalk;
  4. use crmeb\services\QyWeixinService;
  5. use think\facade\Config;
  6. use think\facade\Log;
  7. /**
  8. * 异步机器人通知.
  9. * 消息格式:
  10. * {"type":"type_name", "key":"1234", "desc":''}
  11. * Class WechatNotify
  12. */
  13. class WechatNotify
  14. {
  15. const CMD = 'wechat';
  16. const TYPE_ORDER = 'order';
  17. const TYPE_REFUND = 'refund';
  18. const TYPE_WITHDRAW = 'withdraw';
  19. const TYPE_MESSAGE = 'message';
  20. const TYPE_COMPLIANT = 'compliant';
  21. const TYPE_RECHARGE = 'recharge';
  22. const TYPE_COMMENT = 'comment';
  23. const TYPE_ERROR = 'error';
  24. public static function push(string $type, string $key, string $desc = '')
  25. {
  26. $bean = Beanstalk::instance();
  27. $tube = Config::get('app.beanstalk_tube', 'twong');
  28. $arr = [
  29. 'cmd' => self::CMD,
  30. 'ts' => time(),
  31. 'sender' => '0',
  32. 'params' => [
  33. 'type' => $type,
  34. 'key' => $key,
  35. 'desc' => $desc,
  36. ],
  37. ];
  38. $json = json_encode($arr);
  39. try {
  40. $bean::useTube($tube)->put($json);
  41. } catch (\Exception $e) {
  42. Log::error('push failed: ' . $json);
  43. }
  44. }
  45. /**
  46. * Pop task body from beanstalk and deliver to wechat robot.
  47. * @task: array
  48. * @return boolean
  49. */
  50. public static function exec(array $task)
  51. {
  52. if (!$task || !isset($task['cmd']) || $task['cmd'] != self::CMD) {
  53. Log::error('invalid cmd');
  54. return false;
  55. }
  56. // must has value
  57. $params = $task['params'];
  58. $supported_types = [
  59. self::TYPE_REFUND => '退款',
  60. self::TYPE_ORDER => '订单',
  61. self::TYPE_COMPLIANT => '反馈建议',
  62. self::TYPE_WITHDRAW => '提现请求',
  63. self::TYPE_MESSAGE => '客服消息',
  64. self::TYPE_RECHARGE => '充值',
  65. self::TYPE_COMMENT => '商品评论',
  66. self::TYPE_ERROR => '故障',
  67. ];
  68. if (!isset($params['type']) || !is_string($params['type'])) {
  69. Log::error('invalid type: bad format.');
  70. return false;
  71. }
  72. $type = $params['type'];
  73. $key = isset($params['key']) ? $params['key'] : '';
  74. if (!isset($supported_types[$type])) {
  75. Log::error('unsupported type:' . $type);
  76. return false;
  77. }
  78. $desc = isset($params['desc']) ? $params['desc'] : '';
  79. $msg = $supported_types[$type];
  80. $md = "### 新" . $msg . "\n "
  81. . "> 描述:" . $desc;
  82. QyWeixinService::instance()->key($key)
  83. ->markdown($md)->post();
  84. return true;
  85. }//
  86. }