Order.php 13 KB

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