Order.php 15 KB

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