StoreOrderController.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. <?php
  2. namespace app\api\controller\order;
  3. use app\admin\model\system\{
  4. SystemAttachment, ShippingTemplates
  5. };
  6. use app\admin\model\user\User;
  7. use app\models\routine\RoutineFormId;
  8. use crmeb\repositories\OrderRepository;
  9. use app\models\store\{
  10. StoreBargainUser,
  11. StoreCart,
  12. StoreCoupon,
  13. StoreCouponIssue,
  14. StoreCouponUser,
  15. StoreOrder,
  16. StoreOrderBatch,
  17. StoreOrderCartInfo,
  18. StoreOrderStatus,
  19. StorePink,
  20. StoreProductReply,
  21. StoreSeckill
  22. };
  23. use app\models\system\SystemStore;
  24. use app\models\user\UserAddress;
  25. use app\models\user\UserLevel;
  26. use app\Request;
  27. use think\facade\Cache;
  28. use crmeb\services\{
  29. CacheService,
  30. ExpressService,
  31. SystemConfigService,
  32. UtilService
  33. };
  34. /**
  35. * 订单类
  36. * Class StoreOrderController
  37. * @package app\api\controller\order
  38. */
  39. class StoreOrderController
  40. {
  41. /**
  42. * 订单确认
  43. * @param Request $request
  44. * @return mixed
  45. */
  46. public function confirm(Request $request)
  47. {
  48. // TODO: 运费模板只能选择 ID 为 1 的模板?
  49. $temp = ShippingTemplates::get(1);
  50. if (!$temp) return app('json')->fail('默认模板未配置,无法下单');
  51. list($cartId) = UtilService::postMore(['cartId'], $request, true);
  52. if (!is_string($cartId) || !$cartId) return app('json')->fail('请提交购买的商品');
  53. // 查询当前购物车有效的商品
  54. $uid = $request->uid();
  55. $cartGroup = StoreCart::getUserProductCartList($uid, $cartId, 1);
  56. if (count($cartGroup['invalid'])) {
  57. return app('json')->fail($cartGroup['invalid'][0]['productInfo']['store_name'] . '已失效!');
  58. }
  59. if (!$cartGroup['valid']) {
  60. return app('json')->fail('请提交购买的商品');
  61. }
  62. //
  63. $cartInfo = $cartGroup['valid'];
  64. $addr = UserAddress::getUserDefaultAddress($uid); //UserAddress::where('uid', $uid)->where('is_default', 1)->find();
  65. // 获取当前购物车中各项价格
  66. $priceGroup = StoreOrder::getOrderPriceGroup($cartInfo, $addr);
  67. if ($priceGroup === false) {
  68. return app('json')->fail(StoreOrder::getErrorInfo('运费模板不存在'));
  69. }
  70. $other = [
  71. 'offlinePostage' => sys_config('offline_postage'), // 线下支付是否包邮
  72. 'integralRatio' => sys_config('integral_ratio') // 积分抵用比例
  73. ];
  74. $usableCoupons = []; // TIP 屏蔽优惠券 StoreCouponUser::getUsableCouponList($uid, $cartGroup, $priceGroup['totalPrice']);
  75. $usableCoupon = isset($usableCoupons[0]) ? $usableCoupons[0] : null;
  76. // $cartIdA = explode(',', $cartId);
  77. $seckill_id = 0;
  78. $combination_id = 0;
  79. $bargain_id = 0;
  80. // TIP 屏蔽三个活动
  81. // if (count($cartIdA) == 1) {
  82. // $seckill_id = StoreCart::where('id', $cartId)->value('seckill_id');
  83. // $combination_id = StoreCart::where('id', $cartId)->value('combination_id');
  84. // $bargain_id = StoreCart::where('id', $cartId)->value('bargain_id');
  85. // }
  86. $data['deduction'] = $seckill_id || $combination_id || $bargain_id;
  87. $data['usableCoupon'] = $usableCoupon;
  88. $data['addressInfo'] = $addr; //UserAddress::getUserDefaultAddress($uid);
  89. $data['seckill_id'] = $seckill_id;
  90. $data['combination_id'] = $combination_id;
  91. $data['bargain_id'] = $bargain_id;
  92. $data['cartInfo'] = $cartInfo;
  93. $data['priceGroup'] = $priceGroup;
  94. $data['orderKey'] = StoreOrder::cacheOrderInfo($uid, $cartInfo, $priceGroup, $other);
  95. $data['offlinePostage'] = $other['offlinePostage'];
  96. $vipId = UserLevel::getUserLevel($uid);
  97. $user = $request->user();
  98. if (isset($user['pwd'])) unset($user['pwd']);
  99. $user['vip'] = $vipId !== false ? true : false;
  100. if ($user['vip']) {
  101. $user['vip_id'] = $vipId;
  102. $user['discount'] = UserLevel::getUserLevelInfo($vipId, 'discount');
  103. }
  104. $data['userInfo'] = $user;
  105. $data['integralRatio'] = $other['integralRatio'];
  106. $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2; // 线下支付
  107. $data['store_self_mention'] = (int)sys_config('store_self_mention') ?? 0;//门店自提是否开启
  108. $data['system_store'] = []; // TIP: 屏蔽门店信息 ($res = SystemStore::getStoreDispose()) ? $res : [];//门店信息
  109. return app('json')->successful($data);
  110. }
  111. /**
  112. * 计算订单金额
  113. * @param Request $request
  114. * @param $key
  115. * @return mixed
  116. * @throws \think\Exception
  117. * @throws \think\db\exception\DataNotFoundException
  118. * @throws \think\db\exception\ModelNotFoundException
  119. * @throws \think\exception\DbException
  120. */
  121. public function computedOrder(Request $request, $key)
  122. {
  123. // $key 就是 confirm 返回的 orderKey
  124. if (!$key) return app('json')->fail('参数错误!');
  125. // 是否已存在
  126. $uid = $request->uid();
  127. if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
  128. return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
  129. list($addressId, $couponId, $payType, $useIntegral, $mark,
  130. $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $shipping_type) = UtilService::postMore([
  131. 'addressId',
  132. 'couponId',
  133. ['payType', 'yue'],
  134. ['useIntegral', 0],
  135. 'mark',
  136. ['combinationId', 0],
  137. ['pinkId', 0],
  138. ['seckill_id', 0],
  139. ['formId', ''],
  140. ['bargainId', ''],
  141. ['shipping_type', 1],
  142. ], $request, true);
  143. // weixin / yue
  144. $payType = strtolower($payType);
  145. if ($bargainId) {
  146. $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
  147. if (!$bargainUserTableId)
  148. return app('json')->fail('砍价失败');
  149. $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
  150. if ($status == 3)
  151. return app('json')->fail('砍价已支付');
  152. StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
  153. }
  154. if ($pinkId) {
  155. $cache_pink = Cache::get(md5('store_pink_' . $pinkId));
  156. if ($cache_pink && bcsub($cache_pink['people'], $cache_pink['now_people'], 0) <= 0) {
  157. return app('json')->status('ORDER_EXIST', '订单生成失败,该团人员已满', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  158. }
  159. if (StorePink::getIsPinkUid($pinkId, $request->uid()))
  160. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  161. if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
  162. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  163. }
  164. $priceGroup = StoreOrder::cacheKeyCreateOrder($request->uid(), $key, $addressId, $payType, (int)$useIntegral,
  165. $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, true, 0, $shipping_type);
  166. // return app('json')->fail(StoreOrder::getErrorInfo('计算失败'));
  167. if ($priceGroup)
  168. return app('json')->status('NONE', 'ok', $priceGroup);
  169. else
  170. return app('json')->fail(StoreOrder::getErrorInfo('计算失败'));
  171. }
  172. /**
  173. * 订单创建
  174. * @param Request $request
  175. * @param $key
  176. * @return mixed
  177. * @throws \think\Exception
  178. * @throws \think\db\exception\DataNotFoundException
  179. * @throws \think\db\exception\ModelNotFoundException
  180. * @throws \think\exception\DbException
  181. */
  182. public function create(Request $request, $key)
  183. {
  184. // 还是那个 $orderKey
  185. if (!$key) return app('json')->fail('参数错误!');
  186. // 订单是否已存在
  187. $uid = $request->uid();
  188. if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
  189. return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
  190. // 获得参数
  191. list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $from, $shipping_type, $real_name, $phone, $storeId) = UtilService::postMore([
  192. 'addressId',
  193. 'couponId',
  194. 'payType',
  195. ['useIntegral', 0],
  196. 'mark',
  197. ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''],
  198. ['from', 'weixin'],
  199. ['shipping_type', 1], ['real_name', ''], ['phone', ''], ['store_id', 0]
  200. ], $request, true);
  201. // weixin / yue
  202. $payType = strtolower($payType);
  203. if ($bargainId) {
  204. $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
  205. if (!$bargainUserTableId)
  206. return app('json')->fail('砍价失败');
  207. $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
  208. if ($status == 3)
  209. return app('json')->fail('砍价已支付');
  210. StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
  211. }
  212. if ($pinkId) {
  213. $cache_pink = Cache::get(md5('store_pink_' . $pinkId));
  214. if ($cache_pink && bcsub($cache_pink['people'], $cache_pink['now_people'], 0) <= 0) {
  215. return app('json')->status('ORDER_EXIST', '订单生成失败,该团人员已满', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  216. }
  217. if (StorePink::getIsPinkUid($pinkId, $request->uid()))
  218. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  219. if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
  220. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  221. }
  222. $isChannel = 1; // 'routine'
  223. if ($from == 'weixin')
  224. $isChannel = 0;
  225. elseif ($from == 'weixinh5')
  226. $isChannel = 2;
  227. $order = StoreOrder::cacheKeyCreateOrder($request->uid(), $key, $addressId, $payType, (int)$useIntegral,
  228. $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, false, $isChannel,
  229. $shipping_type, $real_name, $phone, $storeId);
  230. if ($order === false) {
  231. return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败'));
  232. }
  233. $orderId = $order['order_id'];
  234. $info = compact('orderId', 'key');
  235. if ($orderId) {
  236. event('OrderCreated', [$order]); //订单创建成功事件
  237. // event('ShortMssageSend', [$orderId, 'AdminPlaceAnOrder']);//发送管理员通知
  238. switch ($payType) {
  239. case "weixin":
  240. $orderInfo = StoreOrder::where('order_id', $orderId)->find();
  241. if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
  242. $orderInfo = $orderInfo->toArray();
  243. if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
  244. //支付金额为0
  245. if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
  246. //创建订单jspay支付
  247. $payPriceStatus = StoreOrder::jsPayPrice($orderId, $uid, $formId);
  248. if ($payPriceStatus)//0元支付成功
  249. return app('json')->status('success', '微信支付成功', $info);
  250. else
  251. return app('json')->status('pay_error', StoreOrder::getErrorInfo());
  252. } else {
  253. try {
  254. if ($from == 'routine') {
  255. $jsConfig = OrderRepository::jsPay($orderId); //创建订单jspay
  256. } else if ($from == 'weixinh5') {
  257. $jsConfig = OrderRepository::h5Pay($orderId);
  258. } else {
  259. $jsConfig = OrderRepository::wxPay($orderId);
  260. }
  261. } catch (\Exception $e) {
  262. return app('json')->status('pay_error', $e->getMessage(), $info);
  263. }
  264. $info['jsConfig'] = $jsConfig;
  265. if ($from == 'weixinh5') {
  266. return app('json')->status('wechat_h5_pay', '订单创建成功', $info);
  267. } else {
  268. return app('json')->status('wechat_pay', '订单创建成功', $info);
  269. }
  270. }
  271. break;
  272. case 'yue':
  273. if (StoreOrder::yuePay($orderId, $request->uid(), $formId))
  274. return app('json')->status('success', '余额支付成功', $info);
  275. else {
  276. $errorinfo = StoreOrder::getErrorInfo();
  277. if (is_array($errorinfo))
  278. return app('json')->status($errorinfo['status'], $errorinfo['msg'], $info);
  279. else
  280. return app('json')->status('pay_error', $errorinfo);
  281. }
  282. break;
  283. case 'offline':
  284. return app('json')->status('success', '订单创建成功', $info);
  285. break;
  286. }
  287. } else { // !$orderId
  288. return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败!'));
  289. }
  290. }
  291. /**
  292. * 计算订单金额
  293. * @param Request $request
  294. * @param $key
  295. * @return mixed
  296. * @throws \think\Exception
  297. * @throws \think\db\exception\DataNotFoundException
  298. * @throws \think\db\exception\ModelNotFoundException
  299. * @throws \think\exception\DbException
  300. */
  301. public function computedOrder_v2(Request $request, $key)
  302. {
  303. // $key 就是 confirm 返回的 orderKey
  304. if (!$key) return app('json')->fail('参数错误!');
  305. // 是否已存在
  306. $uid = $request->uid();
  307. if (StoreOrderBatch::be(['unique' => $key, 'uid' => $uid]))
  308. return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
  309. list($addressId, $couponId, $payType, $useIntegral, $mark,
  310. $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $shipping_type) = UtilService::postMore([
  311. 'addressId',
  312. 'couponId',
  313. ['payType', 'yue'],
  314. ['useIntegral', 0],
  315. 'mark',
  316. ['combinationId', 0],
  317. ['pinkId', 0],
  318. ['seckill_id', 0],
  319. ['formId', ''],
  320. ['bargainId', ''],
  321. ['shipping_type', 1],
  322. ], $request, true);
  323. // weixin / yue
  324. $payType = strtolower($payType);
  325. if ($bargainId) {
  326. $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
  327. if (!$bargainUserTableId)
  328. return app('json')->fail('砍价失败');
  329. $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
  330. if ($status == 3)
  331. return app('json')->fail('砍价已支付');
  332. StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
  333. }
  334. if ($pinkId) {
  335. $cache_pink = Cache::get(md5('store_pink_' . $pinkId));
  336. if ($cache_pink && bcsub($cache_pink['people'], $cache_pink['now_people'], 0) <= 0) {
  337. return app('json')->status('ORDER_EXIST', '订单生成失败,该团人员已满', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  338. }
  339. if (StorePink::getIsPinkUid($pinkId, $request->uid()))
  340. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  341. if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
  342. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  343. }
  344. $priceGroup = StoreOrderBatch::cacheKeyCreateOrderBatch($request->uid(), $key, $addressId, $payType, (int)$useIntegral,
  345. $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, true, 0, $shipping_type);
  346. // return app('json')->fail(StoreOrder::getErrorInfo('计算失败'));
  347. if ($priceGroup)
  348. return app('json')->status('NONE', 'ok', $priceGroup);
  349. else
  350. return app('json')->fail(StoreOrder::getErrorInfo('计算失败'));
  351. }
  352. /**
  353. * 订单创建, 支持子订单版本
  354. * @param Request $request
  355. * @param $key
  356. * @return mixed
  357. * @throws \think\Exception
  358. * @throws \think\db\exception\DataNotFoundException
  359. * @throws \think\db\exception\ModelNotFoundException
  360. * @throws \think\exception\DbException
  361. */
  362. public function create_v2(Request $request, $key)
  363. {
  364. // 还是那个 $orderKey
  365. if (!$key) {
  366. return app('json')->fail('参数错误!');
  367. }
  368. // 订单是否已存在
  369. $uid = $request->uid();
  370. if (StoreOrderBatch::be(['unique' => $key, 'uid' => $uid]))
  371. return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
  372. // 获得参数
  373. list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $from, $shipping_type, $real_name, $phone, $storeId) = UtilService::postMore([
  374. 'addressId',
  375. 'couponId',
  376. 'payType',
  377. ['useIntegral', 0],
  378. 'mark',
  379. ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''],
  380. ['from', 'weixin'],
  381. ['shipping_type', 1], ['real_name', ''], ['phone', ''], ['store_id', 0]
  382. ], $request, true);
  383. // weixin / yue
  384. $payType = strtolower($payType);
  385. if ($bargainId) {
  386. $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
  387. if (!$bargainUserTableId)
  388. return app('json')->fail('砍价失败');
  389. $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
  390. if ($status == 3)
  391. return app('json')->fail('砍价已支付');
  392. StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
  393. }
  394. if ($pinkId) {
  395. $cache_pink = Cache::get(md5('store_pink_' . $pinkId));
  396. if ($cache_pink && bcsub($cache_pink['people'], $cache_pink['now_people'], 0) <= 0) {
  397. return app('json')->status('ORDER_EXIST', '订单生成失败,该团人员已满', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  398. }
  399. if (StorePink::getIsPinkUid($pinkId, $request->uid()))
  400. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  401. if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
  402. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  403. }
  404. $isChannel = 1; // 'routine'
  405. if ($from == 'weixin')
  406. $isChannel = 0;
  407. elseif ($from == 'weixinh5')
  408. $isChannel = 2;
  409. $porderId = StoreOrderBatch::cacheKeyCreateOrderBatch($request->uid(), $key, $addressId, $payType, (int)$useIntegral,
  410. $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, false, $isChannel,
  411. $shipping_type, $real_name, $phone, $storeId);
  412. if ($porderId === false) {
  413. return app('json')->fail(StoreOrderBatch::getErrorInfo('订单生成失败'));
  414. }
  415. $orderId = $porderId; // for compact
  416. $info = compact('orderId', 'key');
  417. if ($porderId) {
  418. event('BatchOrderCreated', [$porderId]); //订单创建成功事件
  419. // event('ShortMssageSend', [$orderId, 'AdminPlaceAnOrder']);//发送管理员通知
  420. switch ($payType) {
  421. case "weixin":
  422. $subOrders = StoreOrderBatch::getAllSubOrders($porderId);
  423. if (!$subOrders) return app('json')->fail('支付订单不存在!');
  424. $fieldValues = StoreOrderBatch::sumFields($subOrders, ['paid','pay_price']);
  425. if ($fieldValues['paid']) {
  426. return app('json')->fail('支付已支付!');
  427. }
  428. //支付金额为0
  429. if (bcsub($fieldValues['pay_price'], 0, 2) <= 0) {
  430. //创建订单jspay支付
  431. $payPriceStatus = StoreOrderBatch::jsPayPriceBatch($porderId, $uid, $formId);
  432. if ($payPriceStatus)//0元支付成功
  433. return app('json')->status('success', '微信支付成功', $info);
  434. else
  435. return app('json')->status('pay_error', StoreOrderBatch::getErrorInfo());
  436. } else {
  437. try {
  438. if ($from == 'routine') {
  439. $jsConfig = OrderRepository::jsPayBatch($porderId); //创建订单jspay
  440. } else if ($from == 'weixinh5') {
  441. $jsConfig = OrderRepository::h5PayBatch($porderId);
  442. } else {
  443. $jsConfig = OrderRepository::wxPayBatch($porderId);
  444. }
  445. } catch (\Exception $e) {
  446. return app('json')->status('pay_error', $e->getMessage(), $info);
  447. }
  448. $info['jsConfig'] = $jsConfig;
  449. if ($from == 'weixinh5') {
  450. return app('json')->status('wechat_h5_pay', '订单创建成功', $info);
  451. } else {
  452. return app('json')->status('wechat_pay', '订单创建成功', $info);
  453. }
  454. }
  455. break;
  456. case 'yue':
  457. if (StoreOrderBatch::yuePayBatch($porderId, $request->uid(), $formId))
  458. return app('json')->status('success', '余额支付成功', $info);
  459. else {
  460. $errorinfo = StoreOrderBatch::getErrorInfo();
  461. if (is_array($errorinfo))
  462. return app('json')->status($errorinfo['status'], $errorinfo['msg'], $info);
  463. else
  464. return app('json')->status('pay_error', $errorinfo);
  465. }
  466. break;
  467. case 'offline':
  468. return app('json')->status('success', '订单创建成功', $info);
  469. break;
  470. }
  471. } else { // !$orderId
  472. return app('json')->fail(StoreOrderBatch::getErrorInfo('订单生成失败!'));
  473. }
  474. }
  475. /**
  476. * 订单 再次下单
  477. * @param Request $request
  478. * @return mixed
  479. */
  480. public function again(Request $request)
  481. {
  482. list($uni) = UtilService::postMore([
  483. ['uni', ''],
  484. ], $request, true);
  485. if (!$uni) return app('json')->fail('参数错误!');
  486. $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
  487. if (!$order) return app('json')->fail('订单不存在!');
  488. $order = StoreOrder::tidyOrder($order, true);
  489. $res = [];
  490. foreach ($order['cartInfo'] as $v) {
  491. if ($v['combination_id']) return app('json')->fail('拼团产品不能再来一单,请在拼团产品内自行下单!');
  492. else if ($v['bargain_id']) return app('json')->fail('砍价产品不能再来一单,请在砍价产品内自行下单!');
  493. else if ($v['seckill_id']) return app('json')->ail('秒杀产品不能再来一单,请在秒杀产品内自行下单!');
  494. else $res[] = StoreCart::setCart($request->uid(), $v['product_id'], $v['cart_num'], isset($v['productInfo']['attrInfo']['unique']) ? $v['productInfo']['attrInfo']['unique'] : '', 'product', 0, 0);
  495. }
  496. $cateId = [];
  497. foreach ($res as $v) {
  498. if (!$v) return app('json')->fail('再来一单失败,请重新下单!');
  499. $cateId[] = $v['id'];
  500. }
  501. event('OrderCreateAgain', implode(',', $cateId));
  502. return app('json')->successful('ok', ['cateId' => implode(',', $cateId)]);
  503. }
  504. /**
  505. * 订单支付
  506. * @param Request $request
  507. * @return mixed
  508. */
  509. public function pay(Request $request)
  510. {
  511. list($uni, $paytype, $from) = UtilService::postMore([
  512. ['uni', ''],
  513. ['paytype', 'weixin'],
  514. ['from', 'weixin']
  515. ], $request, true);
  516. if (!$uni) return app('json')->fail('参数错误!');
  517. $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
  518. if (!$order)
  519. return app('json')->fail('订单不存在!');
  520. if ($order['paid'])
  521. return app('json')->fail('该订单已支付!');
  522. if ($order['pink_id']) {
  523. $cache_pink = Cache::get(md5('store_pink_' . $order['pink_id']));
  524. if (StorePink::isPinkStatus($order['pink_id']) || ($cache_pink && bcsub($cache_pink['people'], $cache_pink['now_people'], 0) <= 0)) {
  525. return app('json')->fail('该订单已失效!');
  526. }
  527. }
  528. if ($from == 'weixin') {//0
  529. if (in_array($order->is_channel, [1, 2]))
  530. $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  531. }
  532. if ($from == 'weixinh5') {//2
  533. if (in_array($order->is_channel, [0, 1]))
  534. $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  535. }
  536. if ($from == 'routine') {//1
  537. if (in_array($order->is_channel, [0, 2]))
  538. $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  539. }
  540. $order['pay_type'] = $paytype; //重新支付选择支付方式
  541. switch ($order['pay_type']) {
  542. case 'weixin':
  543. try {
  544. if ($from == 'routine') {
  545. $jsConfig = OrderRepository::jsPay($order); //订单列表发起支付
  546. } else if ($from == 'weixinh5') {
  547. $jsConfig = OrderRepository::h5Pay($order);
  548. } else {
  549. $jsConfig = OrderRepository::wxPay($order);
  550. }
  551. } catch (\Exception $e) {
  552. return app('json')->fail($e->getMessage());
  553. }
  554. if ($from == 'weixinh5') {
  555. return app('json')->status('wechat_h5_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
  556. } else {
  557. return app('json')->status('wechat_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
  558. }
  559. break;
  560. case 'yue':
  561. if (StoreOrder::yuePay($order['order_id'], $request->uid()))
  562. return app('json')->status('success', '余额支付成功');
  563. else {
  564. $error = StoreOrder::getErrorInfo();
  565. return app('json')->fail(is_array($error) && isset($error['msg']) ? $error['msg'] : $error);
  566. }
  567. break;
  568. case 'offline':
  569. StoreOrder::createOrderTemplate($order);
  570. if (StoreOrder::setOrderTypePayOffline($order['order_id']))
  571. return app('json')->status('success', '订单创建成功');
  572. else
  573. return app('json')->status('success', '支付失败');
  574. break;
  575. }
  576. return app('json')->fail('支付方式错误');
  577. }
  578. /**
  579. * 订单列表
  580. * @param Request $request
  581. * @return mixed
  582. */
  583. public function lst(Request $request)
  584. {
  585. list($type, $page, $limit, $search) = UtilService::getMore([
  586. ['type', ''],
  587. ['page', 0],
  588. ['limit', ''],
  589. ['search', ''],
  590. ], $request, true);
  591. return app('json')->successful(StoreOrder::getUserOrderSearchList($request->uid(), $type, $page, $limit, $search));
  592. }
  593. /**
  594. * 订单详情 v2
  595. * 订单支持子订单之后,订单详情协议传过来的 $uni 有可能是子订单的,也有可能是主订单的
  596. */
  597. public function detail_v2(Request $request, $uni)
  598. {
  599. if (!strlen(trim($uni))) return app('json')->fail('参数错误');
  600. $uid = $request->uid();
  601. $first4 = mb_substr($uni, 0, 4);
  602. if ($first4 == 'wxcn') {
  603. $porder = StoreOrderBatch::where('porder_id', $uni)->where('uid', $uid)->find();
  604. if (!$porder) {
  605. return app('json')->fail('订单不存在');
  606. }
  607. $porder = $porder->toArray();
  608. $subOrders = StoreOrderBatch::getAllSubOrders($porder['porder_id']);
  609. if (!$subOrders) {
  610. return app('json')->fail('订单不存在');
  611. }
  612. $order = $this->__get_order_details($uid, $subOrders[0]['order_id']);
  613. if (!$order) {
  614. return app('json')->fail('订单不存在');
  615. }
  616. $order['order_id'] = $porder['porder_id'];
  617. $order['pay_price'] = $porder['total_price'];
  618. return app('json')->successful('ok', $order);
  619. } else {
  620. return $this->detail($request, $uni);
  621. }
  622. }
  623. /**
  624. * 订单详情
  625. * @param Request $request
  626. * @param $uni
  627. * @return mixed
  628. */
  629. public function detail(Request $request, $uni)
  630. {
  631. $order = $this->__get_order_details($request->uid(), $uni);
  632. if (!$order) {
  633. return app('json')->fail('订单不存在');
  634. }
  635. return app('json')->successful('ok', $order);
  636. }
  637. public function __get_order_details($uid, $uni)
  638. {
  639. $order = StoreOrder::getUserOrderDetail($uid, $uni);
  640. if (!$order) {
  641. return false;
  642. }
  643. $order = $order->toArray();
  644. //是否开启门店自提
  645. $store_self_mention = sys_config('store_self_mention');
  646. //关闭门店自提后 订单隐藏门店信息
  647. if ($store_self_mention == 0) $order['shipping_type'] = 1;
  648. if ($order['verify_code']) {
  649. $verify_code = $order['verify_code'];
  650. $verify[] = substr($verify_code, 0, 4);
  651. $verify[] = substr($verify_code, 4, 4);
  652. $verify[] = substr($verify_code, 8);
  653. $order['_verify_code'] = implode(' ', $verify);
  654. }
  655. $order['add_time_y'] = date('Y-m-d', $order['add_time']);
  656. $order['add_time_h'] = date('H:i:s', $order['add_time']);
  657. $order['system_store'] = SystemStore::getStoreDispose($order['store_id']);
  658. if ($order['shipping_type'] === 2 && $order['verify_code']) {
  659. $name = $order['verify_code'] . '.jpg';
  660. $imageInfo = SystemAttachment::getInfo($name, 'name');
  661. $siteUrl = sys_config('site_url');
  662. if (!$imageInfo) {
  663. $imageInfo = UtilService::getQRCodePath($order['verify_code'], $name);
  664. if (is_array($imageInfo)) {
  665. SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
  666. $url = $imageInfo['dir'];
  667. } else
  668. $url = '';
  669. } else $url = $imageInfo['att_dir'];
  670. if (isset($imageInfo['image_type']) && $imageInfo['image_type'] == 1) $url = $siteUrl . $url;
  671. $order['code'] = $url;
  672. }
  673. $order['mapKey'] = sys_config('tengxun_map_key');
  674. return StoreOrder::tidyOrder($order, true, true);
  675. }
  676. /**
  677. * 订单删除
  678. * @param Request $request
  679. * @return mixed
  680. */
  681. public function del(Request $request)
  682. {
  683. list($uni) = UtilService::postMore([
  684. ['uni', ''],
  685. ], $request, true);
  686. if (!$uni) return app('json')->fail('参数错误!');
  687. $res = StoreOrder::removeOrder($uni, $request->uid());
  688. if ($res)
  689. return app('json')->successful();
  690. else
  691. return app('json')->fail(StoreOrder::getErrorInfo());
  692. }
  693. /**
  694. * 订单收货
  695. * @param Request $request
  696. * @return mixed
  697. */
  698. public function take(Request $request)
  699. {
  700. list($uni) = UtilService::postMore([
  701. ['uni', ''],
  702. ], $request, true);
  703. if (!$uni) return app('json')->fail('参数错误!');
  704. $res = StoreOrder::takeOrder($uni, $request->uid());
  705. if ($res) {
  706. $order_info = StoreOrder::where('order_id', $uni)->find();
  707. $gain_integral = intval($order_info['gain_integral']);
  708. $gain_coupon = StoreCouponIssue::alias('a')
  709. ->join('store_coupon b', 'a.cid = b.id')
  710. ->where('a.status', 1)
  711. ->where('a.is_full_give', 1)
  712. ->where('a.is_del', 0)
  713. ->where('a.full_reduction', '<=', $order_info['total_price'])
  714. ->sum('b.coupon_price');
  715. return app('json')->successful(['gain_integral' => $gain_integral, 'gain_coupon' => $gain_coupon]);
  716. } else
  717. return app('json')->fail(StoreOrder::getErrorInfo());
  718. }
  719. /**
  720. * 订单 查看物流
  721. * @param Request $request
  722. * @param $uni
  723. * @return mixed
  724. */
  725. public function express(Request $request, $uni)
  726. {
  727. if (!$uni || !($order = StoreOrder::getUserOrderDetail($request->uid(), $uni))) return app('json')->fail('查询订单不存在!');
  728. if ($order['delivery_type'] != 'express' || !$order['delivery_id']) return app('json')->fail('该订单不存在快递单号!');
  729. $cacheName = $uni . $order['delivery_id'];
  730. $result = CacheService::get($cacheName);
  731. if (!$result) {
  732. try {
  733. $result = ExpressService::query($order['delivery_id'], $order['delivery_name']);
  734. } catch (\Throwable $e) {
  735. $result = [];
  736. }
  737. if (is_array($result) && (isset($result['result']) || isset($result['content']))) {
  738. $cacheTime = 1200;
  739. if(isset($result['content'])){
  740. $result['result'] = $result['content'];
  741. unset($result['content']);
  742. }
  743. }else
  744. $cacheTime = 1800;
  745. CacheService::set($cacheName, $result, $cacheTime);
  746. }
  747. $orderInfo = [];
  748. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?? [];
  749. $info = [];
  750. $cartNew = [];
  751. foreach ($cartInfo as $k => $cart) {
  752. $cart = json_decode($cart, true);
  753. $cartNew['cart_num'] = $cart['cart_num'];
  754. $cartNew['truePrice'] = $cart['truePrice'];
  755. $cartNew['productInfo']['image'] = $cart['productInfo']['image'];
  756. $cartNew['productInfo']['store_name'] = $cart['productInfo']['store_name'];
  757. $cartNew['productInfo']['unit_name'] = $cart['productInfo']['unit_name'] ?? '';
  758. array_push($info, $cartNew);
  759. unset($cart);
  760. }
  761. $orderInfo['delivery_id'] = $order['delivery_id'];
  762. $orderInfo['delivery_name'] = $order['delivery_name'];
  763. $orderInfo['delivery_type'] = $order['delivery_type'];
  764. $orderInfo['cartInfo'] = $info;
  765. return app('json')->successful(['order' => $orderInfo, 'express' => $result ? $result : []]);
  766. }
  767. /**
  768. * 订单评价
  769. * @param Request $request
  770. * @return mixed
  771. * @throws \think\db\exception\DataNotFoundException
  772. * @throws \think\db\exception\ModelNotFoundException
  773. * @throws \think\exception\DbException
  774. */
  775. public function comment(Request $request)
  776. {
  777. $group = UtilService::postMore([
  778. ['unique', ''], ['comment', ''], ['pics', ''], ['product_score', 5], ['service_score', 5]
  779. ], $request);
  780. $unique = $group['unique'];
  781. unset($group['unique']);
  782. if (!$unique) return app('json')->fail('参数错误!');
  783. $cartInfo = StoreOrderCartInfo::where('unique', $unique)->find();
  784. $uid = $request->uid();
  785. $user_info = User::get($uid);
  786. $group['nickname'] = $user_info['nickname'];
  787. $group['avatar'] = $user_info['avatar'];
  788. if (!$cartInfo) return app('json')->fail('评价产品不存在!');
  789. $orderUid = StoreOrder::getOrderInfo($cartInfo['oid'], 'uid')['uid'];
  790. if ($uid != $orderUid) {
  791. return app('json')->fail('评价产品不存在!');
  792. }
  793. if (StoreProductReply::be(['oid' => $cartInfo['oid'], 'unique' => $unique]))
  794. return app('json')->fail('该产品已评价!');
  795. $group['comment'] = htmlspecialchars(trim($group['comment']));
  796. if ($group['product_score'] < 1) return app('json')->fail('请为产品评分');
  797. else if ($group['service_score'] < 1) return app('json')->fail('请为商家服务评分');
  798. //
  799. $cartInfo['cart_info'] = json_decode($cartInfo['cart_info'], true);
  800. if ($cartInfo['cart_info']['combination_id']) $productId = $cartInfo['cart_info']['product_id'];
  801. else if ($cartInfo['cart_info']['seckill_id']) $productId = $cartInfo['cart_info']['product_id'];
  802. else if ($cartInfo['cart_info']['bargain_id']) $productId = $cartInfo['cart_info']['product_id'];
  803. else $productId = $cartInfo['product_id'];
  804. if ($group['pics']) {
  805. $group['pics'] = json_encode(is_array($group['pics']) ? $group['pics'] : explode(',', $group['pics']));
  806. } else {
  807. $group['pics'] = '';
  808. }
  809. $group = array_merge($group, [
  810. 'uid' => $uid,
  811. 'oid' => $cartInfo['oid'],
  812. 'unique' => $unique,
  813. 'product_id' => $productId,
  814. 'add_time' => time(),
  815. 'reply_type' => 'product'
  816. ]);
  817. StoreProductReply::beginTrans();
  818. $res = StoreProductReply::reply($group, 'product');
  819. if (!$res) {
  820. StoreProductReply::rollbackTrans();
  821. return app('json')->fail('评价失败!');
  822. }
  823. try {
  824. StoreOrder::checkOrderOver($cartInfo['oid']);
  825. } catch (\Exception $e) {
  826. StoreProductReply::rollbackTrans();
  827. return app('json')->fail($e->getMessage());
  828. }
  829. StoreProductReply::commitTrans();
  830. event('UserCommented', $res);
  831. event('AdminNewPush');
  832. return app('json')->successful();
  833. }
  834. /**
  835. * 订单统计数据
  836. * @param Request $request
  837. * @return mixed
  838. */
  839. public function data(Request $request)
  840. {
  841. return app('json')->successful(StoreOrder::getOrderData($request->uid()));
  842. }
  843. /**
  844. * 订单退款理由
  845. * @return mixed
  846. */
  847. public function refund_reason()
  848. {
  849. $reason = sys_config('stor_reason') ?: [];//退款理由
  850. $reason = str_replace("\r\n", "\n", $reason);//防止不兼容
  851. $reason = explode("\n", $reason);
  852. return app('json')->successful($reason);
  853. }
  854. /**
  855. * 订单退款审核
  856. * @param Request $request
  857. * @return mixed
  858. */
  859. public function refund_verify(Request $request)
  860. {
  861. $data = UtilService::postMore([
  862. ['text', ''],
  863. ['refund_reason_wap_img', ''],
  864. ['refund_reason_wap_explain', ''],
  865. ['uni', '']
  866. ], $request);
  867. $uni = $data['uni'];
  868. unset($data['uni']);
  869. if ($data['refund_reason_wap_img']) $data['refund_reason_wap_img'] = explode(',', $data['refund_reason_wap_img']);
  870. if (!$uni || $data['text'] == '') return app('json')->fail('参数错误!');
  871. $res = StoreOrder::orderApplyRefund($uni, $request->uid(), $data['text'], $data['refund_reason_wap_explain'], $data['refund_reason_wap_img']);
  872. if ($res)
  873. return app('json')->successful('提交申请成功');
  874. else
  875. return app('json')->fail(StoreOrder::getErrorInfo());
  876. }
  877. /**
  878. * 订单取消 未支付的订单回退积分,回退优惠券,回退库存
  879. * @param Request $request
  880. * @return mixed
  881. * @throws \think\db\exception\DataNotFoundException
  882. * @throws \think\db\exception\ModelNotFoundException
  883. * @throws \think\exception\DbException
  884. */
  885. public function cancel(Request $request)
  886. {
  887. list($id) = UtilService::postMore([['id', 0]], $request, true);
  888. if (!$id) return app('json')->fail('参数错误');
  889. if (StoreOrder::cancelOrder($id, $request->uid()))
  890. return app('json')->successful('取消订单成功');
  891. return app('json')->fail(StoreOrder::getErrorInfo('取消订单失败'));
  892. }
  893. /**
  894. * 订单产品信息
  895. * @param Request $request
  896. * @return mixed
  897. * @throws \think\db\exception\DataNotFoundException
  898. * @throws \think\db\exception\ModelNotFoundException
  899. * @throws \think\exception\DbException
  900. */
  901. public function product(Request $request)
  902. {
  903. list($unique) = UtilService::postMore([['unique', '']], $request, true);
  904. if (!$unique || !StoreOrderCartInfo::be(['unique' => $unique]) || !($cartInfo = StoreOrderCartInfo::where('unique', $unique)->find())) return app('json')->fail('评价产品不存在!');
  905. $cartInfo = $cartInfo->toArray();
  906. $cartProduct = [];
  907. $cartProduct['cart_num'] = $cartInfo['cart_info']['cart_num'];
  908. $cartProduct['productInfo']['image'] = isset($cartInfo['cart_info']['productInfo']['image']) ? $cartInfo['cart_info']['productInfo']['image'] : '';
  909. $cartProduct['productInfo']['price'] = isset($cartInfo['cart_info']['productInfo']['price']) ? $cartInfo['cart_info']['productInfo']['price'] : 0;
  910. $cartProduct['productInfo']['store_name'] = isset($cartInfo['cart_info']['productInfo']['store_name']) ? $cartInfo['cart_info']['productInfo']['store_name'] : '';
  911. if (isset($cartInfo['cart_info']['productInfo']['attrInfo'])) {
  912. $cartProduct['productInfo']['attrInfo']['product_id'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['product_id']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['product_id'] : '';
  913. $cartProduct['productInfo']['attrInfo']['suk'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['suk']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['suk'] : '';
  914. $cartProduct['productInfo']['attrInfo']['price'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['price']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['price'] : '';
  915. $cartProduct['productInfo']['attrInfo']['image'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['image']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['image'] : '';
  916. }
  917. $cartProduct['product_id'] = isset($cartInfo['cart_info']['product_id']) ? $cartInfo['cart_info']['product_id'] : 0;
  918. $cartProduct['combination_id'] = isset($cartInfo['cart_info']['combination_id']) ? $cartInfo['cart_info']['combination_id'] : 0;
  919. $cartProduct['seckill_id'] = isset($cartInfo['cart_info']['seckill_id']) ? $cartInfo['cart_info']['seckill_id'] : 0;
  920. $cartProduct['bargain_id'] = isset($cartInfo['cart_info']['bargain_id']) ? $cartInfo['cart_info']['bargain_id'] : 0;
  921. $cartProduct['order_id'] = StoreOrder::where('id', $cartInfo['oid'])->value('order_id');
  922. return app('json')->successful($cartProduct);
  923. }
  924. /**
  925. * 首页获取未支付订单
  926. */
  927. public function get_noPay(Request $request)
  928. {
  929. return app('json')->successful(StoreOrder::getUserOrderSearchList($request->uid(), 0, 0, 0, ''));
  930. }
  931. }