StoreOrderController.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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\{StoreBargainUser,
  10. StoreCart,
  11. StoreCategory,
  12. StoreCoupon,
  13. StoreCouponIssue,
  14. StoreCouponUser,
  15. StoreOrder,
  16. StoreOrderCartInfo,
  17. StoreOrderRelease,
  18. StoreOrderStatus,
  19. StorePink,
  20. StoreProduct,
  21. StoreProductReply};
  22. use app\models\system\SystemStore;
  23. use app\models\user\UserAddress;
  24. use app\models\user\UserLevel;
  25. use app\Request;
  26. use crmeb\services\{
  27. CacheService,
  28. ExpressService,
  29. SystemConfigService,
  30. UtilService
  31. };
  32. include_once dirname(__FILE__). "/../AdapaySdk/init.php";
  33. include_once dirname(__FILE__). "/../AdapaySdk/config.php";
  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. $temp = ShippingTemplates::get(1);
  49. if (!$temp) return app('json')->fail('默认模板未配置,无法下单');
  50. list($cartId) = UtilService::postMore(['cartId'], $request, true);
  51. if (!is_string($cartId) || !$cartId) return app('json')->fail('请提交购买的商品');
  52. $uid = $request->uid();
  53. $cartGroup = StoreCart::getUserProductCartList($uid, $cartId, 1);
  54. if (count($cartGroup['invalid'])) return app('json')->fail($cartGroup['invalid'][0]['productInfo']['store_name'] . '已失效!');
  55. if (!$cartGroup['valid']) return app('json')->fail('请提交购买的商品');
  56. $cartInfo = $cartGroup['valid'];
  57. $addr = UserAddress::where('uid', $uid)->where('is_default', 1)->find();
  58. $priceGroup = StoreOrder::getOrderPriceGroup($cartInfo, $addr);
  59. if ($priceGroup === false) {
  60. return app('json')->fail(StoreOrder::getErrorInfo('运费模板不存在'));
  61. }
  62. $other = [
  63. 'offlinePostage' => sys_config('offline_postage'),
  64. 'integralRatio' => sys_config('integral_ratio')
  65. ];
  66. $usableCoupons = StoreCouponUser::getUsableCouponList($uid, $cartGroup, $priceGroup['totalPrice']);
  67. $usableCoupon = isset($usableCoupons[0]) ? $usableCoupons[0] : null;
  68. $cartIdA = explode(',', $cartId);
  69. $seckill_id = 0;
  70. $combination_id = 0;
  71. $bargain_id = 0;
  72. if (count($cartIdA) == 1) {
  73. $seckill_id = StoreCart::where('id', $cartId)->value('seckill_id');
  74. $combination_id = StoreCart::where('id', $cartId)->value('combination_id');
  75. $bargain_id = StoreCart::where('id', $cartId)->value('bargain_id');
  76. }
  77. $data['deduction'] = $seckill_id || $combination_id || $bargain_id;
  78. $data['usableCoupon'] = $usableCoupon;
  79. $data['addressInfo'] = UserAddress::getUserDefaultAddress($uid);
  80. $data['seckill_id'] = $seckill_id;
  81. $data['combination_id'] = $combination_id;
  82. $data['bargain_id'] = $bargain_id;
  83. $data['cartInfo'] = $cartInfo;
  84. $data['priceGroup'] = $priceGroup;
  85. $data['orderKey'] = StoreOrder::cacheOrderInfo($uid, $cartInfo, $priceGroup, $other);
  86. $data['offlinePostage'] = $other['offlinePostage'];
  87. $vipId = UserLevel::getUserLevel($uid);
  88. $user = $request->user();
  89. if (isset($user['pwd'])) unset($user['pwd']);
  90. $user['vip'] = $vipId !== false ? true : false;
  91. if ($user['vip']) {
  92. $user['vip_id'] = $vipId;
  93. $user['discount'] = UserLevel::getUserLevelInfo($vipId, 'discount');
  94. }
  95. $data['userInfo'] = $user;
  96. $data['integralRatio'] = $other['integralRatio'];
  97. $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2;
  98. $data['store_self_mention'] = (int)sys_config('store_self_mention') ?? 0;//门店自提是否开启
  99. $data['system_store'] = ($res = SystemStore::getStoreDispose()) ? $res : [];//门店信息
  100. return app('json')->successful($data);
  101. }
  102. /**
  103. * 计算订单金额
  104. * @param Request $request
  105. * @param $key
  106. * @return mixed
  107. * @throws \think\Exception
  108. * @throws \think\db\exception\DataNotFoundException
  109. * @throws \think\db\exception\ModelNotFoundException
  110. * @throws \think\exception\DbException
  111. */
  112. public function computedOrder(Request $request, $key)
  113. {
  114. // $priceGroup = StoreOrder::getOrderPriceGroup($cartInfo);
  115. if (!$key) return app('json')->fail('参数错误!');
  116. $uid = $request->uid();
  117. if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
  118. return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
  119. list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $shipping_type,$userConsumption) = UtilService::postMore([
  120. 'addressId', 'couponId', ['payType', 'yue'], ['useIntegral', 0], 'mark', ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''],
  121. ['shipping_type', 1],['userConsumption']
  122. ], $request, true);
  123. $payType = strtolower($payType);
  124. if ($bargainId) {
  125. $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
  126. if (!$bargainUserTableId)
  127. return app('json')->fail('砍价失败');
  128. $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
  129. if ($status == 3)
  130. return app('json')->fail('砍价已支付');
  131. StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
  132. }
  133. if ($pinkId) {
  134. if (StorePink::getIsPinkUid($pinkId, $request->uid()))
  135. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  136. if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
  137. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  138. }
  139. $priceGroup = StoreOrder::cacheKeyCreateOrder($userConsumption,$request->uid(), $key, $addressId, $payType, (int)$useIntegral, $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, true, 0, $shipping_type);
  140. if ($priceGroup)
  141. return app('json')->status('NONE', 'ok', $priceGroup);
  142. else
  143. return app('json')->fail(StoreOrder::getErrorInfo('计算失败'));
  144. }
  145. /**
  146. * 订单创建
  147. * @param Request $request
  148. * @param $key
  149. * @return mixed
  150. * @throws \think\Exception
  151. * @throws \think\db\exception\DataNotFoundException
  152. * @throws \think\db\exception\ModelNotFoundException
  153. * @throws \think\exception\DbException
  154. */
  155. public function create(Request $request, $key)
  156. {
  157. if (!$key) return app('json')->fail('参数错误!');
  158. $uid = $request->uid();
  159. if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
  160. return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
  161. list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $from, $shipping_type, $real_name, $phone, $storeId,$userConsumption) = UtilService::postMore([
  162. 'addressId', 'couponId', 'payType', ['useIntegral', 0], 'mark', ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''], ['from', 'weixin'],
  163. ['shipping_type', 1], ['real_name', ''], ['phone', ''], ['store_id', 0],['userConsumption']
  164. ], $request, true);
  165. $payType = strtolower($payType);
  166. if ($bargainId) {
  167. $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
  168. if (!$bargainUserTableId)
  169. return app('json')->fail('砍价失败');
  170. $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
  171. if ($status == 3)
  172. return app('json')->fail('砍价已支付');
  173. StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
  174. }
  175. if ($pinkId) {
  176. if (StorePink::getIsPinkUid($pinkId, $request->uid()))
  177. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  178. if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
  179. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
  180. }
  181. $isChannel = 1;
  182. if ($from == 'weixin')
  183. $isChannel = 0;
  184. elseif ($from == 'weixinh5')
  185. $isChannel = 2;
  186. $order = StoreOrder::cacheKeyCreateOrder($userConsumption,$request->uid(), $key, $addressId, $payType, (int)$useIntegral, $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, false, $isChannel, $shipping_type, $real_name, $phone, $storeId);
  187. if ($order === false) return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败'));
  188. $orderId = $order['order_id'];
  189. $info = compact('orderId', 'key');
  190. if ($orderId) {
  191. event('OrderCreated', [$order]); //订单创建成功事件
  192. event('ShortMssageSend', [$orderId, 'AdminPlaceAnOrder']);//发送管理员通知
  193. switch ($payType) {
  194. case "weixin":
  195. $orderInfo = StoreOrder::where('order_id', $orderId)->find();
  196. if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
  197. $orderInfo = $orderInfo->toArray();
  198. if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
  199. //支付金额为0
  200. if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
  201. //创建订单jspay支付
  202. $payPriceStatus = StoreOrder::jsPayPrice($orderId, $uid, $formId);
  203. if ($payPriceStatus)//0元支付成功
  204. return app('json')->status('success', '微信支付成功', $info);
  205. else
  206. return app('json')->status('pay_error', StoreOrder::getErrorInfo());
  207. } else {
  208. try {
  209. if ($from == 'routine') {
  210. $jsConfig = OrderRepository::jsPay($orderId); //创建订单jspay
  211. } else if ($from == 'weixinh5') {
  212. $jsConfig = OrderRepository::h5Pay($orderId);
  213. } else {
  214. $jsConfig = OrderRepository::wxPay($orderId);
  215. }
  216. } catch (\Exception $e) {
  217. return app('json')->status('pay_error', $e->getMessage(), $info);
  218. }
  219. $info['jsConfig'] = $jsConfig;
  220. if ($from == 'weixinh5') {
  221. return app('json')->status('wechat_h5_pay', '订单创建成功', $info);
  222. } else {
  223. return app('json')->status('wechat_pay', '订单创建成功', $info);
  224. }
  225. }
  226. break;
  227. case 'yue':
  228. if (StoreOrder::yuePay($orderId, $request->uid(), $formId))
  229. return app('json')->status('success', '余额支付成功', $info);
  230. else {
  231. $errorinfo = StoreOrder::getErrorInfo();
  232. if (is_array($errorinfo))
  233. return app('json')->status($errorinfo['status'], $errorinfo['msg'], $info);
  234. else
  235. return app('json')->status('pay_error', $errorinfo);
  236. }
  237. break;
  238. case 'alipay':
  239. if ($order['pay_price'] <= 0){
  240. if (StoreOrder::yuePay($orderId, $request->uid(), $formId))
  241. return app('json')->status('success', '余额支付成功', $info);
  242. else {
  243. $errorinfo = StoreOrder::getErrorInfo();
  244. if (is_array($errorinfo))
  245. return app('json')->status($errorinfo['status'], $errorinfo['msg'], $info);
  246. else
  247. return app('json')->status('pay_error', $errorinfo);
  248. }
  249. break;
  250. }else{
  251. $payment = new \AdaPaySdk\Payment();
  252. # 支付设置
  253. $payment_params = array(
  254. 'app_id'=> 'app_3dc215b5-ade5-47d8-8461-ddb796bd5e06',
  255. 'order_no'=> $order['order_id'].'-'.rand(100000, 999999),
  256. 'pay_channel'=> 'alipay_wap',
  257. //'time_expire'=> date("YmdHis", time()+86400),
  258. 'pay_amt'=> sprintf("%01.2f",$order['pay_price']),
  259. 'goods_title'=> '环球优购',
  260. 'goods_desc'=> '环球优购',
  261. 'description'=> 'alipay',
  262. 'device_info'=> ['device_p'=> $_SERVER ["REMOTE_ADDR"]],
  263. 'callback_url' => 'http://yg.hqgjsmc.com/index',
  264. 'notify_url' => 'http://yg.hqgjsmc.com/api/adapay/notify'
  265. );
  266. $payment->create($payment_params);
  267. if ($payment->isError()){
  268. //失败处理
  269. return app('json')->fail('支付失败');
  270. } else {
  271. //成功处理
  272. return app('json')->status('alipay', ['jsConfig' => $payment->result, 'orderId' => $order['order_id']]);
  273. }
  274. break;
  275. }
  276. case 'weixin_s':
  277. $payment = new \AdaPaySdk\Payment();
  278. # 支付设置
  279. $payment_params = array(
  280. 'app_id'=> 'app_3dc215b5-ade5-47d8-8461-ddb796bd5e06',
  281. 'order_no'=> $order['order_id'].'-'.rand(100000, 999999),
  282. 'pay_channel'=> 'wx_lite',
  283. //'time_expire'=> date("YmdHis", time()+86400),
  284. 'pay_amt'=> sprintf("%01.2f",$order['pay_price']),
  285. 'currency' => 'cny',
  286. 'goods_title'=> '环球优购',
  287. 'goods_desc'=> '环球优购',
  288. 'description'=> 'weixin',
  289. 'device_info'=> ['device_p'=> $_SERVER ["REMOTE_ADDR"]],
  290. 'expend' => ['open_id' => 'oPVIJ62WxFA5NXYGgiTPdx_uGb3Q'],
  291. 'callback_url' => 'http://yg.hqgjsmc.com/index',
  292. 'notify_url' => 'http://yg.hqgjsmc.com/api/adapay/notify'
  293. );
  294. $payment->create($payment_params);
  295. if ($payment->isError()){
  296. //失败处理
  297. return app('json')->fail('支付失败');
  298. } else {
  299. //成功处理
  300. $pay = json_decode($payment->result['expend']['pay_info']);
  301. //成功处理
  302. return app('json')->status('alipay', ['jsConfig' => $pay, 'orderId' => $order['order_id']]);
  303. }
  304. break;
  305. case 'offline':
  306. return app('json')->status('success', '订单创建成功', $info);
  307. break;
  308. }
  309. } else return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败!'));
  310. }
  311. /**
  312. * 订单 再次下单
  313. * @param Request $request
  314. * @return mixed
  315. */
  316. public function again(Request $request)
  317. {
  318. list($uni) = UtilService::postMore([
  319. ['uni', ''],
  320. ], $request, true);
  321. if (!$uni) return app('json')->fail('参数错误!');
  322. $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
  323. if (!$order) return app('json')->fail('订单不存在!');
  324. $order = StoreOrder::tidyOrder($order, true);
  325. $res = [];
  326. foreach ($order['cartInfo'] as $v) {
  327. if ($v['combination_id']) return app('json')->fail('拼团产品不能再来一单,请在拼团产品内自行下单!');
  328. else if ($v['bargain_id']) return app('json')->fail('砍价产品不能再来一单,请在砍价产品内自行下单!');
  329. else if ($v['seckill_id']) return app('json')->ail('秒杀产品不能再来一单,请在秒杀产品内自行下单!');
  330. else $res[] = StoreCart::setCart($request->uid(), $v['product_id'], $v['cart_num'], isset($v['productInfo']['attrInfo']['unique']) ? $v['productInfo']['attrInfo']['unique'] : '', 'product', 0, 0);
  331. }
  332. $cateId = [];
  333. foreach ($res as $v) {
  334. if (!$v) return app('json')->fail('再来一单失败,请重新下单!');
  335. $cateId[] = $v['id'];
  336. }
  337. event('OrderCreateAgain', implode(',', $cateId));
  338. return app('json')->successful('ok', ['cateId' => implode(',', $cateId)]);
  339. }
  340. /**
  341. * 订单支付
  342. * @param Request $request
  343. * @return mixed
  344. */
  345. public function pay(Request $request)
  346. {
  347. list($uni, $paytype, $from) = UtilService::postMore([
  348. ['uni', ''],
  349. ['paytype', 'weixin'],
  350. ['from', 'weixin']
  351. ], $request, true);
  352. if (!$uni) return app('json')->fail('参数错误!');
  353. $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
  354. $orderInfo = StoreOrderCartInfo::where('oid', $order['id'])->select();
  355. if ($order){
  356. foreach ($orderInfo as $item)
  357. {
  358. $cate_id = StoreProduct::where('id', $item['product_id'])->value('cate_id');
  359. $pid = StoreCategory::where('id', $cate_id)->find();
  360. $cate = StoreCategory::select()->toArray();
  361. $cateId = getParent_cate($pid['pid'], $cate);
  362. $number = 0;
  363. if ($item['cart_info']['productInfo']['give_integral'] > 0 and $cateId[0] == 1)
  364. {
  365. for ($i = 1; $i <= $item['cart_info']['cart_num']; $i++){
  366. $number += 1;
  367. }
  368. }
  369. }
  370. if ($number > 0){
  371. $user = \app\models\user\User::where('uid', $order['uid'])->find();
  372. $user['shop_number'] += $number;
  373. $shop_number = sys_config('shop_number');
  374. if ($user['shop_number'] > $shop_number) return app('json')->fail('环球优购商品购买已达到上限');
  375. }
  376. }
  377. if (!$order)
  378. return app('json')->fail('订单不存在!');
  379. if ($order['paid'])
  380. return app('json')->fail('该订单已支付!');
  381. if ($order['pink_id']) if (StorePink::isPinkStatus($order['pink_id']))
  382. return app('json')->fail('该订单已失效!');
  383. if ($from == 'weixin') {//0
  384. if (in_array($order->is_channel, [1, 2]))
  385. $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  386. }
  387. if ($from == 'weixinh5') {//2
  388. if (in_array($order->is_channel, [0, 1]))
  389. $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  390. }
  391. if ($from == 'routine') {//1
  392. if (in_array($order->is_channel, [0, 2]))
  393. $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  394. }
  395. $order['pay_type'] = $paytype; //重新支付选择支付方式
  396. switch ($order['pay_type']) {
  397. case 'weixin':
  398. try {
  399. if ($from == 'routine') {
  400. $jsConfig = OrderRepository::jsPay($order); //订单列表发起支付
  401. } else if ($from == 'weixinh5') {
  402. $jsConfig = OrderRepository::h5Pay($order);
  403. } else {
  404. $jsConfig = OrderRepository::wxPay($order);
  405. }
  406. } catch (\Exception $e) {
  407. return app('json')->fail($e->getMessage());
  408. }
  409. if ($from == 'weixinh5') {
  410. return app('json')->status('wechat_h5_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
  411. } else {
  412. return app('json')->status('wechat_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
  413. }
  414. break;
  415. case 'yue':
  416. if (StoreOrder::yuePay($order['order_id'], $request->uid()))
  417. return app('json')->status('success', '余额支付成功');
  418. else {
  419. $error = StoreOrder::getErrorInfo();
  420. return app('json')->fail(is_array($error) && isset($error['msg']) ? $error['msg'] : $error);
  421. }
  422. break;
  423. case 'alipay':
  424. if ($order['pay_price'] <= 0){
  425. if (StoreOrder::yuePay($order['order_id'], $request->uid()))
  426. return app('json')->status('success', '余额支付成功');
  427. else {
  428. $error = StoreOrder::getErrorInfo();
  429. return app('json')->fail(is_array($error) && isset($error['msg']) ? $error['msg'] : $error);
  430. }
  431. break;
  432. }else{
  433. $payment = new \AdaPaySdk\Payment();
  434. # 支付设置
  435. $payment_params = array(
  436. 'app_id'=> 'app_3dc215b5-ade5-47d8-8461-ddb796bd5e06',
  437. 'order_no'=> $order['order_id'].'-'.rand(100000, 999999),
  438. 'pay_channel'=> 'alipay_wap',
  439. //'time_expire'=> date("YmdHis", time()+86400),
  440. 'pay_amt'=> $order['pay_price'],
  441. 'goods_title'=> '环球优购',
  442. 'goods_desc'=> '环球优购',
  443. 'description'=> 'alipay',
  444. 'device_info'=> ['device_p'=> $_SERVER ["REMOTE_ADDR"]],
  445. 'callback_url' => 'http://yg.hqgjsmc.com/index',
  446. 'notify_url' => 'http://yg.hqgjsmc.com/api/adapay/notify'
  447. );
  448. $payment->create($payment_params);
  449. if ($payment->isError()){
  450. //失败处理
  451. return app('json')->fail('支付失败');
  452. } else {
  453. //成功处理
  454. return app('json')->status('alipay', ['jsConfig' => $payment->result, 'order_id' => $order['order_id']]);
  455. }
  456. break;
  457. }
  458. case 'weixin_s':
  459. $payment = new \AdaPaySdk\Payment();
  460. # 支付设置
  461. $payment_params = array(
  462. 'app_id'=> 'app_3dc215b5-ade5-47d8-8461-ddb796bd5e06',
  463. 'order_no'=> $order['order_id'].'-'.rand(100000, 999999),
  464. 'pay_channel'=> 'wx_lite',
  465. //'time_expire'=> date("YmdHis", time()+86400),
  466. 'pay_amt'=> $order['pay_price'],
  467. 'currency' => 'cny',
  468. 'goods_title'=> '环球优购',
  469. 'goods_desc'=> '环球优购',
  470. 'description'=> 'weixin',
  471. 'device_info'=> ['device_p'=> $_SERVER ["REMOTE_ADDR"]],
  472. 'expend' => ['open_id' => 'oPVIJ62WxFA5NXYGgiTPdx_uGb3Q'],
  473. 'callback_url' => 'http://yg.hqgjsmc.com/index',
  474. 'notify_url' => 'http://yg.hqgjsmc.com/api/adapay/notify'
  475. );
  476. $payment->create($payment_params);
  477. if ($payment->isError()){
  478. //失败处理
  479. return app('json')->fail('支付失败');
  480. } else {
  481. $pay = json_decode($payment->result['expend']['pay_info']);
  482. //成功处理
  483. return app('json')->status('alipay', ['jsConfig' => $pay, 'orderId' => $order['order_id']]);
  484. }
  485. break;
  486. case 'offline':
  487. StoreOrder::createOrderTemplate($order);
  488. if (StoreOrder::setOrderTypePayOffline($order['order_id']))
  489. return app('json')->status('success', '订单创建成功');
  490. else
  491. return app('json')->status('success', '支付失败');
  492. break;
  493. }
  494. return app('json')->fail('支付方式错误');
  495. }
  496. /**
  497. * 订单列表
  498. * @param Request $request
  499. * @return mixed
  500. */
  501. public function lst(Request $request)
  502. {
  503. list($type, $page, $limit, $search) = UtilService::getMore([
  504. ['type', ''],
  505. ['page', 0],
  506. ['limit', ''],
  507. ['search', ''],
  508. ], $request, true);
  509. return app('json')->successful(StoreOrder::getUserOrderSearchList($request->uid(), $type, $page, $limit, $search));
  510. }
  511. /**
  512. * 订单详情
  513. * @param Request $request
  514. * @param $uni
  515. * @return mixed
  516. */
  517. public function detail(Request $request, $uni)
  518. {
  519. if (!strlen(trim($uni))) return app('json')->fail('参数错误');
  520. $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
  521. if (!$order) return app('json')->fail('订单不存在');
  522. $order = $order->toArray();
  523. //是否开启门店自提
  524. $store_self_mention = sys_config('store_self_mention');
  525. //关闭门店自提后 订单隐藏门店信息
  526. if ($store_self_mention == 0) $order['shipping_type'] = 1;
  527. if ($order['verify_code']) {
  528. $verify_code = $order['verify_code'];
  529. $verify[] = substr($verify_code, 0, 4);
  530. $verify[] = substr($verify_code, 4, 4);
  531. $verify[] = substr($verify_code, 8);
  532. $order['_verify_code'] = implode(' ', $verify);
  533. }
  534. $order['add_time_y'] = date('Y-m-d', $order['add_time']);
  535. $order['add_time_h'] = date('H:i:s', $order['add_time']);
  536. $order['system_store'] = SystemStore::getStoreDispose($order['store_id']);
  537. if ($order['shipping_type'] === 2 && $order['verify_code']) {
  538. $name = $order['verify_code'] . '.jpg';
  539. $imageInfo = SystemAttachment::getInfo($name, 'name');
  540. $siteUrl = sys_config('site_url');
  541. if (!$imageInfo) {
  542. $imageInfo = UtilService::getQRCodePath($order['verify_code'], $name);
  543. if (is_array($imageInfo)) {
  544. SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
  545. $url = $imageInfo['dir'];
  546. } else
  547. $url = '';
  548. } else $url = $imageInfo['att_dir'];
  549. if (isset($imageInfo['image_type']) && $imageInfo['image_type'] == 1) $url = $siteUrl . $url;
  550. $order['code'] = $url;
  551. }
  552. $order['mapKey'] = sys_config('tengxun_map_key');
  553. return app('json')->successful('ok', StoreOrder::tidyOrder($order, true, true));
  554. }
  555. /**
  556. * 订单删除
  557. * @param Request $request
  558. * @return mixed
  559. */
  560. public function del(Request $request)
  561. {
  562. list($uni) = UtilService::postMore([
  563. ['uni', ''],
  564. ], $request, true);
  565. if (!$uni) return app('json')->fail('参数错误!');
  566. $res = StoreOrder::removeOrder($uni, $request->uid());
  567. if ($res)
  568. return app('json')->successful();
  569. else
  570. return app('json')->fail(StoreOrder::getErrorInfo());
  571. }
  572. /**
  573. * 订单收货
  574. * @param Request $request
  575. * @return mixed
  576. */
  577. public function take(Request $request)
  578. {
  579. list($uni) = UtilService::postMore([
  580. ['uni', ''],
  581. ], $request, true);
  582. if (!$uni) return app('json')->fail('参数错误!');
  583. $res = StoreOrder::takeOrder($uni, $request->uid());
  584. if ($res) {
  585. $order_info = StoreOrder::where('order_id', $uni)->find();
  586. $gain_integral = intval($order_info['gain_integral']);
  587. $gain_coupon = StoreCouponIssue::alias('a')
  588. ->join('store_coupon b', 'a.cid = b.id')
  589. ->where('a.status', 1)
  590. ->where('a.is_full_give', 1)
  591. ->where('a.is_del', 0)
  592. ->where('a.full_reduction', '<=', $order_info['total_price'])
  593. ->sum('b.coupon_price');
  594. return app('json')->successful(['gain_integral' => $gain_integral, 'gain_coupon' => $gain_coupon]);
  595. } else
  596. return app('json')->fail(StoreOrder::getErrorInfo());
  597. }
  598. /**
  599. * 订单 查看物流
  600. * @param Request $request
  601. * @param $uni
  602. * @return mixed
  603. */
  604. public function express(Request $request, $uni)
  605. {
  606. if (!$uni || !($order = StoreOrder::getUserOrderDetail($request->uid(), $uni))) return app('json')->fail('查询订单不存在!');
  607. if ($order['delivery_type'] != 'express' || !$order['delivery_id']) return app('json')->fail('该订单不存在快递单号!');
  608. $cacheName = $uni . $order['delivery_id'];
  609. $result = CacheService::get($cacheName, null);
  610. if ($result === NULL) {
  611. $result = ExpressService::query($order['delivery_id']);
  612. if (is_array($result) &&
  613. isset($result['result']) &&
  614. isset($result['result']['deliverystatus']) &&
  615. $result['result']['deliverystatus'] >= 3)
  616. $cacheTime = 0;
  617. else
  618. $cacheTime = 1800;
  619. CacheService::set($cacheName, $result, $cacheTime);
  620. }
  621. $orderInfo = [];
  622. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?? [];
  623. $info = [];
  624. $cartNew = [];
  625. foreach ($cartInfo as $k => $cart) {
  626. $cart = json_decode($cart, true);
  627. $cartNew['cart_num'] = $cart['cart_num'];
  628. $cartNew['truePrice'] = $cart['truePrice'];
  629. $cartNew['productInfo']['image'] = $cart['productInfo']['image'];
  630. $cartNew['productInfo']['store_name'] = $cart['productInfo']['store_name'];
  631. $cartNew['productInfo']['unit_name'] = $cart['productInfo']['unit_name'] ?? '';
  632. array_push($info, $cartNew);
  633. unset($cart);
  634. }
  635. $orderInfo['delivery_id'] = $order['delivery_id'];
  636. $orderInfo['delivery_name'] = $order['delivery_name'];
  637. $orderInfo['delivery_type'] = $order['delivery_type'];
  638. $orderInfo['cartInfo'] = $info;
  639. return app('json')->successful(['order' => $orderInfo, 'express' => $result ? $result : []]);
  640. }
  641. /**
  642. * 订单评价
  643. * @param Request $request
  644. * @return mixed
  645. * @throws \think\db\exception\DataNotFoundException
  646. * @throws \think\db\exception\ModelNotFoundException
  647. * @throws \think\exception\DbException
  648. */
  649. public function comment(Request $request)
  650. {
  651. $group = UtilService::postMore([
  652. ['unique', ''], ['comment', ''], ['pics', ''], ['product_score', 5], ['service_score', 5]
  653. ], $request);
  654. $unique = $group['unique'];
  655. unset($group['unique']);
  656. if (!$unique) return app('json')->fail('参数错误!');
  657. $cartInfo = StoreOrderCartInfo::where('unique', $unique)->find();
  658. $uid = $request->uid();
  659. $user_info = User::get($uid);
  660. $group['nickname'] = $user_info['nickname'];
  661. $group['avatar'] = $user_info['avatar'];
  662. if (!$cartInfo) return app('json')->fail('评价产品不存在!');
  663. $orderUid = StoreOrder::getOrderInfo($cartInfo['oid'], 'uid')['uid'];
  664. if ($uid != $orderUid) return app('json')->fail('评价产品不存在!');
  665. if (StoreProductReply::be(['oid' => $cartInfo['oid'], 'unique' => $unique]))
  666. return app('json')->fail('该产品已评价!');
  667. $group['comment'] = htmlspecialchars(trim($group['comment']));
  668. if ($group['product_score'] < 1) return app('json')->fail('请为产品评分');
  669. else if ($group['service_score'] < 1) return app('json')->fail('请为商家服务评分');
  670. if ($cartInfo['cart_info']['combination_id']) $productId = $cartInfo['cart_info']['product_id'];
  671. else if ($cartInfo['cart_info']['seckill_id']) $productId = $cartInfo['cart_info']['product_id'];
  672. else if ($cartInfo['cart_info']['bargain_id']) $productId = $cartInfo['cart_info']['product_id'];
  673. else $productId = $cartInfo['product_id'];
  674. if ($group['pics']) $group['pics'] = json_encode(is_array($group['pics']) ? $group['pics'] : explode(',', $group['pics']));
  675. $group = array_merge($group, [
  676. 'uid' => $uid,
  677. 'oid' => $cartInfo['oid'],
  678. 'unique' => $unique,
  679. 'product_id' => $productId,
  680. 'add_time' => time(),
  681. 'reply_type' => 'product'
  682. ]);
  683. StoreProductReply::beginTrans();
  684. $res = StoreProductReply::reply($group, 'product');
  685. if (!$res) {
  686. StoreProductReply::rollbackTrans();
  687. return app('json')->fail('评价失败!');
  688. }
  689. try {
  690. StoreOrder::checkOrderOver($cartInfo['oid']);
  691. } catch (\Exception $e) {
  692. StoreProductReply::rollbackTrans();
  693. return app('json')->fail($e->getMessage());
  694. }
  695. StoreProductReply::commitTrans();
  696. event('UserCommented', $res);
  697. event('AdminNewPush');
  698. return app('json')->successful();
  699. }
  700. /**
  701. * 订单统计数据
  702. * @param Request $request
  703. * @return mixed
  704. */
  705. public function data(Request $request)
  706. {
  707. return app('json')->successful(StoreOrder::getOrderData($request->uid()));
  708. }
  709. /**
  710. * 订单退款理由
  711. * @return mixed
  712. */
  713. public function refund_reason()
  714. {
  715. $reason = sys_config('stor_reason') ?: [];//退款理由
  716. $reason = str_replace("\r\n", "\n", $reason);//防止不兼容
  717. $reason = explode("\n", $reason);
  718. return app('json')->successful($reason);
  719. }
  720. /**
  721. * 订单退款审核
  722. * @param Request $request
  723. * @return mixed
  724. */
  725. public function refund_verify(Request $request)
  726. {
  727. $data = UtilService::postMore([
  728. ['text', ''],
  729. ['refund_reason_wap_img', ''],
  730. ['refund_reason_wap_explain', ''],
  731. ['uni', '']
  732. ], $request);
  733. $uni = $data['uni'];
  734. unset($data['uni']);
  735. if ($data['refund_reason_wap_img']) $data['refund_reason_wap_img'] = explode(',', $data['refund_reason_wap_img']);
  736. if (!$uni || $data['text'] == '') return app('json')->fail('参数错误!');
  737. $res = StoreOrder::orderApplyRefund($uni, $request->uid(), $data['text'], $data['refund_reason_wap_explain'], $data['refund_reason_wap_img']);
  738. if ($res)
  739. return app('json')->successful('提交申请成功');
  740. else
  741. return app('json')->fail(StoreOrder::getErrorInfo());
  742. }
  743. /**
  744. * 订单取消 未支付的订单回退积分,回退优惠券,回退库存
  745. * @param Request $request
  746. * @return mixed
  747. * @throws \think\db\exception\DataNotFoundException
  748. * @throws \think\db\exception\ModelNotFoundException
  749. * @throws \think\exception\DbException
  750. */
  751. public function cancel(Request $request)
  752. {
  753. list($id) = UtilService::postMore([['id', 0]], $request, true);
  754. if (!$id) return app('json')->fail('参数错误');
  755. if (StoreOrder::cancelOrder($id, $request->uid()))
  756. return app('json')->successful('取消订单成功');
  757. return app('json')->fail(StoreOrder::getErrorInfo('取消订单失败'));
  758. }
  759. /**
  760. * 订单产品信息
  761. * @param Request $request
  762. * @return mixed
  763. * @throws \think\db\exception\DataNotFoundException
  764. * @throws \think\db\exception\ModelNotFoundException
  765. * @throws \think\exception\DbException
  766. */
  767. public function product(Request $request)
  768. {
  769. list($unique) = UtilService::postMore([['unique', '']], $request, true);
  770. if (!$unique || !StoreOrderCartInfo::be(['unique' => $unique]) || !($cartInfo = StoreOrderCartInfo::where('unique', $unique)->find())) return app('json')->fail('评价产品不存在!');
  771. $cartInfo = $cartInfo->toArray();
  772. $cartProduct = [];
  773. $cartProduct['cart_num'] = $cartInfo['cart_info']['cart_num'];
  774. $cartProduct['productInfo']['image'] = isset($cartInfo['cart_info']['productInfo']['image']) ? $cartInfo['cart_info']['productInfo']['image'] : '';
  775. $cartProduct['productInfo']['price'] = isset($cartInfo['cart_info']['productInfo']['price']) ? $cartInfo['cart_info']['productInfo']['price'] : 0;
  776. $cartProduct['productInfo']['store_name'] = isset($cartInfo['cart_info']['productInfo']['store_name']) ? $cartInfo['cart_info']['productInfo']['store_name'] : '';
  777. if (isset($cartInfo['cart_info']['productInfo']['attrInfo'])) {
  778. $cartProduct['productInfo']['attrInfo']['product_id'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['product_id']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['product_id'] : '';
  779. $cartProduct['productInfo']['attrInfo']['suk'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['suk']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['suk'] : '';
  780. $cartProduct['productInfo']['attrInfo']['price'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['price']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['price'] : '';
  781. $cartProduct['productInfo']['attrInfo']['image'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['image']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['image'] : '';
  782. }
  783. $cartProduct['product_id'] = isset($cartInfo['cart_info']['product_id']) ? $cartInfo['cart_info']['product_id'] : 0;
  784. $cartProduct['combination_id'] = isset($cartInfo['cart_info']['combination_id']) ? $cartInfo['cart_info']['combination_id'] : 0;
  785. $cartProduct['seckill_id'] = isset($cartInfo['cart_info']['seckill_id']) ? $cartInfo['cart_info']['seckill_id'] : 0;
  786. $cartProduct['bargain_id'] = isset($cartInfo['cart_info']['bargain_id']) ? $cartInfo['cart_info']['bargain_id'] : 0;
  787. $cartProduct['order_id'] = StoreOrder::where('id', $cartInfo['oid'])->value('order_id');
  788. return app('json')->successful($cartProduct);
  789. }
  790. /**
  791. * 首页获取未支付订单
  792. */
  793. public function get_noPay(Request $request)
  794. {
  795. return app('json')->successful(StoreOrder::getUserOrderSearchList($request->uid(), 0, 0, 0, ''));
  796. }
  797. }