Order.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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\index\model;
  13. use app\common\library\paypal\PayPal;
  14. use app\index\model\{Goods as GoodsModel, OrderRefund as OrderRefundModel, Setting as SettingModel};
  15. use app\index\service\{User as UserService, Payment as PaymentService};
  16. use app\index\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. $conf = config('paypal');
  122. $pp = new PayPal($conf);
  123. return $pp->unify($order['order_no'], $order['pay_price']);
  124. }
  125. /**
  126. * 立即购买:获取订单商品列表
  127. * @param int $goodsId 商品ID
  128. * @param string $goodsSkuId 商品SKU
  129. * @param int $goodsNum 购买数量
  130. * @return mixed
  131. * @throws BaseException
  132. */
  133. public function getOrderGoodsListByNow(int $goodsId, string $goodsSkuId, int $goodsNum)
  134. {
  135. // 获取商品列表
  136. $model = new GoodsModel;
  137. $goodsList = $model->isGoodsGradeMoney(false)->getListByIdsFromApi([$goodsId]);
  138. if ($goodsList->isEmpty()) {
  139. throwError('未找到商品信息');
  140. }
  141. // 隐藏冗余的属性
  142. $goodsList->hidden(array_merge($model->hidden, ['content', 'goods_images', 'images']));
  143. foreach ($goodsList as &$item) {
  144. // 商品sku信息
  145. $goodsInfo['skuInfo'] = GoodsModel::getSkuInfo($item, $goodsSkuId, false);
  146. // 商品单价
  147. $item['goods_price'] = $item['skuInfo']['goods_price'];
  148. // 商品购买数量
  149. $item['total_num'] = $goodsNum;
  150. // 商品SKU索引
  151. $item['goods_sku_id'] = $item['skuInfo']['goods_sku_id'];
  152. // 商品购买总金额
  153. $item['total_price'] = helper::bcmul($item['goods_price'], $goodsNum);
  154. }
  155. return $goodsList;
  156. }
  157. /**
  158. * 余额支付标记订单已支付
  159. * @param string $orderNo 订单号
  160. * @return bool
  161. */
  162. public function onPaymentByBalance(string $orderNo): bool
  163. {
  164. // 获取订单详情
  165. $service = new OrderPaySuccesService($orderNo);
  166. // 发起余额支付
  167. $status = $service->onPaySuccess(OrderPayTypeEnum::BALANCE);
  168. if (!$status) {
  169. $this->error = $service->getError();
  170. }
  171. return $status;
  172. }
  173. /**
  174. * 获取用户订单列表
  175. * @param string $type 订单类型 (all全部 payment待付款 delivery待发货 received待收货 comment待评价)
  176. * @return \think\Paginator
  177. * @throws \think\db\exception\DbException
  178. * @throws BaseException
  179. */
  180. public function getList(string $type = 'all'): \think\Paginator
  181. {
  182. // 筛选条件
  183. $filter = [];
  184. // 订单数据类型
  185. switch ($type) {
  186. case 'all':
  187. break;
  188. case 'payment':
  189. $filter['pay_status'] = PayStatusEnum::PENDING;
  190. $filter['order_status'] = OrderStatusEnum::NORMAL;
  191. break;
  192. case 'delivery':
  193. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  194. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  195. $filter['order_status'] = OrderStatusEnum::NORMAL;
  196. break;
  197. case 'received':
  198. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  199. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  200. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  201. $filter['order_status'] = OrderStatusEnum::NORMAL;
  202. break;
  203. case 'comment':
  204. $filter['is_comment'] = 0;
  205. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  206. break;
  207. }
  208. // 当前用户ID
  209. $userId = UserService::getCurrentLoginUserId();
  210. // 查询列表数据
  211. return $this->with(['goods.image'])
  212. ->where($filter)
  213. ->where('user_id', '=', $userId)
  214. ->where('is_delete', '=', 0)
  215. ->order(['create_time' => 'desc'])
  216. ->paginate(15);
  217. }
  218. /**
  219. * 取消订单
  220. * @return bool|mixed
  221. */
  222. public function cancel()
  223. {
  224. if ($this['delivery_status'] == DeliveryStatusEnum::DELIVERED) {
  225. $this->error = '已发货订单不可取消';
  226. return false;
  227. }
  228. // 订单是否已支付
  229. $isPay = $this['pay_status'] == PayStatusEnum::SUCCESS;
  230. // 提示信息
  231. $this->message = $isPay ? '订单已申请取消,需等待后台审核' : '订单已取消成功';
  232. // 订单取消事件
  233. return $this->transaction(function () use ($isPay) {
  234. // 订单取消事件
  235. $isPay == false && OrderService::cancelEvent($this);
  236. // 更新订单状态: 已付款的订单设置为"待取消", 等待后台审核
  237. return $this->save(['order_status' => $isPay ? OrderStatusEnum::APPLY_CANCEL : OrderStatusEnum::CANCELLED]);
  238. });
  239. }
  240. /**
  241. * 确认收货
  242. * @return bool|mixed
  243. */
  244. public function receipt()
  245. {
  246. // 验证订单是否合法
  247. // 条件1: 订单必须已发货
  248. // 条件2: 订单必须未收货
  249. if ($this['delivery_status'] != 20 || $this['receipt_status'] != 10) {
  250. $this->error = '该订单不合法';
  251. return false;
  252. }
  253. return $this->transaction(function () {
  254. // 更新订单状态
  255. $status = $this->save([
  256. 'receipt_status' => 20,
  257. 'receipt_time' => time(),
  258. 'order_status' => 30
  259. ]);
  260. // 执行订单完成后的操作
  261. $OrderCompleteService = new OrderCompleteService();
  262. $OrderCompleteService->complete([$this], static::$storeId);
  263. return $status;
  264. });
  265. }
  266. /**
  267. * 获取当前用户订单数量
  268. * @param string $type 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
  269. * @return int
  270. * @throws BaseException
  271. */
  272. public function getCount(string $type = 'all'): int
  273. {
  274. // 筛选条件
  275. $filter = [];
  276. // 订单数据类型
  277. switch ($type) {
  278. case 'all':
  279. break;
  280. case 'payment':
  281. $filter['pay_status'] = PayStatusEnum::PENDING;
  282. break;
  283. case 'received':
  284. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  285. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  286. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  287. break;
  288. case 'delivery':
  289. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  290. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  291. $filter['order_status'] = OrderStatusEnum::NORMAL;
  292. break;
  293. case 'comment':
  294. $filter['is_comment'] = 0;
  295. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  296. break;
  297. }
  298. // 当前用户ID
  299. $userId = UserService::getCurrentLoginUserId();
  300. // 查询数据
  301. return $this->where('user_id', '=', $userId)
  302. ->where('order_status', '<>', 20)
  303. ->where($filter)
  304. ->where('is_delete', '=', 0)
  305. ->count();
  306. }
  307. /**
  308. * 获取用户订单详情(含关联数据)
  309. * @param int $orderId 订单ID
  310. * @return Order|array|null
  311. * @throws BaseException
  312. * @throws \think\db\exception\DataNotFoundException
  313. * @throws \think\db\exception\DbException
  314. * @throws \think\db\exception\ModelNotFoundException
  315. */
  316. public static function getUserOrderDetail(int $orderId)
  317. {
  318. // 关联查询
  319. $with = [
  320. 'goods' => ['image', 'goods', 'refund'],
  321. 'address', 'express'
  322. ];
  323. // 查询订单记录
  324. $order = static::getDetail($orderId, $with);
  325. // 该订单是否允许申请售后
  326. $order['isAllowRefund'] = static::isAllowRefund($order);
  327. return $order;
  328. }
  329. /**
  330. * 获取用户订单详情(仅订单记录)
  331. * @param int $orderId
  332. * @param array $with
  333. * @return Order|array|null
  334. * @throws BaseException
  335. */
  336. public static function getDetail(int $orderId, array $with = [])
  337. {
  338. // 查询订单记录
  339. $order = static::detail([
  340. 'order_id' => $orderId,
  341. 'user_id' => UserService::getCurrentLoginUserId(),
  342. ], $with);
  343. empty($order) && throwError('订单不存在');
  344. return $order;
  345. }
  346. /**
  347. * 获取当前用户待处理的订单数量
  348. * @return array
  349. * @throws BaseException
  350. */
  351. public function getTodoCounts(): array
  352. {
  353. return [
  354. 'payment' => $this->getCount('payment'), // 待付款的订单
  355. 'delivery' => $this->getCount('delivery'), // 待发货的订单
  356. 'received' => $this->getCount('received'), // 待收货的订单
  357. 'refund' => OrderRefundModel::getCountByUnderway(), // 进行中的售后单
  358. ];
  359. }
  360. // 返回提示信息
  361. public function getMessage(): string
  362. {
  363. return $this->message;
  364. }
  365. /**
  366. * 当前订单是否允许申请售后
  367. * @param Order $order
  368. * @return bool
  369. * @throws \think\db\exception\DataNotFoundException
  370. * @throws \think\db\exception\DbException
  371. * @throws \think\db\exception\ModelNotFoundException
  372. */
  373. private static function isAllowRefund(self $order): bool
  374. {
  375. // 必须是已发货的订单
  376. if ($order['delivery_status'] != DeliveryStatusEnum::DELIVERED) {
  377. return false;
  378. }
  379. // 允许申请售后期限(天)
  380. $refundDays = SettingModel::getItem(SettingEnum::TRADE)['order']['refund_days'];
  381. // 不允许售后
  382. if ($refundDays == 0) {
  383. return false;
  384. }
  385. // 当前时间超出允许申请售后期限
  386. if (
  387. $order['receipt_status'] == ReceiptStatusEnum::RECEIVED
  388. && time() > ($order->getData('receipt_time') + ((int)$refundDays * 86400))
  389. ) {
  390. return false;
  391. }
  392. return true;
  393. }
  394. }