You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

635 lines
25 KiB

6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Commons\Log;
  4. use App\Constants\v3\ErrorCode;
  5. use App\Constants\v3\LogLabel;
  6. use App\Constants\v3\OrderState;
  7. use App\Constants\v3\OrderType;
  8. use App\Constants\v3\Payment;
  9. use App\Constants\v3\SsdbKeys;
  10. use App\Exception\ErrorCodeException;
  11. use App\Model\v3\Coupon;
  12. use App\Model\v3\Goods;
  13. use App\Model\v3\GoodsActivity;
  14. use App\Model\v3\Order;
  15. use App\Model\v3\OrderGoods;
  16. use App\Model\v3\OrderMain;
  17. use App\Model\v3\OrderSalesStatistic;
  18. use App\Model\v3\ShoppingCart;
  19. use App\Model\v3\Store;
  20. use App\Service\v3\Interfaces\BadgeServiceInterface;
  21. use App\Service\v3\Interfaces\CouponRecServiceInterface;
  22. use App\Service\v3\Interfaces\CouponServiceInterface;
  23. use App\Service\v3\Interfaces\GoodsActivityServiceInterface;
  24. use App\Service\v3\Interfaces\GoodsServiceInterface;
  25. use App\Service\v3\Interfaces\InitialDeliveryServiceInterface;
  26. use App\Service\v3\Interfaces\PaymentServiceInterface;
  27. use App\Service\v3\Interfaces\ShopCartUpdateServiceInterface;
  28. use App\Service\v3\Interfaces\UserAddressServiceInterface;
  29. use App\TaskWorker\SSDBTask;
  30. use Exception;
  31. use Hyperf\Database\Model\Model;
  32. use Hyperf\DbConnection\Db;
  33. use Hyperf\Di\Annotation\Inject;
  34. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  35. use Hyperf\Redis\Redis;
  36. use Hyperf\Snowflake\IdGeneratorInterface;
  37. use Hyperf\Utils\ApplicationContext;
  38. class OrderOnlineService implements OrderOnlineServiceInterface
  39. {
  40. /**
  41. * @Inject
  42. * @var Log
  43. */
  44. protected $log;
  45. /**
  46. * @Inject
  47. * @var UserAddressServiceInterface
  48. */
  49. protected $userAddressService;
  50. /**
  51. * @Inject
  52. * @var CouponRecServiceInterface
  53. */
  54. protected $couponRecService;
  55. /**
  56. * @Inject
  57. * @var CouponServiceInterface
  58. */
  59. protected $couponService;
  60. /**
  61. * @Inject
  62. * @var GoodsActivityServiceInterface
  63. */
  64. protected $goodsActivityService;
  65. /**
  66. * @Inject
  67. * @var GoodsServiceInterface
  68. */
  69. protected $goodsService;
  70. /**
  71. * @Inject
  72. * @var PaymentServiceInterface
  73. */
  74. protected $paymentService;
  75. /**
  76. * @Inject
  77. * @var ShopCartUpdateServiceInterface
  78. */
  79. protected $shopCartUpdateService;
  80. /**
  81. * @Inject
  82. * @var BadgeServiceInterface
  83. */
  84. protected $badgeService;
  85. /**
  86. * @Inject
  87. * @var InitialDeliveryServiceInterface
  88. */
  89. protected $initialDeliveryService;
  90. /**
  91. * 下单
  92. * @param $marketId
  93. * @param $userId
  94. * @param $userAddrId
  95. * @param $storeList
  96. * @param $totalMoney
  97. * @param string $deliveryTimeNote
  98. * @param int $serviceMoney
  99. * @param null $receiveCouponIds
  100. * @param string $plat
  101. * @return array[]
  102. */
  103. public function do($marketId, $userId, $userAddrId, $storeList, $totalMoney, $deliveryTimeNote='尽快送达', $serviceMoney=0, $receiveCouponIds=null, $plat=''){
  104. $redis = ApplicationContext::getContainer()->get(Redis::class);
  105. $carts = [];
  106. Db::beginTransaction();
  107. try {
  108. $mainTable = ApplicationContext::getContainer()->get(OrderMain::class)->getTable();
  109. $childTable = ApplicationContext::getContainer()->get(Order::class)->getTable();
  110. $currentTime = time();
  111. bcscale(6);
  112. // 用户收货地址
  113. // 获取配送费用
  114. $userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId);
  115. $userAddr = $userAddrAndDPrice['address']['address'];
  116. $deliveryAmount = $userAddrAndDPrice['distribution_price'];
  117. $deliveryDistance = $userAddrAndDPrice['delivery_distance'];
  118. // 优惠券数据,当前订单可用个优惠券
  119. $couponRecs = $this->couponRecService->allForOnlineOrderAvailable($userId, $marketId);
  120. $canRealUseCoupons = $couponRecs['available'];
  121. $canRealUseCouponRecIds = array_values(array_column($canRealUseCoupons, 'id'));
  122. if (!empty(array_diff($receiveCouponIds, $canRealUseCouponRecIds))) {
  123. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '订单中有不能使用优惠券的商品', 'data' => json_encode([
  124. 'all_user_coupons_rec' => json_encode($couponRecs),
  125. 'can_real_user_coupons' => json_encode($canRealUseCoupons),
  126. 'receive_coupon_ids' => json_encode($canRealUseCouponRecIds),
  127. ])]);
  128. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON);
  129. }
  130. // 处理购物车数据,计算订单金额、子订单数据处理等
  131. $totalAmount = 0; # 实付金额
  132. $orderAmount = 0; # 订单金额
  133. $dataMain = []; # 主订单
  134. $dataChildren = []; # 子订单
  135. $dataOrderGoods = []; # 订单商品
  136. $storeTypeIds = []; # 订单中的商户类型,用于校验红包
  137. foreach ($storeList as $key => &$storeItem) {
  138. $storeId = $storeItem->store_id;
  139. // 子订单金额
  140. $subAmount = 0;
  141. // 店铺分类
  142. $storeType = Store::query()->where(['id' => $storeId])->value('category_id');
  143. $storeTypeIds[] = (string)$storeType;
  144. // 店铺今天的订单数
  145. $count = Order::query()
  146. ->join($mainTable, ''.$mainTable.'.global_order_id', '=', ''.$childTable.'.order_main_id')
  147. ->where([''.$childTable.'.store_id' => $storeId, ''.$mainTable.'.type' => OrderType::ONLINE])
  148. ->whereBetween(''.$childTable.'.created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
  149. ->count();
  150. // 用户购物车数据
  151. $cartIds = explode(',', $storeItem->cart_ids);
  152. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
  153. foreach ($carts as $k => &$cart) {
  154. // 查个商品,做商品有效的判断检查
  155. $goods = [];
  156. if ($cart->activity_type == 1) {
  157. $goods = Goods::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  158. if (empty($goods)) {
  159. throw new ErrorCodeException(ErrorCode::GOODS_NOT_EXISTS, '['.$cart->goods_id.']');
  160. }
  161. $check = $this->goodsService->check($goods, $cart->num);
  162. if (true !== $check) {
  163. throw new ErrorCodeException($check, '['.$goods->name.'/'.$goods->goods_unit.']');
  164. }
  165. } elseif ($cart->activity_type == 2) {
  166. $goods = GoodsActivity::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  167. if (empty($goods)) {
  168. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_NOT_EXISTS, '['.$cart->goods_id.']');
  169. }
  170. $check = $this->goodsActivityService->check($goods, $cart->num, $userId);
  171. if (true !== $check) {
  172. throw new ErrorCodeException($check, '['.$goods->name.'/'.$goods->goods_unit.']');
  173. }
  174. }
  175. // 算金额
  176. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
  177. $subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
  178. // 订单商品数据
  179. $dataOrderGoods[$storeId][] = [
  180. 'order_id' => 0,
  181. 'goods_id' => $cart->goods_id,
  182. 'activity_type' => $cart->activity_type,
  183. 'number' => $cart->num,
  184. 'price' => $goods->price,
  185. 'original_price' => $goods->original_price,
  186. 'vip_price' => $goods->vip_price,
  187. 'name' => $goods->name ?: '',
  188. 'goods_unit' => $goods->goods_unit ?: '',
  189. 'cover_img' => $goods->cover_img ?: '',
  190. 'spec' => json_encode($goods->spec),
  191. ];
  192. }
  193. // 子订单数据
  194. $dataChildren[] = [
  195. 'order_main_id' => 0,
  196. 'user_id' => $userId,
  197. 'store_id' => $storeId,
  198. 'money' => bcadd((string)$subAmount, '0', 2),
  199. 'oid' => $count + 1,
  200. 'order_num' => date('YmdHis').mt_rand(1000, 9999),
  201. 'note' => $storeItem->note
  202. ];
  203. // 订单金额
  204. $orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
  205. }
  206. // 优惠券的使用
  207. $couponMoney = 0;
  208. if (!empty($receiveCouponIds)) {
  209. // 计算红包折扣金额
  210. foreach ($canRealUseCoupons as $key => &$coupon) {
  211. if (!in_array($coupon['id'], $receiveCouponIds)) {
  212. unset($coupon);
  213. continue;
  214. }
  215. if ($coupon['coupon']['discount_type'] == Coupon::DISCOUNT_TYPE_CASH) {
  216. $couponMoney = bcadd($couponMoney, $coupon['coupon']['discounts'], 2);
  217. } elseif ($coupon['coupon']['discount_type'] == Coupon::DISCOUNT_TYPE_RATE) {
  218. $discountRate = bcdiv($coupon['coupon']['discounts'],10);
  219. $discountRate = bcsub(1,$discountRate);
  220. $discountMoney = bcmul($orderAmount, $discountRate);
  221. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  222. }
  223. }
  224. }
  225. // 获取分布式全局ID
  226. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  227. $globalOrderId = $generator->generate();
  228. $orderAmount = bcadd((string)$orderAmount, '0', 2);
  229. $totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
  230. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  231. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  232. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  233. // 校验订单总金额
  234. if ($totalAmount != $totalMoney) {
  235. throw new ErrorCodeException(ErrorCode::ORDER_TOTAL_AMOUNT_ERROR);
  236. }
  237. // 校验订单总金额是否满足起送
  238. $initDeliveryAmount = $this->initialDeliveryService->get();
  239. if ($orderAmount < $initDeliveryAmount) {
  240. throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
  241. }
  242. $dataMain = [
  243. 'market_id' => $marketId,
  244. 'order_num' => $globalOrderId,
  245. 'global_order_id' => $globalOrderId,
  246. 'user_id' => $userId,
  247. 'type' => OrderType::ONLINE,
  248. 'money' => $totalAmount,
  249. 'total_money' => $orderAmount,
  250. 'services_money' => $serviceMoney,
  251. 'coupon_money' => $couponMoney,
  252. 'delivery_money' => $deliveryAmount,
  253. 'delivery_distance' => $deliveryDistance,
  254. 'state' => OrderState::UNPAID,
  255. 'tel' => $userAddr->tel,
  256. 'address' => $userAddr->address.$userAddr->doorplate,
  257. 'lat' => $userAddr->lat,
  258. 'lng' => $userAddr->lng,
  259. 'name' => $userAddr->user_name,
  260. 'plat' => $plat,
  261. 'delivery_time_note' => $deliveryTimeNote
  262. ];
  263. // 生成主订单
  264. $orderMain = OrderMain::query()->create($dataMain);
  265. // 处理子订单
  266. foreach ($dataChildren as $key => &$child) {
  267. $child['order_main_id'] = $globalOrderId;
  268. $orderChild = Order::query()->create($child);
  269. $orderChildId = $orderChild->id;
  270. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  271. $orderGoods['order_id'] = $orderChildId;
  272. $orderGoods['created_at'] = $currentTime;
  273. $orderGoods['updated_at'] = $currentTime;
  274. }
  275. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  276. }
  277. // 判断是否有购买多个特价商品
  278. $check = $this->goodsActivityService->checkOrderActivityCount($dataOrderGoods);
  279. if(!$check){
  280. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '订单中有活动商品超过限购数量', 'data' => json_encode($dataOrderGoods)]);
  281. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT);
  282. }
  283. // 订单成功,做一些处理
  284. // 活动商品购买记录
  285. foreach ($dataOrderGoods as $key => &$goods) {
  286. foreach ($goods as $k => &$goodsItem)
  287. if ($goodsItem['activity_type'] == 2) {
  288. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  289. }
  290. }
  291. // 优惠券红包使用记录
  292. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  293. Db::commit();
  294. // 清除购物车
  295. $this->shopCartUpdateService->doClear($userId, $marketId);
  296. // 记录badge
  297. $this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
  298. // 支付
  299. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  300. } catch (Exception $e) {
  301. Db::rollBack();
  302. // 释redis库存
  303. foreach ($carts as $k => &$cart) {
  304. // 拼接activity_type和goods_id
  305. $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id;
  306. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  307. if (!$redis->exists($inventoryKey)) {
  308. $redis->set($inventoryKey, 0);
  309. } else {
  310. $redis->decrBy($inventoryKey, $cart->num);
  311. }
  312. }
  313. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
  314. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL);
  315. }
  316. }
  317. public function check($globalOrderId, $userId, $state): Model
  318. {
  319. $builder = OrderMain::query()
  320. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  321. if (is_array($state)) {
  322. $builder = $builder->whereIn('state', $state);
  323. } else {
  324. $builder = $builder->where(['state' => $state]);
  325. }
  326. $orderMain = $builder->first();
  327. if (empty($orderMain)) {
  328. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  329. }
  330. return $orderMain;
  331. }
  332. /**
  333. * @inheritDoc
  334. */
  335. public function undo($globalOrderId, $userId)
  336. {
  337. Db::beginTransaction();
  338. try {
  339. // 订单待支付
  340. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  341. $orderMain->state = OrderState::CANCELED;
  342. if (!$orderMain->save()) {
  343. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  344. }
  345. // 退还优惠券
  346. $this->couponService->orderRefundCoupons($globalOrderId);
  347. // 撤销活动商品购买记录
  348. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  349. $orderGoods = OrderGoods::query()
  350. // ->where('activity_type', 2)
  351. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  352. ->get()
  353. ->toArray();
  354. foreach ($orderGoods as $key => &$goods) {
  355. if ($goods['activity_type'] == 2) {
  356. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain['user_id']);
  357. }
  358. }
  359. Db::commit();
  360. // 释redis库存
  361. $redis = ApplicationContext::getContainer()->get(Redis::class);
  362. foreach ($orderGoods as $k => &$goodsItem) {
  363. // 拼接activity_type和goods_id
  364. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  365. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  366. if (!$redis->exists($inventoryKey)) {
  367. $redis->set($inventoryKey, 0);
  368. } else {
  369. $redis->decrBy($inventoryKey, $goodsItem['number']);
  370. }
  371. }
  372. // 记录badge
  373. $orderChildIds = array_values(array_column($orders, 'store_id'));
  374. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  375. return true;
  376. } catch (Exception $e) {
  377. Db::rollBack();
  378. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  379. }
  380. }
  381. public function detailByUser($globalOrderId, $userId)
  382. {
  383. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  384. $orders = Order::query()
  385. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  386. ->with([
  387. 'orderGoods',
  388. 'store'
  389. ])
  390. ->get()->toArray();
  391. return ['order_main' => $orderMain, 'orders' => $orders];
  392. }
  393. /**
  394. * @inheritDoc
  395. */
  396. public function doByPaid($globalOrderId)
  397. {
  398. Db::beginTransaction();
  399. try {
  400. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  401. // 查询订单
  402. $orderMain = OrderMain::query()
  403. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  404. ->first();
  405. // 修改订单、子订单状态
  406. $currentTime = time();
  407. $orderMain->state = OrderState::PAID;
  408. $orderMain->pay_time = $currentTime;
  409. $orderMain->save();;
  410. // 更新商品库存和销量
  411. $orders = Order::query()
  412. ->where(['order_main_id' => $globalOrderId])
  413. ->get()
  414. ->toArray();
  415. // 更新商户销量
  416. $upStoreScore = Store::query()
  417. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  418. ->update(['sales' => Db::raw('sales+1')]);
  419. $orderGoods = OrderGoods::query()
  420. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  421. ->get()
  422. ->toArray();
  423. foreach ($orderGoods as $key => &$goodsItem) {
  424. if ($goodsItem['activity_type'] == 2) { # 活动商品
  425. $goods = GoodsActivity::find($goodsItem['goods_id']);
  426. } else {
  427. $goods = Goods::find($goodsItem['goods_id']);
  428. }
  429. $goods->inventory = $goods->inventory - $goodsItem['number'];
  430. $goods->sales = $goods->sales + $goodsItem['number'];
  431. $goods->save();
  432. // 商品月销
  433. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  434. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  435. } else {
  436. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  437. }
  438. }
  439. Db::commit();
  440. // 释redis库存
  441. $redis = ApplicationContext::getContainer()->get(Redis::class);
  442. foreach ($orderGoods as $k => &$goodsItem) {
  443. // 拼接activity_type和goods_id
  444. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  445. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  446. if (!$redis->exists($inventoryKey)) {
  447. $redis->set($inventoryKey, 0);
  448. } else {
  449. $redis->decrBy($inventoryKey, $goodsItem['number']);
  450. }
  451. }
  452. // 月销流水
  453. $statistics = [];
  454. foreach ($orders as $key => &$order) {
  455. $statistics[] = [
  456. 'money' => $order['money'],
  457. 'user_id' => $order['user_id'],
  458. 'store_id' => $order['store_id'],
  459. 'market_id' => $orderMain->market_id,
  460. 'order_id' => $order['id'],
  461. ];
  462. // 商户月销
  463. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  464. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  465. } else {
  466. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  467. }
  468. }
  469. if (is_array($statistics) && !empty($statistics)) {
  470. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  471. }
  472. return true;
  473. } catch (Exception $e) {
  474. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  475. Db::rollBack();
  476. return false;
  477. }
  478. }
  479. /**
  480. * @inheritDoc
  481. */
  482. public function doPay($globalOrderId, $userId)
  483. {
  484. // 订单待支付
  485. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  486. return $this->paymentService->do(
  487. $orderMain->global_order_id,
  488. $orderMain->money,
  489. $orderMain->user_id,
  490. config('wechat.notify_url.online')
  491. );
  492. }
  493. /**
  494. * @inheritDoc
  495. * @throws Exception
  496. */
  497. public function doDel($globalOrderId, $userId)
  498. {
  499. // 订单完成
  500. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  501. if (!$orderMain->delete()) {
  502. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  503. }
  504. return true;
  505. }
  506. /**
  507. * @inheritDoc
  508. */
  509. public function doApplyRefund($globalOrderId, $userId)
  510. {
  511. // 未接单
  512. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  513. $orderMain->state = OrderState::REFUNDING;
  514. if (!$orderMain->save()) {
  515. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  516. }
  517. // 记录badge
  518. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  519. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
  520. return true;
  521. }
  522. /**
  523. * @inheritDoc
  524. */
  525. public function doComplete($globalOrderId, $userId)
  526. {
  527. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  528. $orderMain->state = OrderState::COMPLETED;
  529. if (!$orderMain->save()) {
  530. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  531. }
  532. // 记录badge
  533. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  534. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
  535. return true;
  536. }
  537. /**
  538. * @inheritDoc
  539. */
  540. public function doRefund($globalOrderId, $userId)
  541. {
  542. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  543. // 微信退款
  544. if ($orderMain->pay_type == Payment::WECHAT) {
  545. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  546. }
  547. }
  548. }