Order.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\model;
  13. use app\common\library\paypal\PayPal;
  14. use app\api\model\{Goods as GoodsModel, OrderRefund as OrderRefundModel, Setting as SettingModel};
  15. use app\api\service\{User as UserService, Payment as PaymentService};
  16. use app\api\service\order\{PaySuccess as OrderPaySuccesService, source\Factory as OrderSourceFactory};
  17. use app\common\model\Order as OrderModel;
  18. use app\common\service\{Order as OrderService, order\Complete as OrderCompleteService};
  19. use app\common\enum\{
  20. Setting as SettingEnum,
  21. OrderType as OrderTypeEnum,
  22. order\PayType as OrderPayTypeEnum,
  23. order\PayStatus as PayStatusEnum,
  24. order\OrderStatus as OrderStatusEnum,
  25. // order\DeliveryType as DeliveryTypeEnum,
  26. order\ReceiptStatus as ReceiptStatusEnum,
  27. order\DeliveryStatus as DeliveryStatusEnum
  28. };
  29. use app\common\library\helper;
  30. use cores\exception\BaseException;
  31. /**
  32. * 订单模型
  33. * Class Order
  34. * @package app\api\model
  35. */
  36. class Order extends OrderModel
  37. {
  38. /**
  39. * 隐藏字段
  40. * @var array
  41. */
  42. protected $hidden = [
  43. 'store_id',
  44. 'update_time'
  45. ];
  46. // 信息提示
  47. private $message = '';
  48. /**
  49. * 待支付订单详情
  50. * @param string $orderNo 订单号
  51. * @return null|static
  52. */
  53. public static function getPayDetail(string $orderNo): ?Order
  54. {
  55. return self::detail(['order_no' => $orderNo, 'pay_status' => PayStatusEnum::PENDING, 'is_delete' => 0], ['goods', 'user']);
  56. }
  57. /**
  58. * 订单支付事件
  59. * @param int $payType
  60. * @return bool
  61. */
  62. public function onPay(int $payType = OrderPayTypeEnum::WECHAT): bool
  63. {
  64. // 判断订单状态
  65. $orderSource = OrderSourceFactory::getFactory($this['order_source']);
  66. if (!$orderSource->checkOrderStatusOnPay($this)) {
  67. $this->error = $orderSource->getError();
  68. return false;
  69. }
  70. // 余额支付
  71. if ($payType == OrderPayTypeEnum::BALANCE) {
  72. return $this->onPaymentByBalance($this['order_no']);
  73. }
  74. return true;
  75. }
  76. /**
  77. * 构建支付请求的参数
  78. * @param self $order 订单信息
  79. * @param int $payType 订单支付方式
  80. * @return array
  81. * @throws BaseException
  82. * @throws \think\db\exception\DataNotFoundException
  83. * @throws \think\db\exception\DbException
  84. * @throws \think\db\exception\ModelNotFoundException
  85. */
  86. public function onOrderPayment(self $order, int $payType): array
  87. {
  88. if ($payType == OrderPayTypeEnum::WECHAT) {
  89. return $this->onPaymentByWechat($order);
  90. }
  91. if ($payType == OrderPayTypeEnum::PAYPAL) {
  92. return $this->onPaymentByPaypal($order);
  93. }
  94. return [];
  95. }
  96. /**
  97. * 构建微信支付请求
  98. * @param self $order 订单详情
  99. * @return array
  100. * @throws BaseException
  101. * @throws \think\db\exception\DataNotFoundException
  102. * @throws \think\db\exception\DbException
  103. * @throws \think\db\exception\ModelNotFoundException
  104. */
  105. protected function onPaymentByWechat(self $order): array
  106. {
  107. return PaymentService::wechat(
  108. $order['order_id'],
  109. $order['order_no'],
  110. $order['pay_price'],
  111. OrderTypeEnum::ORDER
  112. );
  113. }
  114. protected function onPaymentByPaypal(self $order): array
  115. {
  116. $conf = [
  117. 'client_id' => 'AS0FH780ZGtSAdpT1NTjwkFzryCPf69rZb_FR9Rt_rZdasB80cmjqTQ6CQELWiFVh_MU9e31CSnyz7Ai', // ClientID
  118. 'secret' => 'EDqRQhgLNHCb5bxld98T8-JJJZKvMIeqxudO7lMwDFOxBfy138PjM5A21FnDNyb3q4yYUh8r7Qr2BnVi', // ClientSecret
  119. 'web_hook_id'=>'3NP026061E6858914',
  120. ];
  121. $pp = new PayPal($conf);
  122. $pp->unify($order['order_no'],$order['pay_price']);
  123. return PaymentService::wechat(
  124. $order['order_id'],
  125. $order['order_no'],
  126. $order['pay_price'],
  127. OrderTypeEnum::ORDER
  128. );
  129. }
  130. /**
  131. * 立即购买:获取订单商品列表
  132. * @param int $goodsId 商品ID
  133. * @param string $goodsSkuId 商品SKU
  134. * @param int $goodsNum 购买数量
  135. * @return mixed
  136. * @throws BaseException
  137. */
  138. public function getOrderGoodsListByNow(int $goodsId, string $goodsSkuId, int $goodsNum)
  139. {
  140. // 获取商品列表
  141. $model = new GoodsModel;
  142. $goodsList = $model->isGoodsGradeMoney(false)->getListByIdsFromApi([$goodsId]);
  143. if ($goodsList->isEmpty()) {
  144. throwError('未找到商品信息');
  145. }
  146. // 隐藏冗余的属性
  147. $goodsList->hidden(array_merge($model->hidden, ['content', 'goods_images', 'images']));
  148. foreach ($goodsList as &$item) {
  149. // 商品sku信息
  150. $goodsInfo['skuInfo'] = GoodsModel::getSkuInfo($item, $goodsSkuId, false);
  151. // 商品单价
  152. $item['goods_price'] = $item['skuInfo']['goods_price'];
  153. // 商品购买数量
  154. $item['total_num'] = $goodsNum;
  155. // 商品SKU索引
  156. $item['goods_sku_id'] = $item['skuInfo']['goods_sku_id'];
  157. // 商品购买总金额
  158. $item['total_price'] = helper::bcmul($item['goods_price'], $goodsNum);
  159. }
  160. return $goodsList;
  161. }
  162. /**
  163. * 余额支付标记订单已支付
  164. * @param string $orderNo 订单号
  165. * @return bool
  166. */
  167. public function onPaymentByBalance(string $orderNo): bool
  168. {
  169. // 获取订单详情
  170. $service = new OrderPaySuccesService($orderNo);
  171. // 发起余额支付
  172. $status = $service->onPaySuccess(OrderPayTypeEnum::BALANCE);
  173. if (!$status) {
  174. $this->error = $service->getError();
  175. }
  176. return $status;
  177. }
  178. /**
  179. * 获取用户订单列表
  180. * @param string $type 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
  181. * @return \think\Paginator
  182. * @throws \think\db\exception\DbException
  183. * @throws BaseException
  184. */
  185. public function getList(string $type = 'all'): \think\Paginator
  186. {
  187. // 筛选条件
  188. $filter = [];
  189. // 订单数据类型
  190. switch ($type) {
  191. case 'all':
  192. break;
  193. case 'payment':
  194. $filter['pay_status'] = PayStatusEnum::PENDING;
  195. $filter['order_status'] = OrderStatusEnum::NORMAL;
  196. break;
  197. case 'delivery':
  198. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  199. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  200. $filter['order_status'] = OrderStatusEnum::NORMAL;
  201. break;
  202. case 'received':
  203. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  204. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  205. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  206. $filter['order_status'] = OrderStatusEnum::NORMAL;
  207. break;
  208. case 'comment':
  209. $filter['is_comment'] = 0;
  210. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  211. break;
  212. }
  213. // 当前用户ID
  214. $userId = UserService::getCurrentLoginUserId();
  215. // 查询列表数据
  216. return $this->with(['goods.image'])
  217. ->where($filter)
  218. ->where('user_id', '=', $userId)
  219. ->where('is_delete', '=', 0)
  220. ->order(['create_time' => 'desc'])
  221. ->paginate(15);
  222. }
  223. /**
  224. * 取消订单
  225. * @return bool|mixed
  226. */
  227. public function cancel()
  228. {
  229. if ($this['delivery_status'] == DeliveryStatusEnum::DELIVERED) {
  230. $this->error = '已发货订单不可取消';
  231. return false;
  232. }
  233. // 订单是否已支付
  234. $isPay = $this['pay_status'] == PayStatusEnum::SUCCESS;
  235. // 提示信息
  236. $this->message = $isPay ? '订单已申请取消,需等待后台审核' : '订单已取消成功';
  237. // 订单取消事件
  238. return $this->transaction(function () use ($isPay) {
  239. // 订单取消事件
  240. $isPay == false && OrderService::cancelEvent($this);
  241. // 更新订单状态: 已付款的订单设置为"待取消", 等待后台审核
  242. return $this->save(['order_status' => $isPay ? OrderStatusEnum::APPLY_CANCEL : OrderStatusEnum::CANCELLED]);
  243. });
  244. }
  245. /**
  246. * 确认收货
  247. * @return bool|mixed
  248. */
  249. public function receipt()
  250. {
  251. // 验证订单是否合法
  252. // 条件1: 订单必须已发货
  253. // 条件2: 订单必须未收货
  254. if ($this['delivery_status'] != 20 || $this['receipt_status'] != 10) {
  255. $this->error = '该订单不合法';
  256. return false;
  257. }
  258. return $this->transaction(function () {
  259. // 更新订单状态
  260. $status = $this->save([
  261. 'receipt_status' => 20,
  262. 'receipt_time' => time(),
  263. 'order_status' => 30
  264. ]);
  265. // 执行订单完成后的操作
  266. $OrderCompleteService = new OrderCompleteService();
  267. $OrderCompleteService->complete([$this], static::$storeId);
  268. return $status;
  269. });
  270. }
  271. /**
  272. * 获取当前用户订单数量
  273. * @param string $type 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
  274. * @return int
  275. * @throws BaseException
  276. */
  277. public function getCount(string $type = 'all'): int
  278. {
  279. // 筛选条件
  280. $filter = [];
  281. // 订单数据类型
  282. switch ($type) {
  283. case 'all':
  284. break;
  285. case 'payment':
  286. $filter['pay_status'] = PayStatusEnum::PENDING;
  287. break;
  288. case 'received':
  289. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  290. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  291. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  292. break;
  293. case 'delivery':
  294. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  295. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  296. $filter['order_status'] = OrderStatusEnum::NORMAL;
  297. break;
  298. case 'comment':
  299. $filter['is_comment'] = 0;
  300. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  301. break;
  302. }
  303. // 当前用户ID
  304. $userId = UserService::getCurrentLoginUserId();
  305. // 查询数据
  306. return $this->where('user_id', '=', $userId)
  307. ->where('order_status', '<>', 20)
  308. ->where($filter)
  309. ->where('is_delete', '=', 0)
  310. ->count();
  311. }
  312. /**
  313. * 获取用户订单详情(含关联数据)
  314. * @param int $orderId 订单ID
  315. * @return Order|array|null
  316. * @throws BaseException
  317. * @throws \think\db\exception\DataNotFoundException
  318. * @throws \think\db\exception\DbException
  319. * @throws \think\db\exception\ModelNotFoundException
  320. */
  321. public static function getUserOrderDetail(int $orderId)
  322. {
  323. // 关联查询
  324. $with = [
  325. 'goods' => ['image', 'goods', 'refund'],
  326. 'address', 'express'
  327. ];
  328. // 查询订单记录
  329. $order = static::getDetail($orderId, $with);
  330. // 该订单是否允许申请售后
  331. $order['isAllowRefund'] = static::isAllowRefund($order);
  332. return $order;
  333. }
  334. /**
  335. * 获取用户订单详情(仅订单记录)
  336. * @param int $orderId
  337. * @param array $with
  338. * @return Order|array|null
  339. * @throws BaseException
  340. */
  341. public static function getDetail(int $orderId, array $with = [])
  342. {
  343. // 查询订单记录
  344. $order = static::detail([
  345. 'order_id' => $orderId,
  346. 'user_id' => UserService::getCurrentLoginUserId(),
  347. ], $with);
  348. empty($order) && throwError('订单不存在');
  349. return $order;
  350. }
  351. /**
  352. * 获取当前用户待处理的订单数量
  353. * @return array
  354. * @throws BaseException
  355. */
  356. public function getTodoCounts(): array
  357. {
  358. return [
  359. 'payment' => $this->getCount('payment'), // 待付款的订单
  360. 'delivery' => $this->getCount('delivery'), // 待发货的订单
  361. 'received' => $this->getCount('received'), // 待收货的订单
  362. 'refund' => OrderRefundModel::getCountByUnderway(), // 进行中的售后单
  363. ];
  364. }
  365. // 返回提示信息
  366. public function getMessage(): string
  367. {
  368. return $this->message;
  369. }
  370. /**
  371. * 当前订单是否允许申请售后
  372. * @param Order $order
  373. * @return bool
  374. * @throws \think\db\exception\DataNotFoundException
  375. * @throws \think\db\exception\DbException
  376. * @throws \think\db\exception\ModelNotFoundException
  377. */
  378. private static function isAllowRefund(self $order): bool
  379. {
  380. // 必须是已发货的订单
  381. if ($order['delivery_status'] != DeliveryStatusEnum::DELIVERED) {
  382. return false;
  383. }
  384. // 允许申请售后期限(天)
  385. $refundDays = SettingModel::getItem(SettingEnum::TRADE)['order']['refund_days'];
  386. // 不允许售后
  387. if ($refundDays == 0) {
  388. return false;
  389. }
  390. // 当前时间超出允许申请售后期限
  391. if (
  392. $order['receipt_status'] == ReceiptStatusEnum::RECEIVED
  393. && time() > ($order->getData('receipt_time') + ((int)$refundDays * 86400))
  394. ) {
  395. return false;
  396. }
  397. return true;
  398. }
  399. }