Order.php 14 KB

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