Checkout.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. <?php
  2. namespace app\api\service\order;
  3. use app\api\model\Order as OrderModel;
  4. use app\api\model\User;
  5. use app\api\model\User as UserModel;
  6. use app\api\model\Goods as GoodsModel;
  7. use app\api\model\Setting as SettingModel;
  8. use app\api\model\store\Shop as ShopModel;
  9. use app\api\model\UserCoupon as UserCouponModel;
  10. use app\api\model\dealer\Order as DealerOrderModel;
  11. use app\api\service\User as UserService;
  12. use app\api\service\Payment as PaymentService;
  13. use app\api\service\coupon\GoodsDeduct as GoodsDeductService;
  14. use app\api\service\points\GoodsDeduct as PointsDeductService;
  15. use app\api\service\order\source\checkout\Factory as CheckoutFactory;
  16. use app\common\library\helper;
  17. use app\common\enum\OrderType as OrderTypeEnum;
  18. use app\common\enum\DeliveryType as DeliveryTypeEnum;
  19. use app\common\enum\order\PayType as PayTypeEnum;
  20. use app\common\service\goods\source\Factory as StockFactory;
  21. use app\common\enum\order\OrderSource as OrderSourceEnum;
  22. use app\common\service\delivery\Express as ExpressService;
  23. use app\common\exception\BaseException;
  24. /**
  25. * 订单结算台服务类
  26. * Class Checkout
  27. * @package app\api\service\order
  28. */
  29. class Checkout
  30. {
  31. /* $model OrderModel 订单模型 */
  32. public $model;
  33. // 当前小程序id
  34. private $wxapp_id;
  35. /* @var UserModel $user 当前用户信息 */
  36. private $user;
  37. // 订单结算商品列表
  38. private $goodsList = [];
  39. // 错误信息
  40. protected $error;
  41. /**
  42. * 订单结算api参数
  43. * @var array
  44. */
  45. private $param = [
  46. 'delivery' => null, // 配送方式
  47. 'shop_id' => 0, // 自提门店id
  48. 'linkman' => '', // 自提联系人
  49. 'phone' => '', // 自提联系电话
  50. 'coupon_id' => 0, // 优惠券id
  51. 'is_use_points' => 0, // 是否使用积分抵扣
  52. 'remark' => '', // 买家留言
  53. 'is_upgrade'=> 0,
  54. 'pay_type' => PayTypeEnum::WECHAT, // 支付方式
  55. ];
  56. /**
  57. * 订单结算的规则
  58. * @var array
  59. */
  60. private $checkoutRule = [
  61. 'is_user_grade' => true, // 会员等级折扣
  62. 'is_coupon' => true, // 优惠券抵扣
  63. 'is_use_points' => true, // 是否使用积分抵扣
  64. 'is_dealer' => true, // 是否开启分销
  65. ];
  66. /**
  67. * 订单来源
  68. * @var array
  69. */
  70. private $orderSource = [
  71. 'source' => OrderSourceEnum::MASTER,
  72. 'source_id' => 0,
  73. ];
  74. /**
  75. * 订单结算数据
  76. * @var array
  77. */
  78. private $orderData = [];
  79. /**
  80. * 构造函数
  81. * Checkout constructor.
  82. */
  83. public function __construct()
  84. {
  85. $this->model = new OrderModel;
  86. $this->wxapp_id = OrderModel::$wxapp_id;
  87. }
  88. /**
  89. * 设置结算台请求的参数
  90. * @param $param
  91. * @return array
  92. */
  93. public function setParam($param)
  94. {
  95. $this->param = array_merge($this->param, $param);
  96. return $this->getParam();
  97. }
  98. /**
  99. * 获取结算台请求的参数
  100. * @return array
  101. */
  102. public function getParam()
  103. {
  104. return $this->param;
  105. }
  106. /**
  107. * 订单结算的规则
  108. * @param $data
  109. * @return $this
  110. */
  111. public function setCheckoutRule($data)
  112. {
  113. $this->checkoutRule = array_merge($this->checkoutRule, $data);
  114. return $this;
  115. }
  116. /**
  117. * 设置订单来源(普通订单、砍价订单、秒杀订单)
  118. * @param $data
  119. * @return $this
  120. */
  121. public function setOrderSource($data)
  122. {
  123. $this->orderSource = array_merge($this->orderSource, $data);
  124. return $this;
  125. }
  126. /**
  127. * 订单确认-结算台
  128. * @param $user
  129. * @param $goodsList
  130. * @return array
  131. * @throws BaseException
  132. * @throws \think\Exception
  133. * @throws \think\db\exception\DataNotFoundException
  134. * @throws \think\db\exception\ModelNotFoundException
  135. * @throws \think\exception\DbException
  136. */
  137. public function onCheckout($user, $goodsList)
  138. {
  139. $this->user = $user;
  140. $this->goodsList = $goodsList;
  141. // 订单确认-立即购买
  142. return $this->checkout();
  143. }
  144. /**
  145. * 订单结算台
  146. * @return array
  147. * @throws BaseException
  148. * @throws \think\Exception
  149. * @throws \think\db\exception\DataNotFoundException
  150. * @throws \think\db\exception\ModelNotFoundException
  151. * @throws \think\exception\DbException
  152. */
  153. private function checkout()
  154. {
  155. // 整理订单数据
  156. $this->orderData = $this->getOrderData();
  157. // 验证商品状态, 是否允许购买
  158. $this->validateGoodsList();
  159. // 订单商品总数量
  160. $orderTotalNum = helper::getArrayColumnSum($this->goodsList, 'total_num');
  161. // 设置订单商品会员折扣价
  162. $this->setOrderGoodsGradeMoney();
  163. // 设置订单商品总金额(不含优惠折扣)
  164. $this->setOrderTotalPrice();
  165. // 计算可用积分抵扣
  166. $this->setOrderPoints();
  167. // 当前用户可用的优惠券列表
  168. $couponList = $this->getUserCouponList($this->orderData['order_total_price']);
  169. // 计算优惠券抵扣
  170. $this->setOrderCouponMoney($couponList, $this->param['coupon_id']);
  171. // 计算订单商品的实际付款金额
  172. $this->setOrderGoodsPayPrice();
  173. // 设置默认配送方式
  174. !$this->param['delivery'] && $this->param['delivery'] = current(SettingModel::getItem('store')['delivery_type']);
  175. // 处理配送方式
  176. if ($this->param['delivery'] == DeliveryTypeEnum::EXPRESS) {
  177. $this->setOrderExpress();
  178. } elseif ($this->param['delivery'] == DeliveryTypeEnum::EXTRACT) {
  179. $this->param['shop_id'] > 0 && $this->orderData['extract_shop'] = ShopModel::detail($this->param['shop_id']);
  180. }
  181. // 计算订单最终金额
  182. $this->setOrderPayPrice();
  183. // 计算订单积分赠送数量
  184. $this->setOrderPointsBonus();
  185. // 返回订单数据
  186. return array_merge([
  187. 'goods_list' => array_values($this->goodsList), // 商品信息
  188. 'order_total_num' => $orderTotalNum, // 商品总数量
  189. 'coupon_list' => array_values($couponList), // 优惠券列表
  190. 'has_error' => $this->hasError(),
  191. 'error_msg' => $this->getError(),
  192. ], $this->orderData);
  193. }
  194. /**
  195. * 计算订单可用积分抵扣
  196. * @return bool
  197. */
  198. private function setOrderPoints()
  199. {
  200. // 设置默认的商品积分抵扣信息
  201. $this->setDefaultGoodsPoints();
  202. // 积分设置
  203. $setting = SettingModel::getItem('points');
  204. // 条件:后台开启下单使用积分抵扣
  205. if (!$setting['is_shopping_discount'] || !$this->checkoutRule['is_use_points']) {
  206. return false;
  207. }
  208. // 条件:订单金额满足[?]元
  209. if (helper::bccomp($setting['discount']['full_order_price'], $this->orderData['order_total_price']) === 1) {
  210. return false;
  211. }
  212. // 计算订单商品最多可抵扣的积分数量
  213. $this->setOrderGoodsMaxPointsNum();
  214. // 订单最多可抵扣的积分总数量
  215. $maxPointsNumCount = helper::getArrayColumnSum($this->goodsList, 'max_points_num');
  216. // 实际可抵扣的积分数量
  217. $actualPointsNum = min($maxPointsNumCount, $this->user['points']);
  218. if ($actualPointsNum < 1) {
  219. return false;
  220. }
  221. // 计算订单商品实际抵扣的积分数量和金额
  222. $GoodsDeduct = new PointsDeductService($this->goodsList);
  223. $GoodsDeduct->setGoodsPoints($maxPointsNumCount, $actualPointsNum);
  224. // 积分抵扣总金额
  225. $orderPointsMoney = helper::getArrayColumnSum($this->goodsList, 'points_money');
  226. $this->orderData['points_money'] = helper::number2($orderPointsMoney);
  227. // 积分抵扣总数量
  228. $this->orderData['points_num'] = $actualPointsNum;
  229. // 允许积分抵扣
  230. $this->orderData['is_allow_points'] = true;
  231. return true;
  232. }
  233. /**
  234. * 计算订单商品最多可抵扣的积分数量
  235. * @return bool
  236. */
  237. private function setOrderGoodsMaxPointsNum()
  238. {
  239. // 积分设置
  240. $setting = SettingModel::getItem('points');
  241. foreach ($this->goodsList as &$goods) {
  242. // 商品不允许积分抵扣
  243. if (!$goods['is_points_discount']) continue;
  244. // 积分抵扣比例
  245. $deductionRatio = helper::bcdiv($setting['discount']['max_money_ratio'], 100);
  246. // 最多可抵扣的金额
  247. $maxPointsMoney = helper::bcmul($goods['total_price'], $deductionRatio);
  248. // 最多可抵扣的积分数量
  249. $goods['max_points_num'] = helper::bcdiv($maxPointsMoney, $setting['discount']['discount_ratio'], 0);
  250. }
  251. return true;
  252. }
  253. /**
  254. * 设置默认的商品积分抵扣信息
  255. * @return bool
  256. */
  257. private function setDefaultGoodsPoints()
  258. {
  259. foreach ($this->goodsList as &$goods) {
  260. // 最多可抵扣的积分数量
  261. $goods['max_points_num'] = 0;
  262. // 实际抵扣的积分数量
  263. $goods['points_num'] = 0;
  264. // 实际抵扣的金额
  265. $goods['points_money'] = 0.00;
  266. }
  267. return true;
  268. }
  269. /**
  270. * 整理订单数据(结算台初始化)
  271. * @return array
  272. */
  273. private function getOrderData()
  274. {
  275. // 系统支持的配送方式 (后台设置)
  276. $deliveryType = SettingModel::getItem('store')['delivery_type'];
  277. // 积分设置
  278. $pointsSetting = SettingModel::getItem('points');
  279. return [
  280. // 配送类型
  281. 'delivery' => $this->param['delivery'] > 0 ? $this->param['delivery'] : $deliveryType[0],
  282. // 默认地址
  283. 'address' => $this->user['address_default'],
  284. // 是否存在收货地址
  285. 'exist_address' => $this->user['address_id'] > 0,
  286. // 配送费用
  287. 'express_price' => 0.00,
  288. // 当前用户收货城市是否存在配送规则中
  289. 'intra_region' => true,
  290. // 自提门店信息
  291. 'extract_shop' => [],
  292. // 是否允许使用积分抵扣
  293. 'is_allow_points' => false,
  294. // 是否使用积分抵扣
  295. 'is_use_points' => $this->param['is_use_points'],
  296. // 是否升级商品订单
  297. 'is_upgrade' => $this->param['is_upgrade'],
  298. // 积分抵扣金额
  299. 'points_money' => 0.00,
  300. // 赠送的积分数量
  301. 'points_bonus' => 0,
  302. // 支付方式
  303. 'pay_type' => $this->param['pay_type'],
  304. // 系统设置
  305. 'setting' => [
  306. 'delivery' => $deliveryType, // 支持的配送方式
  307. 'points_name' => $pointsSetting['points_name'], // 积分名称
  308. 'points_describe' => $pointsSetting['describe'], // 积分说明
  309. ],
  310. // 记忆的自提联系方式
  311. 'last_extract' => UserService::getLastExtract($this->user['user_id']),
  312. // todo: delete - 兼容处理
  313. 'deliverySetting' => $deliveryType,
  314. ];
  315. }
  316. /**
  317. * 当前用户可用的优惠券列表
  318. * @param $orderTotalPrice
  319. * @return mixed
  320. * @throws \think\db\exception\DataNotFoundException
  321. * @throws \think\db\exception\ModelNotFoundException
  322. * @throws \think\exception\DbException
  323. */
  324. private function getUserCouponList($orderTotalPrice)
  325. {
  326. // 是否开启优惠券折扣
  327. if (!$this->checkoutRule['is_coupon']) {
  328. return [];
  329. }
  330. return UserCouponModel::getUserCouponList($this->user['user_id'], $orderTotalPrice);
  331. }
  332. /**
  333. * 验证订单商品的状态
  334. * @return bool
  335. */
  336. private function validateGoodsList()
  337. {
  338. $Checkout = CheckoutFactory::getFactory(
  339. $this->user,
  340. $this->goodsList,
  341. $this->orderSource['source']
  342. );
  343. $status = $Checkout->validateGoodsList();
  344. $status == false && $this->setError($Checkout->getError());
  345. return $status;
  346. }
  347. /**
  348. * 设置订单的商品总金额(不含优惠折扣)
  349. */
  350. private function setOrderTotalPrice()
  351. {
  352. // 订单商品的总金额(不含优惠券折扣)
  353. $this->orderData['order_total_price'] = helper::number2(helper::getArrayColumnSum($this->goodsList, 'total_price'));
  354. }
  355. /**
  356. * 设置订单的实际支付金额(含配送费)
  357. */
  358. private function setOrderPayPrice()
  359. {
  360. // 订单金额(含优惠折扣)
  361. $this->orderData['order_price'] = helper::number2(helper::getArrayColumnSum($this->goodsList, 'total_pay_price'));
  362. // 订单实付款金额(订单金额 + 运费)
  363. $this->orderData['order_pay_price'] = helper::number2(helper::bcadd($this->orderData['order_price'], $this->orderData['express_price']));
  364. }
  365. /**
  366. * 计算订单积分赠送数量
  367. * @return bool
  368. */
  369. private function setOrderPointsBonus()
  370. {
  371. // 初始化商品积分赠送数量
  372. foreach ($this->goodsList as &$goods) {
  373. $goods['points_bonus'] = 0;
  374. }
  375. // 积分设置
  376. $setting = SettingModel::getItem('points');
  377. // 条件:后台开启开启购物送积分
  378. if (!$setting['is_shopping_gift']) {
  379. return false;
  380. }
  381. // 设置商品积分赠送数量
  382. foreach ($this->goodsList as &$goods) {
  383. // 积分赠送比例
  384. $ratio = $setting['gift_ratio'] / 100;
  385. // 计算抵扣积分数量
  386. $goods['points_bonus'] = !$goods['is_points_gift'] ? 0 : helper::bcmul($goods['total_pay_price'], $ratio, 0);
  387. }
  388. // 订单积分赠送数量
  389. $this->orderData['points_bonus'] = helper::getArrayColumnSum($this->goodsList, 'points_bonus');
  390. return true;
  391. }
  392. /**
  393. * 计算订单商品的实际付款金额
  394. * @return bool
  395. */
  396. private function setOrderGoodsPayPrice()
  397. {
  398. // 商品总价 - 优惠抵扣
  399. foreach ($this->goodsList as &$goods) {
  400. // 减去优惠券抵扣金额
  401. $value = helper::bcsub($goods['total_price'], $goods['coupon_money'],8);
  402. // 减去积分抵扣金额
  403. if ($this->orderData['is_allow_points'] && $this->orderData['is_use_points']) {
  404. $value = helper::bcsub($value, $goods['points_money'],8);
  405. }
  406. $goods['total_pay_price'] = round($value,1);
  407. }
  408. return true;
  409. }
  410. /**
  411. * 设置订单商品会员折扣价
  412. * @return bool
  413. */
  414. private function setOrderGoodsGradeMoney()
  415. {
  416. // 设置默认数据
  417. helper::setDataAttribute($this->goodsList, [
  418. // 标记参与会员折扣
  419. 'is_user_grade' => false,
  420. // 会员等级抵扣的金额
  421. 'grade_ratio' => 0,
  422. // 会员折扣的商品单价
  423. 'grade_goods_price' => 0.00,
  424. // 会员折扣的总额差
  425. 'grade_total_money' => 0.00,
  426. ], true);
  427. // 是否开启会员等级折扣
  428. if (!$this->checkoutRule['is_user_grade']) {
  429. return false;
  430. }
  431. // 会员等级状态
  432. if (!(
  433. $this->user['grade_id'] > 0 && !empty($this->user['grade'])
  434. && !$this->user['grade']['is_delete'] && $this->user['grade']['status']
  435. )) {
  436. return false;
  437. }
  438. // 计算抵扣金额
  439. foreach ($this->goodsList as &$goods) {
  440. // 判断商品是否参与会员折扣
  441. if (!$goods['is_enable_grade']) {
  442. continue;
  443. }
  444. // 商品单独设置了会员折扣
  445. if ($goods['is_alone_grade'] && isset($goods['alone_grade_equity'][$this->user['grade_id']])) {
  446. // 折扣比例
  447. $discountRatio = helper::bcdiv($goods['alone_grade_equity'][$this->user['grade_id']], 10,8);
  448. } else {
  449. // 折扣比例
  450. $discountRatio = helper::bcdiv($this->user['grade']['equity']['discount'], 10,8);
  451. }
  452. if ($discountRatio > 0) {
  453. // 会员折扣后的商品总金额
  454. $gradeTotalPrice = max(0.01, helper::bcmul($goods['total_price'], $discountRatio,1));
  455. helper::setDataAttribute($goods, [
  456. 'is_user_grade' => true,
  457. 'grade_ratio' => $discountRatio,
  458. 'grade_goods_price' => helper::number2(helper::bcmul($goods['goods_price'], $discountRatio,1)),
  459. 'grade_total_money' => helper::number2(helper::bcsub($goods['total_price'], $gradeTotalPrice,1)),
  460. 'total_price' => $gradeTotalPrice,
  461. ], false);
  462. }
  463. }
  464. return true;
  465. }
  466. /**
  467. * 设置订单优惠券抵扣信息
  468. * @param array $couponList 当前用户可用的优惠券列表
  469. * @param int $couponId 当前选择的优惠券id
  470. * @return bool
  471. * @throws BaseException
  472. */
  473. private function setOrderCouponMoney($couponList, $couponId)
  474. {
  475. // 设置默认数据:订单信息
  476. helper::setDataAttribute($this->orderData, [
  477. 'coupon_id' => 0, // 用户优惠券id
  478. 'coupon_money' => 0, // 优惠券抵扣金额
  479. ], false);
  480. // 设置默认数据:订单商品列表
  481. helper::setDataAttribute($this->goodsList, [
  482. 'coupon_money' => 0, // 优惠券抵扣金额
  483. ], true);
  484. // 是否开启优惠券折扣
  485. if (!$this->checkoutRule['is_coupon']) {
  486. return false;
  487. }
  488. // 如果没有可用的优惠券,直接返回
  489. if ($couponId <= 0 || empty($couponList)) {
  490. return true;
  491. }
  492. // 获取优惠券信息
  493. $couponInfo = helper::getArrayItemByColumn($couponList, 'user_coupon_id', $couponId);
  494. if ($couponInfo == false) {
  495. throw new BaseException(['msg' => '未找到优惠券信息']);
  496. }
  497. // 计算订单商品优惠券抵扣金额
  498. $goodsListTemp = helper::getArrayColumns($this->goodsList, ['total_price']);
  499. $CouponMoney = new GoodsDeductService;
  500. $completed = $CouponMoney->setGoodsCouponMoney($goodsListTemp, $couponInfo['reduced_price']);
  501. // 分配订单商品优惠券抵扣金额
  502. foreach ($this->goodsList as $key => &$goods) {
  503. $goods['coupon_money'] = $completed[$key]['coupon_money'] / 100;
  504. }
  505. // 记录订单优惠券信息
  506. $this->orderData['coupon_id'] = $couponId;
  507. $this->orderData['coupon_money'] = helper::number2($CouponMoney->getActualReducedMoney() / 100);
  508. return true;
  509. }
  510. /**
  511. * 订单配送-快递配送
  512. * @return bool
  513. * @throws \think\db\exception\DataNotFoundException
  514. * @throws \think\db\exception\ModelNotFoundException
  515. * @throws \think\exception\DbException
  516. */
  517. private function setOrderExpress()
  518. {
  519. // 设置默认数据:配送费用
  520. helper::setDataAttribute($this->goodsList, [
  521. 'express_price' => 0,
  522. ], true);
  523. // 当前用户收货城市id
  524. $cityId = $this->user['address_default'] ? $this->user['address_default']['city_id'] : null;
  525. // 初始化配送服务类
  526. $ExpressService = new ExpressService($cityId, $this->goodsList, OrderTypeEnum::MASTER);
  527. // 验证商品是否在配送范围
  528. if (!$isIntraRegion = $ExpressService->isIntraRegion()) {
  529. $notInRuleGoodsName = $ExpressService->getNotInRuleGoodsName();
  530. $this->setError("很抱歉,您的收货地址不在商品 [{$notInRuleGoodsName}] 的配送范围内");
  531. }
  532. // 订单总运费金额
  533. $this->orderData['intra_region'] = $isIntraRegion;
  534. $this->orderData['express_price'] = $ExpressService->getDeliveryFee();
  535. return true;
  536. }
  537. /**
  538. * 创建新订单
  539. * @param array $order 订单信息
  540. * @return bool
  541. * @throws \Exception
  542. */
  543. public function createOrder($order)
  544. {
  545. // 表单验证
  546. if (!$this->validateOrderForm($order, $this->param['linkman'], $this->param['phone'])) {
  547. return false;
  548. }
  549. // 创建新的订单
  550. $status = $this->model->transaction(function () use ($order) {
  551. // 创建订单事件
  552. return $this->createOrderEvent($order);
  553. });
  554. // 余额支付标记订单已支付
  555. if ($status && $order['pay_type'] == PayTypeEnum::BALANCE) {
  556. // 验证密码
  557. $payPassword = input('pay_password','');
  558. if(empty($payPassword)){
  559. $this->error = '请填写支付密码';
  560. return false;
  561. }
  562. $userPayPassword = User::where(['user_id'=> $this->model['user_id'],'wxapp_id'=>$this->model['wxapp_id']])
  563. ->value('pay_password');
  564. if(empty($userPayPassword)){
  565. $this->error = '请先设置支付密码';
  566. return false;
  567. }
  568. if(makePassword($payPassword) != $userPayPassword){
  569. $this->error = '支付密码错误';
  570. return false;
  571. }
  572. // 检查是否购买的低级别升级套餐
  573. if($this->model['is_upgrade']==1){
  574. $grade = User::alias('a')
  575. ->where(['a.user_id'=> $this->model['user_id'],'a.wxapp_id'=>$this->model['wxapp_id']])
  576. ->join('user_grade ug','ug.grade_id=a.grade_id','left')
  577. ->field('a.user_id,ug.upgrade')
  578. ->find();
  579. $grade = $grade?$grade->toArray() : [];
  580. $upgrade = isset($grade['upgrade']) && !is_array($grade['upgrade'])? json_decode($grade['upgrade'], true) : [];
  581. $upgradeMoney = isset($upgrade['expend_money'])?$upgrade['expend_money'] : 0;
  582. if($upgradeMoney>=$this->model['total_price']){
  583. $this->error = '当前级别不能购买低级别套餐';
  584. return false;
  585. }
  586. }
  587. return $this->model->onPaymentByBalance($this->model['order_no']);
  588. }
  589. return $status;
  590. }
  591. /**
  592. * 创建订单事件
  593. * @param $order
  594. * @return bool
  595. * @throws BaseException
  596. * @throws \think\exception\DbException
  597. * @throws \Exception
  598. */
  599. private function createOrderEvent($order)
  600. {
  601. // 新增订单记录
  602. $status = $this->add($order, $this->param['remark']);
  603. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  604. // 记录收货地址
  605. $this->saveOrderAddress($order['address']);
  606. } elseif ($order['delivery'] == DeliveryTypeEnum::EXTRACT) {
  607. // 记录自提信息
  608. $this->saveOrderExtract($this->param['linkman'], $this->param['phone']);
  609. }
  610. // 保存订单商品信息
  611. $this->saveOrderGoods($order);
  612. // 更新商品库存 (针对下单减库存的商品)
  613. $this->updateGoodsStockNum($order);
  614. // 设置优惠券使用状态
  615. UserCouponModel::setIsUse($this->param['coupon_id']);
  616. // 积分抵扣情况下扣除用户积分
  617. if ($order['is_allow_points'] && $order['is_use_points'] && $order['points_num'] > 0) {
  618. $describe = "用户消费:{$this->model['order_no']}";
  619. $this->user->setIncPoints(-$order['points_num'], $describe);
  620. }
  621. // 获取订单详情
  622. $detail = OrderModel::getUserOrderDetail($this->model['order_id'], $this->user['user_id']);
  623. // 记录分销商订单
  624. $this->checkoutRule['is_dealer'] && DealerOrderModel::createOrder($detail);
  625. return $status;
  626. }
  627. /**
  628. * 构建支付请求的参数
  629. * @return array
  630. * @throws BaseException
  631. * @throws \think\exception\DbException
  632. */
  633. public function onOrderPayment()
  634. {
  635. return PaymentService::orderPayment($this->user, $this->model, $this->param['pay_type']);
  636. }
  637. /**
  638. * 表单验证 (订单提交)
  639. * @param array $order 订单信息
  640. * @param string $linkman 联系人
  641. * @param string $phone 联系电话
  642. * @return bool
  643. */
  644. private function validateOrderForm(&$order, $linkman, $phone)
  645. {
  646. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  647. if (empty($order['address'])) {
  648. $this->error = '您还没有选择配送地址';
  649. return false;
  650. }
  651. }
  652. if ($order['delivery'] == DeliveryTypeEnum::EXTRACT) {
  653. if (empty($order['extract_shop'])) {
  654. $this->error = '您还没有选择自提门店';
  655. return false;
  656. }
  657. if (empty($linkman) || empty($phone)) {
  658. $this->error = '您还没有填写联系人和电话';
  659. return false;
  660. }
  661. }
  662. // 余额支付时判断用户余额是否足够
  663. if ($order['pay_type'] == PayTypeEnum::BALANCE) {
  664. if ($this->user['balance'] < $order['order_pay_price']) {
  665. $this->error = '您的余额不足,无法使用余额支付';
  666. return false;
  667. }
  668. }
  669. return true;
  670. }
  671. /**
  672. * 当前订单是否存在和使用积分抵扣
  673. * @param $order
  674. * @return bool
  675. */
  676. private function isExistPointsDeduction($order)
  677. {
  678. return $order['is_allow_points'] && $order['is_use_points'];
  679. }
  680. /**
  681. * 新增订单记录
  682. * @param $order
  683. * @param string $remark
  684. * @return false|int
  685. */
  686. private function add($order, $remark = '')
  687. {
  688. // 当前订单是否存在和使用积分抵扣
  689. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  690. // 订单数据
  691. $data = [
  692. 'user_id' => $this->user['user_id'],
  693. 'order_no' => $this->model->orderNo(),
  694. 'total_price' => $order['order_total_price'],
  695. 'order_price' => $order['order_price'],
  696. 'coupon_id' => $order['coupon_id'],
  697. 'coupon_money' => $order['coupon_money'],
  698. 'points_money' => $isExistPointsDeduction ? $order['points_money'] : 0.00,
  699. 'points_num' => $isExistPointsDeduction ? $order['points_num'] : 0,
  700. 'pay_price' => $order['order_pay_price'],
  701. 'delivery_type' => $order['delivery'],
  702. 'pay_type' => $order['pay_type'],
  703. 'is_upgrade' => isset($order['is_upgrade'])? $order['is_upgrade'] : 0,
  704. 'buyer_remark' => trim($remark),
  705. 'order_source' => $this->orderSource['source'],
  706. 'order_source_id' => $this->orderSource['source_id'],
  707. 'points_bonus' => $order['points_bonus'],
  708. 'wxapp_id' => $this->wxapp_id,
  709. ];
  710. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  711. $data['express_price'] = $order['express_price'];
  712. } elseif ($order['delivery'] == DeliveryTypeEnum::EXTRACT) {
  713. $data['extract_shop_id'] = $order['extract_shop']['shop_id'];
  714. }
  715. // 保存订单记录
  716. return $this->model->save($data);
  717. }
  718. /**
  719. * 保存订单商品信息
  720. * @param $order
  721. * @return int
  722. */
  723. private function saveOrderGoods($order)
  724. {
  725. // 当前订单是否存在和使用积分抵扣
  726. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  727. // 订单商品列表
  728. $goodsList = [];
  729. foreach ($order['goods_list'] as $goods) {
  730. /* @var GoodsModel $goods */
  731. $item = [
  732. 'user_id' => $this->user['user_id'],
  733. 'wxapp_id' => $this->wxapp_id,
  734. 'goods_id' => $goods['goods_id'],
  735. 'goods_name' => $goods['goods_name'],
  736. 'image_id' => $goods['image'][0]['image_id'],
  737. 'deduct_stock_type' => $goods['deduct_stock_type'],
  738. 'spec_type' => $goods['spec_type'],
  739. 'spec_sku_id' => $goods['goods_sku']['spec_sku_id'],
  740. 'goods_sku_id' => $goods['goods_sku']['goods_sku_id'],
  741. 'goods_attr' => $goods['goods_sku']['goods_attr'],
  742. 'content' => $goods['content'],
  743. 'goods_no' => $goods['goods_sku']['goods_no'],
  744. 'goods_price' => $goods['goods_sku']['goods_price'],
  745. 'line_price' => $goods['goods_sku']['line_price'],
  746. 'goods_weight' => $goods['goods_sku']['goods_weight'],
  747. 'is_user_grade' => (int)$goods['is_user_grade'],
  748. 'grade_ratio' => $goods['grade_ratio'],
  749. 'grade_goods_price' => $goods['grade_goods_price'],
  750. 'grade_total_money' => $goods['grade_total_money'],
  751. 'coupon_money' => $goods['coupon_money'],
  752. 'points_money' => $isExistPointsDeduction ? $goods['points_money'] : 0.00,
  753. 'points_num' => $isExistPointsDeduction ? $goods['points_num'] : 0,
  754. 'points_bonus' => $goods['points_bonus'],
  755. 'total_num' => $goods['total_num'],
  756. 'total_price' => $goods['total_price'],
  757. 'total_pay_price' => $goods['total_pay_price'],
  758. 'is_ind_dealer' => $goods['is_ind_dealer'],
  759. 'dealer_money_type' => $goods['dealer_money_type'],
  760. 'first_money' => $goods['first_money'],
  761. 'second_money' => $goods['second_money'],
  762. 'third_money' => $goods['third_money'],
  763. ];
  764. // 记录订单商品来源id
  765. $item['goods_source_id'] = isset($goods['goods_source_id']) ? $goods['goods_source_id'] : 0;
  766. $goodsList[] = $item;
  767. }
  768. return $this->model->goods()->saveAll($goodsList);
  769. }
  770. /**
  771. * 更新商品库存 (针对下单减库存的商品)
  772. * @param $order
  773. * @return mixed
  774. */
  775. private function updateGoodsStockNum($order)
  776. {
  777. return StockFactory::getFactory($this->model['order_source'])->updateGoodsStock($order['goods_list']);
  778. }
  779. /**
  780. * 记录收货地址
  781. * @param $address
  782. * @return false|\think\Model
  783. */
  784. private function saveOrderAddress($address)
  785. {
  786. if ($address['region_id'] == 0 && !empty($address['district'])) {
  787. $address['detail'] = $address['district'] . ' ' . $address['detail'];
  788. }
  789. return $this->model->address()->save([
  790. 'user_id' => $this->user['user_id'],
  791. 'wxapp_id' => $this->wxapp_id,
  792. 'name' => $address['name'],
  793. 'phone' => $address['phone'],
  794. 'province_id' => $address['province_id'],
  795. 'city_id' => $address['city_id'],
  796. 'region_id' => $address['region_id'],
  797. 'detail' => $address['detail'],
  798. ]);
  799. }
  800. /**
  801. * 保存上门自提联系人
  802. * @param $linkman
  803. * @param $phone
  804. * @return false|\think\Model
  805. */
  806. private function saveOrderExtract($linkman, $phone)
  807. {
  808. // 记忆上门自提联系人(缓存),用于下次自动填写
  809. UserService::setLastExtract($this->model['user_id'], trim($linkman), trim($phone));
  810. // 保存上门自提联系人(数据库)
  811. return $this->model->extract()->save([
  812. 'linkman' => trim($linkman),
  813. 'phone' => trim($phone),
  814. 'user_id' => $this->model['user_id'],
  815. 'wxapp_id' => $this->wxapp_id,
  816. ]);
  817. }
  818. /**
  819. * 设置错误信息
  820. * @param $error
  821. */
  822. protected function setError($error)
  823. {
  824. empty($this->error) && $this->error = $error;
  825. }
  826. /**
  827. * 获取错误信息
  828. * @return mixed
  829. */
  830. public function getError()
  831. {
  832. return $this->error ?: '';
  833. }
  834. /**
  835. * 是否存在错误
  836. * @return bool
  837. */
  838. public function hasError()
  839. {
  840. return !empty($this->error);
  841. }
  842. }