Order.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. public function create()
  80. {
  81. // 验证请求参数
  82. $validate = new \app\api\validate\Order();
  83. if (!$validate->scene('create')->check($this->request->post())) {
  84. $this->error($validate->getError());
  85. }
  86. $address_id = $this->request->post('address_id/d'); // 地址id
  87. $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id
  88. $remark = $this->request->post('remark','','trim'); // 备注
  89. $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
  90. $goods_list = $this->request->post('goods_list/a'); // 商品列表
  91. $order = null;
  92. try {
  93. if (!empty($cart_ids)) {
  94. // 购物车模式 - 校验购物车id合法性
  95. $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
  96. if ($row) {
  97. $this->error('存在不合法购物车数据');
  98. }
  99. // 先转换购物车为商品列表
  100. $goods_list = \app\common\Service\CartService::convertCartToGoodsList($cart_ids, $this->auth->id);
  101. // 创建订单
  102. $order = OrderService::createOrder($address_id, $this->auth->id, $goods_list, $user_coupon_id, $remark);
  103. // 购物车订单创建成功后清理购物车
  104. \app\common\Service\CartService::clear($cart_ids);
  105. } elseif (!empty($goods_list)) {
  106. // 商品列表模式 - 直接创建订单
  107. $order = OrderService::createOrder($address_id, $this->auth->id, $goods_list, $user_coupon_id, $remark);
  108. } else {
  109. $this->error('请提供购物车ID或商品列表');
  110. }
  111. } catch (\Exception $e) {
  112. $this->error($e->getMessage());
  113. }
  114. $this->success('下单成功!', array_intersect_key($order->toArray(), array_flip(['order_sn', 'id', 'order_status'])));
  115. }
  116. //订单详情
  117. public function detail()
  118. {
  119. // 验证请求参数
  120. $validate = new \app\api\validate\Order();
  121. $orderId = $this->request->get('orderId');
  122. $params = ['orderId' => $orderId];
  123. if (!$validate->scene('detail')->check($params)) {
  124. $this->error($validate->getError());
  125. }
  126. $order = OrderService::getDetail($orderId, $this->auth->id);
  127. if (empty($order)) {
  128. $this->error('未找到订单');
  129. }
  130. //$order->append(['order_status_text']);
  131. $address = OrderService::getAddressInfo($orderId);
  132. $order->address = $address;
  133. // $order->append(['status_text']);
  134. // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
  135. // $order->expiretime = $order->expiretime - time();
  136. $this->success('', $order);
  137. }
  138. //订单列表
  139. public function index()
  140. {
  141. // 验证请求参数
  142. $validate = new \app\api\validate\Order();
  143. $param = $this->request->param();
  144. $param['time_range'] = '1'; // 添加触发时间范围验证的字段
  145. if (!$validate->scene('lists')->check($param)) {
  146. $this->error($validate->getError());
  147. }
  148. // 设置默认值
  149. $userId = $this->auth->id;
  150. $param['page'] = $this->request->param('page', 1, 'intval');
  151. $param['pageSize'] = $this->request->param('pageSize', 10, 'intval');
  152. $status = $this->request->param('status', 0, 'intval'); // 默认为0(全部订单)
  153. $param['keywords'] = $this->request->param('keywords', '', 'trim');
  154. $status = OrderEnum::SHOW_TYPE_STATUS_MAP[$status];
  155. $list = OrderService::getOrderList($userId ,$param, $status);
  156. foreach ($list as $item) {
  157. // $item->append(['order_status_text']);
  158. $field = 'id,order_sn,amount,goods_price,order_amount,express_name,express_no,order_goods,order_status_text,order_status';
  159. $item->visible(explode(',', $field));
  160. }
  161. $this->success('获取成功', $list);
  162. }
  163. //取消订单
  164. public function cancel()
  165. {
  166. // 验证请求参数
  167. $validate = new \app\api\validate\Order();
  168. $orderId = $this->request->post('orderId');
  169. $params = ['orderId' => $orderId];
  170. if (!$validate->scene('cancel')->check($params)) {
  171. $this->error($validate->getError());
  172. }
  173. $order = OrderService::getByOrderId($orderId);
  174. if (empty($order)) {
  175. $this->error('订单不存在');
  176. }
  177. if ($order->user_id != $this->auth->id) {
  178. $this->error('不能越权操作');
  179. }
  180. if ($order->status == 'hidden') {
  181. $this->error('订单已失效!');
  182. }
  183. //可以取消
  184. if ($order->canCancelHandle()) {
  185. // 启动事务
  186. Db::startTrans();
  187. try {
  188. $order->order_status = OrderEnum::STATUS_CANCEL;
  189. $order->cancel_time = time();
  190. $order->save();
  191. foreach ($order->order_goods as $item) {
  192. $sku = $item->sku;
  193. $goods = $item->goods;
  194. //商品库存恢复
  195. if ($sku) {
  196. $sku->setInc('stocks', $item->nums);
  197. }
  198. if ($goods) {
  199. $goods->setInc('stocks', $item->nums);
  200. }
  201. }
  202. //恢复优惠券
  203. UserCoupon::resetUserCoupon($order->user_coupon_id, $order->order_sn);
  204. // 提交事务
  205. Db::commit();
  206. } catch (\Exception $e) {
  207. // 回滚事务
  208. Db::rollback();
  209. $this->error('订单取消失败');
  210. }
  211. //记录操作
  212. OrderAction::push($order->order_sn, '系统', '订单取消成功');
  213. $this->success('订单取消成功!', $order['status']);
  214. } else {
  215. $this->error('订单不允许取消');
  216. }
  217. }
  218. //订单支付
  219. public function pay()
  220. {
  221. // 验证请求参数
  222. $validate = new \app\api\validate\Order();
  223. if (!$validate->scene('pay')->check($this->request->post())) {
  224. $this->error($validate->getError());
  225. }
  226. $order_sn = $this->request->post('order_sn');
  227. $paytype = $this->request->post('paytype');
  228. $method = $this->request->post('method');
  229. $appid = $this->request->post('appid'); //为APP的应用id
  230. $returnurl = $this->request->post('returnurl', '', 'trim');
  231. $openid = $this->request->post('openid', '', null);
  232. $logincode = $this->request->post('logincode', '', null);
  233. $orderInfo = OrderModel::getByOrderSn($order_sn);
  234. if (!$orderInfo) {
  235. $this->error("未找到指定的订单");
  236. }
  237. if ($orderInfo) {
  238. $this->error("订单已经支付,请勿重复支付");
  239. }
  240. if (OrderModel::isExpired($order_sn)) {
  241. $this->error("订单已经失效");
  242. }
  243. //如果有传递logincode,则直接使用code换openid
  244. if (!$openid && $logincode) {
  245. $json = (new \app\common\library\Wechat\Service())->getWechatSession($logincode);
  246. $openid = $json['openid'] ?? $openid;
  247. }
  248. //必须传递openid
  249. if (in_array($method, ['miniapp', 'mp', 'mini']) && !$openid) {
  250. $this->error("未找到第三方用户信息", 'bind');
  251. }
  252. $response = null;
  253. try {
  254. $response = OrderModel::pay($order_sn, $this->auth->id, $paytype, $method, $openid, '', $returnurl);
  255. } catch (\Exception $e) {
  256. $this->error($e->getMessage());
  257. }
  258. $this->success("请求成功", $response);
  259. }
  260. //确认收货
  261. public function receipt()
  262. {
  263. // 验证请求参数
  264. $validate = new \app\api\validate\Order();
  265. $orderId = $this->request->post('orderId');
  266. $params = ['orderId' => $orderId];
  267. if (!$validate->scene('detail')->check($params)) {
  268. $this->error($validate->getError());
  269. }
  270. $order = OrderService::getByOrderId($orderId);
  271. if (empty($order)) {
  272. $this->error('订单不存在');
  273. }
  274. if ($order->user_id != $this->auth->id) {
  275. $this->error('该订单不属于当前用户');
  276. }
  277. if ($order->canConfirmHandle()) {
  278. $order->order_status = OrderEnum::STATUS_CONFIRM;
  279. $order->receive_time = time();
  280. $order->save();
  281. //记录操作
  282. OrderAction::push($order->order_sn, '系统', '订单确认收货成功');
  283. $this->success('确认收货成功');
  284. }
  285. $this->error('订单不允许确认收货');
  286. }
  287. //查询物流
  288. public function logistics()
  289. {
  290. // 验证请求参数
  291. $validate = new \app\api\validate\Order();
  292. $params = ['order_sn' => $this->request->param('order_sn')];
  293. if (!$validate->scene('detail')->check($params)) {
  294. $this->error($validate->getError());
  295. }
  296. $order_sn = $this->request->param('order_sn');
  297. $order = OrderModel::getDetail($order_sn, $this->auth->id);
  298. if (empty($order)) {
  299. $this->error('未找到订单');
  300. }
  301. if (!$order->shippingstate) {
  302. $this->error('订单未发货');
  303. }
  304. $electronics = Db::name('shop_order_electronics')->where('order_sn', $order_sn)->where('status', 0)->find();
  305. if (!$electronics) {
  306. $this->error('订单未发货');
  307. }
  308. $result = KdApiExpOrder::getLogisticsQuery([
  309. 'order_sn' => $order_sn,
  310. 'logistic_code' => $electronics['logistic_code'],
  311. 'shipper_code' => $electronics['shipper_code']
  312. ]);
  313. if ($result['Success']) {
  314. $this->success('查询成功', $result['Traces']);
  315. }
  316. $this->error('查询失败');
  317. }
  318. }