userId); return $this->success('获取成功', [ 'price' => $price, // 单次购买价格(积分) 'balance' => $balance, // 当前剩余次数 ]); } /** * 创建购买订单 * @return Response */ public function createOrder(): Response { $data = $this->request->post(); $chatNum = (int)($data['chat_num'] ?? 1); if ($chatNum <= 0) { return $this->fail('购买数量必须大于0'); } $price = ChatBalanceService::getBuyPrice(); if ($price <= 0) { return $this->fail('购买价格未设置'); } $totalPrice = $price * $chatNum; // 检查用户积分是否足够 $userScore = \app\model\api\UserScoreDetail::getUserScore($this->userId); if ($userScore < $totalPrice) { return $this->fail('积分不足,当前积分:' . $userScore); } // 创建订单 $order = ChatOrder::createOrder($this->userId, $chatNum, $totalPrice); if (!$order) { return $this->fail('订单创建失败'); } // 立即支付(积分支付,无需跳转) $result = ChatBalanceService::buyWithScore($this->userId, $chatNum, $order); if (!$result) { // 支付失败,取消订单 ChatOrder::cancelOrder($order->id); return $this->fail('支付失败'); } // 更新订单状态 ChatOrder::paySuccess($order->id); $newBalance = ChatBalanceService::getBalance($this->userId); return $this->success('购买成功', [ 'order_id' => $order->id, 'order_no' => $order->order_no, 'chat_num' => $chatNum, 'price' => $totalPrice, 'balance' => $newBalance, ]); } /** * 获取当前聊天次数余额 * @return Response */ public function balance(): Response { $balance = ChatBalanceService::getBalance($this->userId); return $this->success('获取成功', [ 'balance' => $balance, ]); } /** * 获取购买记录列表 * @return Response */ public function orderList(): Response { $data = $this->request->get(); $page = (int)($data['page'] ?? 1); $limit = (int)($data['limit'] ?? 10); $result = ChatOrder::getUserOrders($this->userId, $page, $limit); // 处理订单状态文本 foreach ($result['list'] as &$item) { $item['status_text'] = ChatOrder::getStatusText($item['status']); } return $this->success('获取成功', $result); } /** * 获取变动明细列表 * @return Response */ public function balanceLogList(): Response { $data = $this->request->get(); $page = (int)($data['page'] ?? 1); $limit = (int)($data['limit'] ?? 10); $result = ChatBalanceLog::getUserLogs($this->userId, $page, $limit); return $this->success('获取成功', $result); } }