PaySuccessAbstract.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Modules\Trade\Pay;
  3. use App\Jobs\QappTikTokUserCharge;
  4. use App\Modules\Book\Models\BookConfig;
  5. use App\Modules\Subscribe\Models\Order;
  6. use App\Modules\User\Services\ReadRecordService;
  7. use App\Modules\UserTask\Services\BaseTask;
  8. use App\Modules\UserTask\Services\UserTaskService;
  9. use Exception;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Redis;
  13. /**
  14. *
  15. * @property \App\Modules\Subscribe\Models\Order $order
  16. */
  17. abstract class PaySuccessAbstract
  18. {
  19. protected $order;
  20. /**
  21. * 处理支付成功的逻辑
  22. */
  23. abstract protected function handlePayProcess();
  24. public function __construct(Order $order)
  25. {
  26. $this->order = $order;
  27. }
  28. /**
  29. * 支付成功入口
  30. */
  31. public function success()
  32. {
  33. try {
  34. DB::beginTransaction();
  35. $this->setOrderSuccess();
  36. $this->handlePayProcess();
  37. DB::commit();
  38. $this->addQueue();
  39. return true;
  40. } catch (Exception $e) {
  41. DB::rollback();
  42. Log::error('pay.success: ' . $e->getMessage() . ' ' . $e->getTraceAsString());
  43. }
  44. }
  45. /**
  46. * 设置order成功
  47. */
  48. protected function setOrderSuccess()
  49. {
  50. $this->order->pay_type = $this->getChargeTimes();
  51. $this->order->status = 'PAID';
  52. $this->order->pay_end_at = date('Y-m-d H:i:s');
  53. $this->order->save();
  54. }
  55. /**
  56. * 获取用户第几次充值
  57. * @param $uid
  58. * @return int
  59. */
  60. private function getChargeTimes()
  61. {
  62. $count = Order::where('uid', $this->order->uid)->where('status', 'PAID')->count('id');
  63. return $count + 1;
  64. }
  65. private function getReportType(int $channel_id)
  66. {
  67. return Redis::hGet('channel:setting:' . $channel_id, 'tiktok_report_type') ?? QappTikTokUserCharge::CURRENT_DAY_REGISTER;
  68. }
  69. protected function addQueue()
  70. {
  71. UserTaskService::addUserTaskQueue($this->order->uid, BaseTask::charge, UserTaskService::judge_trigger);
  72. $bid = ReadRecordService::getSimpleFirstReadRecord($this->order->uid);
  73. $book_id = book_hash_encode($bid);
  74. $book = BookConfig::where('bid', $bid)->select('book_name')->first();
  75. $book_name = $book ? $book->book_name : '';
  76. $job = new QappTikTokUserCharge($this->order->uid, $this->order->price, $this->order->created_at, $this->getReportType($this->order->distribution_channel_id), $book_id, $book_name);
  77. dispatch($job->onConnection('rabbitmq')->onQueue('qapp_tiktok_user_charge_queue'));
  78. }
  79. }