Order.php 13 KB

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