MiniProgramKefuReplyJob.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\jobs;
  13. use app\services\kefu\CozeServices;
  14. use crmeb\basic\BaseJobs;
  15. use crmeb\services\app\MiniProgramService;
  16. use crmeb\services\CacheService;
  17. use crmeb\traits\QueueTrait;
  18. use crmeb\utils\Queue;
  19. use think\facade\Env;
  20. use think\facade\Log;
  21. /**
  22. * 小程序原生客服消息 AI 回复任务
  23. */
  24. class MiniProgramKefuReplyJob extends BaseJobs
  25. {
  26. use QueueTrait;
  27. public static function dispatchAsync(string $openid, string $content, string $messageId = '')
  28. {
  29. if (sys_config('queue_open', 0) != 1 || Env::get('cache.driver', 'file') !== 'redis') {
  30. Log::error('小程序客服 Coze 回复未入队:请开启 Redis 缓存和队列,避免微信回调超时');
  31. return false;
  32. }
  33. return Queue::instance()->job(__CLASS__)->do('doJob')->data($openid, $content, $messageId)->errorCount(1)->push();
  34. }
  35. public function doJob(string $openid, string $content, string $messageId = ''): bool
  36. {
  37. if ($openid === '' || trim($content) === '') {
  38. return true;
  39. }
  40. $lockKey = $messageId ? 'mini_kefu_coze_' . $messageId : 'mini_kefu_coze_' . md5($openid . $content);
  41. if (CacheService::has($lockKey)) {
  42. return true;
  43. }
  44. CacheService::set($lockKey, 1, 3600);
  45. try {
  46. /** @var CozeServices $coze */
  47. $coze = app()->make(CozeServices::class);
  48. $reply = $coze->chatText('mini_' . $openid, $content);
  49. if ($reply !== '') {
  50. $sendResult = MiniProgramService::staffTo($openid, $reply);
  51. if (($sendResult['errcode'] ?? 0) != 0) {
  52. Log::error('小程序客服 Coze 回复发送失败:' . json_encode($sendResult, JSON_UNESCAPED_UNICODE));
  53. }
  54. }
  55. } catch (\Throwable $e) {
  56. Log::error('小程序客服 Coze 回复失败:' . $e->getMessage());
  57. }
  58. return true;
  59. }
  60. }