Order.php 14 KB

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