Order.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\model\UserCoupon;
  4. use app\common\model\Carts;
  5. use app\common\model\Order as OrderModel;
  6. use app\common\model\Address;
  7. use app\common\model\Third;
  8. use app\common\model\OrderAction;
  9. use app\common\model\OrderGoods;
  10. use app\common\library\KdApiExpOrder;
  11. use think\Db;
  12. use app\common\Service\OrderService;
  13. use app\common\Enum\OrderEnum;
  14. use app\common\Service\CartService;
  15. /**
  16. * 订单接口
  17. */
  18. class Order extends Base
  19. {
  20. protected $noNeedLogin = [];
  21. //计算邮费,判断商品 - 支持购物车和商品规格两种模式
  22. public function calculate()
  23. {
  24. // 验证请求参数
  25. $validate = new \app\api\validate\Order();
  26. $postData = $this->request->post();
  27. $postData['calculate_data'] = '1'; // 添加触发自定义验证的字段
  28. if (!$validate->scene('calculate')->check($postData)) {
  29. $this->error($validate->getError());
  30. }
  31. $userId = $this->auth->id;
  32. $config = get_addon_config('shop');
  33. $address_id = $postData['address_id'] ?? 0; // 地址id
  34. $user_coupon_id = $postData['user_coupon_id'] ?? 0; // 优惠券
  35. $cart_ids = $postData['cart_ids'] ?? []; // 购物车ID数组
  36. $goods_list = $postData['goods_list'] ?? []; // 商品列表
  37. $address = Address::get($address_id);
  38. $area_id = !empty($address) ? $address->area_id : 0;
  39. try {
  40. // 自动判断数据源类型并获取标准化的商品列表
  41. if (!empty($cart_ids) && !empty($goods_list)) {
  42. // 结算页有加减数量,需同步更新购物车
  43. CartService::updateCartByGoodsList($cart_ids, $goods_list, $userId);
  44. // goods_list 直接参与后续计算
  45. } elseif (!empty($cart_ids)) {
  46. $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
  47. } elseif (empty($goods_list)) {
  48. throw new \Exception("请提供购物车ID或商品列表");
  49. }
  50. // 统一调用计算方法
  51. $result = OrderService::calculateOrder($goods_list, $userId, $area_id, $user_coupon_id);
  52. $orderItem = $result['orderItem'];
  53. $goodsList = $result['goodsList'];
  54. $orderInfo = $result['orderInfo'];
  55. $userCoupon = $result['userCoupon'];
  56. if (empty($goodsList)) {
  57. throw new \Exception("未找到商品");
  58. }
  59. } catch (\Exception $e) {
  60. $this->error($e->getMessage());
  61. }
  62. // 处理商品数据
  63. foreach ($goodsList as $item) {
  64. //$item->category_id = $item->goods->category_id;
  65. $item->brand_id = $item->goods->brand_id;
  66. $item->goods->visible(explode(',', 'id,title,image,price,marketprice'));
  67. }
  68. // 获取我的可以使用的优惠券
  69. $goods_ids = array_column($goodsList, 'goods_id');
  70. $category_ids = array_column($goodsList, 'category_id');
  71. $brand_ids = array_column($goodsList, 'brand_id');
  72. $this->success('获取成功', [
  73. 'coupons' => UserCoupon::myGoodsCoupon($userId, $goods_ids, $category_ids, $brand_ids),
  74. 'goods_list' => $goodsList,
  75. 'order_info' => $orderInfo,
  76. ]);
  77. }
  78. /**
  79. * 提交订单 - 统一接口
  80. */
  81. public function create()
  82. {
  83. // 验证请求参数
  84. $validate = new \app\api\validate\Order();
  85. if (!$validate->scene('create')->check($this->request->post())) {
  86. $this->error($validate->getError());
  87. }
  88. $address_id = $this->request->post('address_id/d'); // 地址id
  89. $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id
  90. $remark = $this->request->post('remark','','trim'); // 备注
  91. $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
  92. $goods_list = $this->request->post('goods_list/a'); // 商品列表
  93. $order = null;
  94. try {
  95. if (!empty($cart_ids)) {
  96. // 购物车模式 - 校验购物车id合法性
  97. $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
  98. if ($row) {
  99. $this->error('存在不合法购物车数据');
  100. }
  101. // 先转换购物车为商品列表
  102. $goods_list = \app\common\Service\CartService::convertCartToGoodsList($cart_ids, $this->auth->id);
  103. // 创建订单
  104. $order = OrderService::createOrder($address_id, $this->auth->id, $goods_list, $user_coupon_id, $remark);
  105. // 购物车订单创建成功后清理购物车
  106. \app\common\Service\CartService::clear($cart_ids);
  107. } elseif (!empty($goods_list)) {
  108. // 商品列表模式 - 直接创建订单
  109. $order = OrderService::createOrder($address_id, $this->auth->id, $goods_list, $user_coupon_id, $remark);
  110. } else {
  111. $this->error('请提供购物车ID或商品列表');
  112. }
  113. } catch (\Exception $e) {
  114. $this->error($e->getMessage());
  115. }
  116. $this->success('下单成功!', array_intersect_key($order->toArray(), array_flip(['order_sn', 'id', 'order_status'])));
  117. }
  118. //订单详情
  119. public function detail()
  120. {
  121. // 验证请求参数
  122. $validate = new \app\api\validate\Order();
  123. $orderId = $this->request->get('orderId');
  124. $params = ['orderId' => $orderId];
  125. if (!$validate->scene('detail')->check($params)) {
  126. $this->error($validate->getError());
  127. }
  128. $order = OrderService::getDetail($orderId, $this->auth->id);
  129. if (empty($order)) {
  130. $this->error('未找到订单');
  131. }
  132. //$order->append(['order_status_text']);
  133. $address = OrderService::getAddressInfo($orderId);
  134. $order->address = $address;
  135. // $order->append(['status_text']);
  136. // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
  137. // $order->expiretime = $order->expiretime - time();
  138. $this->success('', $order);
  139. }
  140. //订单列表
  141. public function index()
  142. {
  143. // 验证请求参数
  144. $validate = new \app\api\validate\Order();
  145. $param = $this->request->param();
  146. $param['time_range'] = '1'; // 添加触发时间范围验证的字段
  147. if (!$validate->scene('lists')->check($param)) {
  148. $this->error($validate->getError());
  149. }
  150. // 设置默认值
  151. $userId = $this->auth->id;
  152. $param['page'] = $this->request->param('page', 1, 'intval');
  153. $param['pageSize'] = $this->request->param('pageSize', 10, 'intval');
  154. $status = $this->request->param('status', 0, 'intval'); // 默认为0(全部订单)
  155. $param['keywords'] = $this->request->param('keywords', '', 'trim');
  156. $status = OrderEnum::SHOW_TYPE_STATUS_MAP[$status];
  157. $list = OrderService::getOrderList($userId ,$param, $status);
  158. foreach ($list as $item) {
  159. // $item->append(['order_status_text']);
  160. $field = 'id,order_sn,amount,goods_price,order_amount,express_name,express_no,order_goods,order_status_text,order_status';
  161. $item->visible(explode(',', $field));
  162. }
  163. $this->success('获取成功', $list);
  164. }
  165. //取消订单
  166. public function cancel()
  167. {
  168. // 验证请求参数
  169. $validate = new \app\api\validate\Order();
  170. $orderId = $this->request->post('orderId');
  171. $params = ['orderId' => $orderId];
  172. if (!$validate->scene('cancel')->check($params)) {
  173. $this->error($validate->getError());
  174. }
  175. $order = OrderService::getByOrderId($orderId);
  176. if (empty($order)) {
  177. $this->error('订单不存在');
  178. }
  179. if ($order->user_id != $this->auth->id) {
  180. $this->error('不能越权操作');
  181. }
  182. if ($order->status == 'hidden') {
  183. $this->error('订单已失效!');
  184. }
  185. //可以取消
  186. if ($order->canCancelHandle()) {
  187. // 启动事务
  188. Db::startTrans();
  189. try {
  190. $order->order_status = OrderEnum::STATUS_CANCEL;
  191. $order->cancel_time = time();
  192. $order->save();
  193. foreach ($order->order_goods as $item) {
  194. $sku = $item->sku;
  195. $goods = $item->goods;
  196. //商品库存恢复
  197. if ($sku) {
  198. $sku->setInc('stocks', $item->nums);
  199. }
  200. if ($goods) {
  201. $goods->setInc('stocks', $item->nums);
  202. }
  203. }
  204. //恢复优惠券
  205. UserCoupon::resetUserCoupon($order->user_coupon_id, $order->order_sn);
  206. // 提交事务
  207. Db::commit();
  208. } catch (\Exception $e) {
  209. // 回滚事务
  210. Db::rollback();
  211. $this->error('订单取消失败');
  212. }
  213. //记录操作
  214. OrderAction::push($order->order_sn, '系统', '订单取消成功');
  215. $this->success('订单取消成功!', $order['status']);
  216. } else {
  217. $this->error('订单不允许取消');
  218. }
  219. }
  220. //订单支付
  221. public function pay()
  222. {
  223. // 验证请求参数
  224. $validate = new \app\api\validate\Order();
  225. if (!$validate->scene('pay')->check($this->request->post())) {
  226. $this->error($validate->getError());
  227. }
  228. $order_sn = $this->request->post('order_sn');
  229. $paytype = $this->request->post('paytype');
  230. $method = $this->request->post('method');
  231. $appid = $this->request->post('appid'); //为APP的应用id
  232. $returnurl = $this->request->post('returnurl', '', 'trim');
  233. $openid = $this->request->post('openid', '', null);
  234. $logincode = $this->request->post('logincode', '', null);
  235. $orderInfo = OrderModel::getByOrderSn($order_sn);
  236. if (!$orderInfo) {
  237. $this->error("未找到指定的订单");
  238. }
  239. if ($orderInfo) {
  240. $this->error("订单已经支付,请勿重复支付");
  241. }
  242. if (OrderModel::isExpired($order_sn)) {
  243. $this->error("订单已经失效");
  244. }
  245. //如果有传递logincode,则直接使用code换openid
  246. if (!$openid && $logincode) {
  247. $json = (new \app\common\library\Wechat\Service())->getWechatSession($logincode);
  248. $openid = $json['openid'] ?? $openid;
  249. }
  250. //必须传递openid
  251. if (in_array($method, ['miniapp', 'mp', 'mini']) && !$openid) {
  252. $this->error("未找到第三方用户信息", 'bind');
  253. }
  254. $response = null;
  255. try {
  256. $response = OrderModel::pay($order_sn, $this->auth->id, $paytype, $method, $openid, '', $returnurl);
  257. } catch (\Exception $e) {
  258. $this->error($e->getMessage());
  259. }
  260. $this->success("请求成功", $response);
  261. }
  262. //确认收货
  263. public function receipt()
  264. {
  265. // 验证请求参数
  266. $validate = new \app\api\validate\Order();
  267. $orderId = $this->request->post('orderId');
  268. $params = ['orderId' => $orderId];
  269. if (!$validate->scene('detail')->check($params)) {
  270. $this->error($validate->getError());
  271. }
  272. $order = OrderService::getByOrderId($orderId);
  273. if (empty($order)) {
  274. $this->error('订单不存在');
  275. }
  276. if ($order->user_id != $this->auth->id) {
  277. $this->error('该订单不属于当前用户');
  278. }
  279. if ($order->canConfirmHandle()) {
  280. $order->order_status = OrderEnum::STATUS_CONFIRM;
  281. $order->receive_time = time();
  282. $order->save();
  283. //记录操作
  284. OrderAction::push($order->order_sn, '系统', '订单确认收货成功');
  285. $this->success('确认收货成功');
  286. }
  287. $this->error('订单不允许确认收货');
  288. }
  289. //查询物流
  290. public function logistics()
  291. {
  292. // 验证请求参数
  293. $validate = new \app\api\validate\Order();
  294. $params = ['order_sn' => $this->request->param('order_sn')];
  295. if (!$validate->scene('detail')->check($params)) {
  296. $this->error($validate->getError());
  297. }
  298. $order_sn = $this->request->param('order_sn');
  299. $order = OrderModel::getDetail($order_sn, $this->auth->id);
  300. if (empty($order)) {
  301. $this->error('未找到订单');
  302. }
  303. if (!$order->shippingstate) {
  304. $this->error('订单未发货');
  305. }
  306. $electronics = Db::name('shop_order_electronics')->where('order_sn', $order_sn)->where('status', 0)->find();
  307. if (!$electronics) {
  308. $this->error('订单未发货');
  309. }
  310. $result = KdApiExpOrder::getLogisticsQuery([
  311. 'order_sn' => $order_sn,
  312. 'logistic_code' => $electronics['logistic_code'],
  313. 'shipper_code' => $electronics['shipper_code']
  314. ]);
  315. if ($result['Success']) {
  316. $this->success('查询成功', $result['Traces']);
  317. }
  318. $this->error('查询失败');
  319. }
  320. // 获取状态订单统计
  321. public function getOrderStatusCount(){
  322. $userId = $this->auth->id;
  323. $info = OrderService::getOrderStatusCount($userId);
  324. $this->success('获取成功', $info);
  325. }
  326. }