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.

637 lines
25 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 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. // 获取分布式全局ID
  109. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  110. $globalOrderId = $generator->generate();
  111. $mainTable = ApplicationContext::getContainer()->get(OrderMain::class)->getTable();
  112. $childTable = ApplicationContext::getContainer()->get(Order::class)->getTable();
  113. $currentTime = time();
  114. bcscale(6);
  115. // 用户收货地址
  116. // 获取配送费用
  117. $userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId);
  118. $userAddr = $userAddrAndDPrice['address']['address'];
  119. $deliveryAmount = $userAddrAndDPrice['distribution_price'];
  120. $deliveryDistance = $userAddrAndDPrice['delivery_distance'];
  121. // 优惠券数据,当前订单可用个优惠券
  122. $couponRecs = $this->couponRecService->allForOnlineOrderAvailable($userId, $marketId);
  123. $canRealUseCoupons = $couponRecs['available'];
  124. $canRealUseCouponRecIds = array_values(array_column($canRealUseCoupons, 'id'));
  125. if (!empty(array_diff($receiveCouponIds, $canRealUseCouponRecIds))) {
  126. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '订单中有不能使用优惠券的商品', 'data' => json_encode([
  127. 'all_user_coupons_rec' => json_encode($couponRecs),
  128. 'can_real_user_coupons' => json_encode($canRealUseCoupons),
  129. 'receive_coupon_ids' => json_encode($canRealUseCouponRecIds),
  130. ])]);
  131. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON);
  132. }
  133. // 处理购物车数据,计算订单金额、子订单数据处理等
  134. $totalAmount = 0; # 实付金额
  135. $orderAmount = 0; # 订单金额
  136. $dataMain = []; # 主订单
  137. $dataChildren = []; # 子订单
  138. $dataOrderGoods = []; # 订单商品
  139. $storeTypeIds = []; # 订单中的商户类型,用于校验红包
  140. foreach ($storeList as $key => &$storeItem) {
  141. $storeId = $storeItem->store_id;
  142. // 子订单金额
  143. $subAmount = 0;
  144. // 店铺分类
  145. $storeType = Store::query()->where(['id' => $storeId])->value('category_id');
  146. $storeTypeIds[] = (string)$storeType;
  147. // 店铺今天的订单数
  148. $count = Order::query()
  149. ->join($mainTable, ''.$mainTable.'.global_order_id', '=', ''.$childTable.'.order_main_id')
  150. ->where([''.$childTable.'.store_id' => $storeId, ''.$mainTable.'.type' => OrderType::ONLINE])
  151. ->whereBetween(''.$childTable.'.created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
  152. ->count();
  153. // 用户购物车数据
  154. $cartIds = explode(',', $storeItem->cart_ids);
  155. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
  156. foreach ($carts as $k => &$cart) {
  157. // 查个商品,做商品有效的判断检查
  158. $goods = [];
  159. if ($cart->activity_type == 1) {
  160. $goods = Goods::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  161. if (empty($goods)) {
  162. throw new ErrorCodeException(ErrorCode::GOODS_NOT_EXISTS, '['.$cart->goods_id.']');
  163. }
  164. $check = $this->goodsService->check($goods, $cart->num);
  165. if (true !== $check) {
  166. throw new ErrorCodeException($check, '['.$goods->name.'/'.$goods->goods_unit.']');
  167. }
  168. } elseif ($cart->activity_type == 2) {
  169. $goods = GoodsActivity::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  170. if (empty($goods)) {
  171. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_NOT_EXISTS, '['.$cart->goods_id.']');
  172. }
  173. $check = $this->goodsActivityService->check($goods, $cart->num, $userId);
  174. if (true !== $check) {
  175. throw new ErrorCodeException($check, '['.$goods->name.'/'.$goods->goods_unit.']');
  176. }
  177. }
  178. // 算金额
  179. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
  180. $subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
  181. // 订单商品数据
  182. $dataOrderGoods[$storeId][] = [
  183. 'order_id' => 0,
  184. 'goods_id' => $cart->goods_id,
  185. 'activity_type' => $cart->activity_type,
  186. 'number' => $cart->num,
  187. 'price' => $goods->price,
  188. 'original_price' => $goods->original_price,
  189. 'vip_price' => $goods->vip_price,
  190. 'name' => $goods->name ?: '',
  191. 'goods_unit' => $goods->goods_unit ?: '',
  192. 'cover_img' => $goods->cover_img ?: '',
  193. 'spec' => json_encode($goods->spec),
  194. ];
  195. }
  196. // 子订单数据
  197. $dataChildren[] = [
  198. 'order_main_id' => 0,
  199. 'user_id' => $userId,
  200. 'store_id' => $storeId,
  201. 'money' => bcadd((string)$subAmount, '0', 2),
  202. 'oid' => $count + 1,
  203. 'order_num' => date('YmdHis').mt_rand(1000, 9999),
  204. 'note' => $storeItem->note
  205. ];
  206. // 订单金额
  207. $orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
  208. }
  209. // 优惠券的使用
  210. $couponMoney = 0;
  211. if (!empty($receiveCouponIds)) {
  212. // 计算红包折扣金额
  213. foreach ($canRealUseCoupons as $key => &$coupon) {
  214. if (!in_array($coupon->id, $receiveCouponIds)) {
  215. unset($canRealUseCoupons[$key]);
  216. continue;
  217. }
  218. if ($coupon->coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  219. $couponMoney = bcadd($couponMoney, $coupon->coupon->discounts, 2);
  220. } elseif ($coupon->coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  221. $discountRate = bcdiv($coupon->coupon->discounts,10);
  222. $discountRate = bcsub(1,$discountRate);
  223. $discountMoney = bcmul($orderAmount, $discountRate);
  224. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  225. }
  226. }
  227. }
  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. Db::commit();
  292. if (!empty($receiveCouponIds)) {
  293. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  294. }
  295. // 清除购物车
  296. $this->shopCartUpdateService->doClear($userId, $marketId);
  297. // 记录badge
  298. $this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
  299. // 支付
  300. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  301. } catch (Exception $e) {
  302. Db::rollBack();
  303. // 释redis库存
  304. foreach ($carts as $k => &$cart) {
  305. // 拼接activity_type和goods_id
  306. $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id;
  307. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  308. if (!$redis->exists($inventoryKey)) {
  309. $redis->set($inventoryKey, 0);
  310. } else {
  311. $redis->decrBy($inventoryKey, $cart->num);
  312. }
  313. }
  314. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
  315. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL);
  316. }
  317. }
  318. public function check($globalOrderId, $userId, $state): Model
  319. {
  320. $builder = OrderMain::query()
  321. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  322. if (is_array($state)) {
  323. $builder = $builder->whereIn('state', $state);
  324. } else {
  325. $builder = $builder->where(['state' => $state]);
  326. }
  327. $orderMain = $builder->first();
  328. if (empty($orderMain)) {
  329. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  330. }
  331. return $orderMain;
  332. }
  333. /**
  334. * @inheritDoc
  335. */
  336. public function undo($globalOrderId, $userId)
  337. {
  338. Db::beginTransaction();
  339. try {
  340. // 订单待支付
  341. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  342. $orderMain->state = OrderState::CANCELED;
  343. if (!$orderMain->save()) {
  344. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  345. }
  346. // 退还优惠券
  347. $this->couponService->orderRefundCoupons($globalOrderId);
  348. // 撤销活动商品购买记录
  349. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  350. $orderGoods = OrderGoods::query()
  351. // ->where('activity_type', 2)
  352. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  353. ->get()
  354. ->toArray();
  355. foreach ($orderGoods as $key => &$goods) {
  356. if ($goods['activity_type'] == 2) {
  357. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain['user_id']);
  358. }
  359. }
  360. Db::commit();
  361. // 释redis库存
  362. $redis = ApplicationContext::getContainer()->get(Redis::class);
  363. foreach ($orderGoods as $k => &$goodsItem) {
  364. // 拼接activity_type和goods_id
  365. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  366. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  367. if (!$redis->exists($inventoryKey)) {
  368. $redis->set($inventoryKey, 0);
  369. } else {
  370. $redis->decrBy($inventoryKey, $goodsItem['number']);
  371. }
  372. }
  373. // 记录badge
  374. $orderChildIds = array_values(array_column($orders, 'store_id'));
  375. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  376. return true;
  377. } catch (Exception $e) {
  378. Db::rollBack();
  379. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  380. }
  381. }
  382. public function detailByUser($globalOrderId, $userId)
  383. {
  384. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  385. $orders = Order::query()
  386. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  387. ->with([
  388. 'orderGoods',
  389. 'store'
  390. ])
  391. ->get()->toArray();
  392. return ['order_main' => $orderMain, 'orders' => $orders];
  393. }
  394. /**
  395. * @inheritDoc
  396. */
  397. public function doByPaid($globalOrderId)
  398. {
  399. Db::beginTransaction();
  400. try {
  401. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  402. // 查询订单
  403. $orderMain = OrderMain::query()
  404. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  405. ->first();
  406. // 修改订单、子订单状态
  407. $currentTime = time();
  408. $orderMain->state = OrderState::PAID;
  409. $orderMain->pay_time = $currentTime;
  410. $orderMain->save();;
  411. // 更新商品库存和销量
  412. $orders = Order::query()
  413. ->where(['order_main_id' => $globalOrderId])
  414. ->get()
  415. ->toArray();
  416. // 更新商户销量
  417. $upStoreScore = Store::query()
  418. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  419. ->update(['sales' => Db::raw('sales+1')]);
  420. $orderGoods = OrderGoods::query()
  421. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  422. ->get()
  423. ->toArray();
  424. foreach ($orderGoods as $key => &$goodsItem) {
  425. if ($goodsItem['activity_type'] == 2) { # 活动商品
  426. $goods = GoodsActivity::find($goodsItem['goods_id']);
  427. } else {
  428. $goods = Goods::find($goodsItem['goods_id']);
  429. }
  430. $goods->inventory = $goods->inventory - $goodsItem['number'];
  431. $goods->sales = $goods->sales + $goodsItem['number'];
  432. $goods->save();
  433. // 商品月销
  434. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  435. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  436. } else {
  437. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  438. }
  439. }
  440. Db::commit();
  441. // 释redis库存
  442. $redis = ApplicationContext::getContainer()->get(Redis::class);
  443. foreach ($orderGoods as $k => &$goodsItem) {
  444. // 拼接activity_type和goods_id
  445. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  446. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  447. if (!$redis->exists($inventoryKey)) {
  448. $redis->set($inventoryKey, 0);
  449. } else {
  450. $redis->decrBy($inventoryKey, $goodsItem['number']);
  451. }
  452. }
  453. // 月销流水
  454. $statistics = [];
  455. foreach ($orders as $key => &$order) {
  456. $statistics[] = [
  457. 'money' => $order['money'],
  458. 'user_id' => $order['user_id'],
  459. 'store_id' => $order['store_id'],
  460. 'market_id' => $orderMain->market_id,
  461. 'order_id' => $order['id'],
  462. ];
  463. // 商户月销
  464. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  465. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  466. } else {
  467. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  468. }
  469. }
  470. if (is_array($statistics) && !empty($statistics)) {
  471. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  472. }
  473. return true;
  474. } catch (Exception $e) {
  475. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  476. Db::rollBack();
  477. return false;
  478. }
  479. }
  480. /**
  481. * @inheritDoc
  482. */
  483. public function doPay($globalOrderId, $userId)
  484. {
  485. // 订单待支付
  486. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  487. return $this->paymentService->do(
  488. $orderMain->global_order_id,
  489. $orderMain->money,
  490. $orderMain->user_id,
  491. config('wechat.notify_url.online')
  492. );
  493. }
  494. /**
  495. * @inheritDoc
  496. * @throws Exception
  497. */
  498. public function doDel($globalOrderId, $userId)
  499. {
  500. // 订单完成
  501. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  502. if (!$orderMain->delete()) {
  503. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  504. }
  505. return true;
  506. }
  507. /**
  508. * @inheritDoc
  509. */
  510. public function doApplyRefund($globalOrderId, $userId)
  511. {
  512. // 未接单
  513. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  514. $orderMain->state = OrderState::REFUNDING;
  515. if (!$orderMain->save()) {
  516. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  517. }
  518. // 记录badge
  519. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  520. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
  521. return true;
  522. }
  523. /**
  524. * @inheritDoc
  525. */
  526. public function doComplete($globalOrderId, $userId)
  527. {
  528. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  529. $orderMain->state = OrderState::COMPLETED;
  530. if (!$orderMain->save()) {
  531. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  532. }
  533. // 记录badge
  534. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  535. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
  536. return true;
  537. }
  538. /**
  539. * @inheritDoc
  540. */
  541. public function doRefund($globalOrderId, $userId)
  542. {
  543. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  544. // 微信退款
  545. if ($orderMain->pay_type == Payment::WECHAT) {
  546. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  547. }
  548. }
  549. }