Order.php 15 KB

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