PaySuccessAbstract.php 2.3 KB

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