OrderService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. namespace app\admin\service\order;
  3. use app\model\GoodsRunning;
  4. use app\model\GoodsSku;
  5. use app\model\Member;
  6. use app\model\Order;
  7. use app\model\OrderSheet;
  8. use app\model\PayDetail;
  9. use app\model\SysDept;
  10. use support\Db;
  11. use support\exception\BusinessException;
  12. use support\Log as SupportLog;
  13. use support\Redis;
  14. use Yansongda\Pay\Exceptions\GatewayException;
  15. use Yansongda\Pay\Log;
  16. use Yansongda\Pay\Pay;
  17. class OrderService
  18. {
  19. /**
  20. * @Desc 自动确认收货
  21. * @Author Gorden
  22. * @Date 2024/4/11 16:09
  23. *
  24. * @return void
  25. */
  26. public static function AutomaticReceipt()
  27. {
  28. try {
  29. Db::beginTransaction();
  30. $timeUnix = strtotime("-7 days");
  31. $orders = Order::where('order_status_system', 'SIGNED')
  32. ->where('order_addtimes', '<', $timeUnix)
  33. ->get();
  34. foreach ($orders as $order) {
  35. // 订单主表
  36. Order::where('order_id', $order->order_id)->update([
  37. 'order_is_complete' => 'Y',
  38. 'order_status_system' => 'CONFIRM',
  39. 'order_status_storage' => 'DONE'
  40. ]);
  41. // 订单详情表
  42. OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'DONE']);
  43. // 7天后自动完成 order_is_complete=Y
  44. // $redis = Redis::connection();
  45. // $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
  46. // $redis->sadd($key, $order->order_id);
  47. }
  48. Db::commit();
  49. } catch (\Exception $e) {
  50. Db::rollBack();
  51. }
  52. }
  53. /**
  54. * @Desc 自动完成订单
  55. * @Author Gorden
  56. * @Date 2024/7/16 9:37
  57. *
  58. * @return void
  59. */
  60. public static function AutomaticComplete()
  61. {
  62. Db::beginTransaction();
  63. try {
  64. $redis = Redis::connection();
  65. $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd');
  66. $orderIds = $redis->smembers($key);
  67. foreach ($orderIds as $orderId) {
  68. $order = Order::where('order_id', $orderId)
  69. ->select('order_is_complete', 'order_category', 'order_status_system')
  70. ->first();
  71. if ($order && $order->order_is_complete != 'Y' && $order->order_category != 'RETURN' && in_array($order->order_status_system, ['RECVING', 'SIGNED', 'CONFIRM'])) {
  72. // 更新主表
  73. Order::where('order_id', $orderId)->update(['order_is_complete' => 'Y', 'order_status_system' => 'CONFIRM', 'order_status_storage' => 'DONE']);
  74. // sheet表
  75. OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
  76. }
  77. }
  78. $redis->del($key);
  79. Db::commit();
  80. } catch (\Exception $e) {
  81. dump($e->getMessage());
  82. Db::rollBack();
  83. }
  84. }
  85. public static function checkPayingOrder()
  86. {
  87. try {
  88. Db::beginTransaction();
  89. $timeUnix = strtotime("-30 minutes");
  90. $orders = Order::where('order_status_system', 'PAYING')
  91. ->where('order_category', '<>', 'DISHES') // 点餐不自动取消
  92. // ->where('order_platform','<>','SYSTEM') // 后台产生的订单不自动取消
  93. ->where(function ($query) {
  94. $query->where('order_platform', '<>', 'SYSTEM')->orWhereNull('order_platform');
  95. })
  96. ->where('order_addtimes', '<', $timeUnix)
  97. ->get();
  98. foreach ($orders as $order) {
  99. // 订单主表
  100. Order::where('order_id', $order->order_id)->update([
  101. 'order_is_complete' => 'Y',
  102. 'order_status_system' => 'CANCEL',
  103. 'order_status_payment' => 'CANCEL'
  104. ]);
  105. $sheets = OrderSheet::where('join_sheet_order_id', $order->order_id)->get();
  106. foreach ($sheets as $sheet) {
  107. // 还原库存
  108. $goodsSku = GoodsSku::where('goods_sku_id', $sheet->join_sheet_goods_sku_id)->first();
  109. if (!empty($goodsSku) && !empty($goodsSku->goods_sku_storage_json)) {
  110. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  111. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  112. $skuStorageJson['storage'] = $skuStorageJson['storage'] + $sheet->order_sheet_num;
  113. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  114. $goodsSku->save();
  115. }
  116. }
  117. $goodsRunning = GoodsRunning::where('join_running_goods_id', $sheet->join_sheet_goods_id)->first();
  118. if (!empty($goodsRunning)) {
  119. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $sheet->order_sheet_num;
  120. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $sheet->order_sheet_num;
  121. $goodsRunning->save();
  122. }
  123. }
  124. // 订单详情表
  125. OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'CANCEL']);
  126. // 支付表
  127. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  128. if (!empty($payDetail)) {
  129. $payExtendJson = [];
  130. if (!empty($payDetail->pay_extend_json)) {
  131. $payExtendJson = json_decode($payDetail->pay_extend_json, true);
  132. }
  133. $payExtendJson['cancel_times'] = date('Y-m-d H:i:s');
  134. PayDetail::where('join_pay_order_id', $order->order_groupby)->update([
  135. 'pay_status' => 'CANCEL',
  136. 'pay_extend_json' => json_encode($payExtendJson)
  137. ]);
  138. }
  139. }
  140. Db::commit();
  141. } catch (\Exception $e) {
  142. Db::rollBack();
  143. }
  144. }
  145. public static function generateWriteOffData($params)
  146. {
  147. return [
  148. 'charge' => [
  149. 'charge_amount' => 1,
  150. 'charge_content' => $params['order_remark'] ?? '',
  151. 'charge_user_id' => $params['write_off_member_id'],
  152. 'charge_premises' => $params['dept_premises_id'],
  153. ],
  154. 'member_id' => $params['join_order_member_id']
  155. ];
  156. }
  157. public static function generateAppointmentApplyData($params)
  158. {
  159. $member = Member::with('cert', 'info')
  160. ->where('member_id', $params['join_order_member_id'])
  161. ->first();
  162. $name = '';
  163. if (!empty($member) && !empty($member->cert) && !empty($member->cert->member_cert_name)) {
  164. $name = $member->cert->member_cert_name;
  165. } else if (!empty($member) && !empty($member->info) && !empty($member->info->member_info_nickname)) {
  166. $name = $member->info->member_info_nickname;
  167. }
  168. return [
  169. 'name' => $name,
  170. 'times' => '',
  171. 'mobile' => !empty($member) ? $member->member_mobile : '',
  172. 'person' => $params['order_sheet_num'] ?? '',
  173. 'premises' => $params['dept_premises_id'] ?? ''
  174. ];
  175. }
  176. /**
  177. * 微信支付宝扫码支付
  178. */
  179. public static function qrcodePay($params)
  180. {
  181. $log = SupportLog::channel('pay');
  182. $log->info("PAY_PARAMS", json_decode(json_encode($params), true));
  183. $params['order_amount_pay'] = floatval($params['order_amount_pay']);
  184. $qrcodeNbr = $params['qrcode_nbr'];
  185. $prefix = substr($qrcodeNbr, 0, 2);
  186. // 模拟数据
  187. // $result = [
  188. // 'return_code'=>'SUCCESS',
  189. // 'result_code' => 'SUCCESS'
  190. // ];
  191. // $result=[
  192. // 'code'=> '10000',
  193. // 'msg' => 'Success'
  194. // ];
  195. // return $result;
  196. // 微信支付
  197. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  198. $payData = [
  199. 'out_trade_no' => $params['orderGroupId'],
  200. 'body' => '万悦康养订单',
  201. 'total_fee' => $params['order_amount_pay'] * 100,
  202. 'auth_code' => $params['qrcode_nbr'],
  203. ];
  204. try {
  205. $config = config('payment.wxpay');
  206. $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/wxpay';
  207. Pay::wechat($config)->pos($payData);
  208. $result = self::findWxpay($params['orderGroupId'], 0);
  209. }catch (GatewayException $g){
  210. $result = self::findWxpay($params['orderGroupId'], 0);
  211. } catch (\Exception $e) {
  212. $log->error("WXPAY", ['msg' => $e->getMessage()]);
  213. $result = self::findWxpay($params['orderGroupId'], 0);
  214. // throw new BusinessException("支付失败");
  215. }
  216. try{
  217. $log->info("WXPAY_RETURN", json_decode(json_encode($result), true));
  218. }catch (\Exception $e){}
  219. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  220. $payData = [
  221. 'out_trade_no' => $params['orderGroupId'],
  222. 'total_amount' => $params['order_amount_pay'],
  223. 'subject' => '万悦康养订单',
  224. 'auth_code' => $params['qrcode_nbr'],
  225. ];
  226. try {
  227. $config = config('payment.alipay');
  228. $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN').'/notify/orderPay/alipay';
  229. Pay::alipay($config)->pos($payData);
  230. $result = self::findAlipay($params['orderGroupId'], 0);
  231. } catch (GatewayException $g){
  232. $result = self::findAlipay($params['orderGroupId'], 0);
  233. } catch (\Exception $e) {
  234. $log->error("ALIPAY", ['msg' => $e->getMessage()]);
  235. throw new BusinessException("支付失败");
  236. }
  237. try{
  238. $log->info("ALIPAY_RETURN", json_decode(json_encode($result), true));
  239. }catch (\Exception $e){}
  240. } else {
  241. throw new BusinessException("付款码无效");
  242. }
  243. return $result;
  244. }
  245. /**
  246. * @Desc 查询微信支付
  247. * @Author Gorden
  248. * @Date 2024/8/16 14:55
  249. *
  250. * @param $orderId
  251. * @param $nbr 循环次数
  252. * @return mixed|void
  253. * @throws BusinessException
  254. */
  255. public static function findWxpay($orderId, $nbr = 0)
  256. {
  257. try {
  258. $result = Pay::wechat(config('payment.wxpay'))->find($orderId, 'pos');
  259. $result = json_decode(json_encode($result), true);
  260. } catch (\Exception $e) {
  261. SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => $e->getMessage()]);
  262. }
  263. if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
  264. SupportLog::channel('pay')->info("FIND_WXPAY_SUCCESS", ['nbr' => $nbr,'order_id'=>$orderId]);
  265. return $result;
  266. } else {
  267. if ($nbr > 2) {
  268. SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => '订单查询失败','order_id'=>$orderId]);
  269. return ['msg'=>'订单查询失败'];
  270. }
  271. dump('nbr-'.$nbr);
  272. sleep(5);
  273. SupportLog::channel('pay')->error("FIND_WXPAY", ['nbr' => $nbr,'order_id'=>$orderId]);
  274. return self::findWxpay($orderId, $nbr + 1);
  275. }
  276. }
  277. /**
  278. * @Desc 查询支付宝订单
  279. * @Author Gorden
  280. * @Date 2024/8/16 15:16
  281. *
  282. * @param $orderId
  283. * @param $nbr 循环次数
  284. * @return mixed|void
  285. * @throws BusinessException
  286. */
  287. public static function findAlipay($orderId, $nbr = 0)
  288. {
  289. try {
  290. $result = Pay::alipay(config('payment.alipay'))->find($orderId);
  291. $result = json_decode(json_encode($result), true);
  292. } catch (\Exception $e) {
  293. SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => $e->getMessage()]);
  294. }
  295. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  296. SupportLog::channel('pay')->info("FIND_ALIPAY_SUCCESS", ['nbr' => $nbr,'order_id'=>$orderId]);
  297. return $result;
  298. } else {
  299. if ($nbr > 2) {
  300. SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => '订单查询失败','order_id'=>$orderId]);
  301. return ['msg'=>'订单查询失败'];
  302. }
  303. sleep(5);
  304. SupportLog::channel('pay')->error("FIND_ALIPAY", ['nbr' => $nbr,'order_id'=>$orderId]);
  305. return self::findAlipay($orderId, $nbr + 1);
  306. }
  307. }
  308. /**
  309. * 验证产品库存
  310. */
  311. public static function checkGoodsStorage($params)
  312. {
  313. foreach ($params['goodsContentList'] as $goods) {
  314. // 减库存,规格和总库存
  315. if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') {
  316. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  317. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  318. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  319. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  320. }
  321. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  322. throw new BusinessException('库存不足');
  323. }
  324. }
  325. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  326. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  327. if ($goodsRunning->goods_running_storage < 0) {
  328. throw new BusinessException('库存不足');
  329. }
  330. }
  331. }
  332. /**
  333. * 下单时结算的组合支付payDetail
  334. */
  335. public static function createPayDetail($params)
  336. {
  337. $insertPayDetailData = [
  338. 'join_pay_member_id' => $params['join_order_member_id'],
  339. 'join_pay_order_id' => $params['orderGroupId'],
  340. 'pay_status' => $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  341. 'pay_category' => !empty($params['submit_goods_classify']) ? $params['submit_goods_classify'] : $params['goods_classify'],
  342. 'pay_amount' => $params['order_amount_pay'],
  343. 'pay_paytimes' => date('Y-m-d H:i:s'),
  344. 'pay_prepayid' => $params['pay_category'],
  345. 'pay_json_request' => json_encode($params),
  346. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  347. 'pay_addtimes' => time()
  348. ];
  349. PayDetail::insert($insertPayDetailData);
  350. }
  351. /**
  352. * 组合支付,PayDetail
  353. */
  354. public static function createPayConstituteDetail($params, $payDetail)
  355. {
  356. $qrcodePrepayId = '';
  357. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  358. $qrcodePrepayId = $params['join_order_member_id'] . '-QRCODE';
  359. }
  360. if (!$payDetail || ($payDetail->pay_prepayid != $params['pay_category'] && $payDetail->pay_prepayid != $qrcodePrepayId)) {
  361. $payDetail = new PayDetail();
  362. $payDetail->join_pay_member_id = $params['join_order_member_id'];
  363. $payDetail->join_pay_order_id = $params['orderGroupId'];
  364. $payDetail->pay_category = $params['goods_classify'] ?? '';
  365. $payDetail->pay_prepayid = $params['pay_category'];
  366. $payDetail->pay_json_request = json_encode($params);
  367. $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
  368. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  369. ]);
  370. $payDetail->pay_addtimes = time();
  371. }
  372. if ($payDetail->pay_prepayid == $qrcodePrepayId) {
  373. $payDetail->pay_prepayid = $params['pay_category'];
  374. }
  375. $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
  376. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  377. ]);
  378. $payDetail->pay_amount = $params['order_amount_pay'];
  379. $payDetail->pay_paytimes = date('Y-m-d H:i:s');
  380. $payDetail->pay_status = 'SUCCESS';
  381. $payDetail->save();
  382. }
  383. public static $couponClassify=[
  384. 'wipe'=>'抹零',
  385. 'custom'=>'自定义优惠金额'
  386. ];
  387. }