Order.php 16 KB

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