Order.php 13 KB

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