WebhookService.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Services\Webhook;
  3. use App\Dao\Account\AccountDao;
  4. use App\Dao\User\UserDao;
  5. use App\Services\OpenApi\OpenService;
  6. use App\Services\Order\OrderService;
  7. class WebhookService
  8. {
  9. private $accountDao;
  10. private $userDao;
  11. private $openService;
  12. public function __construct(
  13. AccountDao $accountDao,
  14. UserDao $userDao,
  15. OpenService $openService
  16. )
  17. {
  18. $this->accountDao = $accountDao;
  19. $this->userDao = $userDao;
  20. $this->openService = $openService;
  21. }
  22. /**
  23. * @param $event // 用户咨询私信:trade_event平台校验:verify_webhook
  24. * @param $data
  25. * @return array|mixed|string
  26. * @throws \GuzzleHttp\Exception\GuzzleException
  27. */
  28. public function handleDouYinEvent($event, $data)
  29. {
  30. // 事件判断
  31. if (!in_array($event, ['verify_webhook', 'trade_event'])) {
  32. return [];
  33. }
  34. // 基本参数
  35. $clientKey = trim(getProp($data, 'client_key')); // 小程序的 APPID
  36. $signature = trim(getProp($data, 'signature')); // 消息签名,用户安全校验
  37. $eventId = (int)getProp($data, 'event_id', 0); // 事件 ID 默认 0
  38. $content = getProp($data, 'content', []); //具体内容
  39. $challenge = getProp($content, 'challenge', '');
  40. // 用户咨询私信
  41. if ($event === 'trade_event') {
  42. // 基本参数
  43. $orderId = getProp($content, 'order_id'); // 订单号
  44. $openId = getProp($content, 'customer_uid'); // 用户的 openId
  45. $serviceOpenId = getProp($content, 'sp_uid'); // 客服的 openId
  46. $conversionId = getProp($content, 'conversation_short_id'); // 会话 ID,加密
  47. // 获取小程序信息
  48. $app = $this->accountDao->getMiniAppByAppId($clientKey);
  49. if ($app) {
  50. // 获取用户信息
  51. $user = $this->userDao->getUserByOpenId($openId);
  52. if (empty($user)) {
  53. return compact('challenge');
  54. }
  55. // 获取订单信息
  56. $order = OrderService::getByTikTokOrderId($orderId);
  57. if (getProp($user, 'id') != getProp($order, 'uid')) {
  58. return compact('challenge');
  59. }
  60. // 发送私信
  61. $this->openService->getOpenInstance([
  62. 'app_id' => getProp($app, 'app_id'),
  63. 'secret' => getProp($app, 'app_secret'),
  64. ])->senImMsg($serviceOpenId, [
  65. 'conversion_id' => $conversionId, // 会话id
  66. 'send_url' => getProp($order, 'pay_url'), // 支付链接
  67. 'to_user_id' => $openId,
  68. 'msg_type' => 1, // 1-发送支付链接 2-发送支付成功
  69. ]);
  70. }
  71. }
  72. return compact('challenge');
  73. }
  74. }