BuyHandler.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <?php
  2. namespace App\Module\AppGame\Handler\Shop;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\Fund\Enums\LOG_TYPE;
  5. use App\Module\Fund\Logic\User as FundUser;
  6. use App\Module\GameItems\Services\ItemService;
  7. use App\Module\Shop\Models\ShopItem;
  8. use Google\Protobuf\Internal\Message;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Uraus\Kku\Common\DataItem;
  12. use Uraus\Kku\Common\LastData;
  13. use Uraus\Kku\Request\RequestShopBuy;
  14. use Uraus\Kku\Response\ResponseShopBuy;
  15. use UCore\Exception\LogicException;
  16. /**
  17. * 处理商品购买请求
  18. */
  19. class BuyHandler extends BaseHandler
  20. {
  21. /**
  22. * 是否需要登录
  23. * @var bool
  24. */
  25. protected bool $need_login = true;
  26. /**
  27. * 处理商品购买请求
  28. *
  29. * @param RequestShopBuy $data 商品购买请求数据
  30. * @return ResponseShopBuy 商品购买响应
  31. */
  32. public function handle(Message $data): Message
  33. {
  34. // 创建响应对象
  35. $response = new ResponseShopBuy();
  36. try {
  37. // 获取请求参数
  38. $goodId = $data->getGoodId();
  39. $number = $data->getNumber();
  40. $userId = $this->user_id;
  41. // 参数验证
  42. if ($goodId <= 0) {
  43. throw new LogicException("商品ID无效");
  44. }
  45. if ($number <= 0) {
  46. throw new LogicException("购买数量必须大于0");
  47. }
  48. // 获取商品信息
  49. $shopItem = ShopItem::findOrFail($goodId);
  50. if (!$shopItem->is_active) {
  51. throw new LogicException("该商品已下架");
  52. }
  53. // 检查购买限制
  54. if ($shopItem->max_buy > 0) {
  55. // 获取用户已购买数量
  56. $boughtCount = $shopItem->getUserBoughtCount($userId);
  57. if ($boughtCount + $number > $shopItem->max_buy) {
  58. throw new LogicException("超出购买限制,最多还能购买" . ($shopItem->max_buy - $boughtCount) . "个");
  59. }
  60. }
  61. // 计算总价
  62. $totalPrice = $shopItem->price * $number;
  63. // 开始事务
  64. DB::beginTransaction();
  65. // 扣除用户货币
  66. $fundResult = FundUser::handle(
  67. $userId,
  68. $shopItem->currency_id,
  69. -$totalPrice,
  70. LOG_TYPE::TRADE,
  71. $goodId,
  72. "购买商品:{$shopItem->name} x {$number}"
  73. );
  74. if (is_string($fundResult)) {
  75. throw new LogicException("购买失败:" . $fundResult);
  76. }
  77. // 添加物品到用户背包
  78. ItemService::addItem(
  79. $userId,
  80. $shopItem->item_id,
  81. $number * $shopItem->item_quantity,
  82. [
  83. 'source_type' => 'shop_buy',
  84. 'source_id' => $goodId,
  85. 'details' => [
  86. 'shop_item_id' => $goodId,
  87. 'shop_item_name' => $shopItem->name,
  88. 'price' => $shopItem->price,
  89. 'quantity' => $number
  90. ]
  91. ]
  92. );
  93. // 记录购买记录
  94. $shopItem->recordPurchase($userId, $number, $totalPrice);
  95. // 提交事务
  96. DB::commit();
  97. // 创建LastData对象,用于返回物品信息
  98. $lastData = new LastData();
  99. $itemList = [];
  100. // 创建物品数据
  101. $dataItem = new DataItem();
  102. $dataItem->setItemId($shopItem->item_id);
  103. $dataItem->setQuantity($number * $shopItem->item_quantity);
  104. $itemList[] = $dataItem;
  105. // 设置物品列表到LastData
  106. $lastData->setItems($itemList);
  107. // 设置LastData到响应
  108. $this->response->setLastData($lastData);
  109. // 设置响应状态
  110. $this->response->setCode(0);
  111. $this->response->setMsg('购买成功');
  112. // 记录日志
  113. Log::info('用户购买商品成功', [
  114. 'user_id' => $userId,
  115. 'good_id' => $goodId,
  116. 'number' => $number,
  117. 'total_price' => $totalPrice,
  118. 'item_id' => $shopItem->item_id,
  119. 'item_quantity' => $shopItem->item_quantity
  120. ]);
  121. } catch (LogicException $e) {
  122. // 回滚事务
  123. if (DB::transactionLevel() > 0) {
  124. DB::rollBack();
  125. }
  126. // 设置错误响应
  127. $this->response->setCode(400);
  128. $this->response->setMsg($e->getMessage());
  129. Log::warning('用户购买商品失败', [
  130. 'user_id' => $this->user_id,
  131. 'error' => $e->getMessage(),
  132. 'trace' => $e->getTraceAsString()
  133. ]);
  134. } catch (\Exception $e) {
  135. // 回滚事务
  136. if (DB::transactionLevel() > 0) {
  137. DB::rollBack();
  138. }
  139. // 设置错误响应
  140. $this->response->setCode(500);
  141. $this->response->setMsg('系统错误,请稍后再试');
  142. Log::error('购买商品操作异常', [
  143. 'user_id' => $this->user_id,
  144. 'error' => $e->getMessage(),
  145. 'trace' => $e->getTraceAsString()
  146. ]);
  147. }
  148. return $response;
  149. }
  150. }