123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420 |
- <?php
- namespace app\admin\service\order;
- use app\model\GoodsRunning;
- use app\model\GoodsSku;
- use app\model\Member;
- use app\model\Order;
- use app\model\OrderSheet;
- use app\model\PayDetail;
- use app\model\SysDept;
- use support\Db;
- use support\exception\BusinessException;
- use support\Log as SupportLog;
- use support\Redis;
- use Yansongda\Pay\Exceptions\GatewayException;
- use Yansongda\Pay\Log;
- use Yansongda\Pay\Pay;
- class OrderService
- {
- /**
- * @Desc 自动确认收货
- * @Author Gorden
- * @Date 2024/4/11 16:09
- *
- * @return void
- */
- public static function AutomaticReceipt()
- {
- try {
- Db::beginTransaction();
- $timeUnix = strtotime("-7 days");
- $orders = Order::where('order_status_system', 'SIGNED')
- ->where('order_addtimes', '<', $timeUnix)
- ->get();
- foreach ($orders as $order) {
- // 订单主表
- Order::where('order_id', $order->order_id)->update([
- 'order_is_complete' => 'Y',
- 'order_status_system' => 'CONFIRM',
- 'order_status_storage' => 'DONE'
- ]);
- // 订单详情表
- OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'DONE']);
- // 7天后自动完成 order_is_complete=Y
- // $redis = Redis::connection();
- // $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
- // $redis->sadd($key, $order->order_id);
- }
- Db::commit();
- } catch (\Exception $e) {
- Db::rollBack();
- }
- }
- /**
- * @Desc 自动完成订单
- * @Author Gorden
- * @Date 2024/7/16 9:37
- *
- * @return void
- */
- public static function AutomaticComplete()
- {
- Db::beginTransaction();
- try {
- $redis = Redis::connection();
- $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd');
- $orderIds = $redis->smembers($key);
- foreach ($orderIds as $orderId) {
- $order = Order::where('order_id', $orderId)
- ->select('order_is_complete', 'order_category', 'order_status_system')
- ->first();
- if ($order && $order->order_is_complete != 'Y' && $order->order_category != 'RETURN' && in_array($order->order_status_system, ['RECVING', 'SIGNED', 'CONFIRM'])) {
- // 更新主表
- Order::where('order_id', $orderId)->update(['order_is_complete' => 'Y', 'order_status_system' => 'CONFIRM', 'order_status_storage' => 'DONE']);
- // sheet表
- OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
- }
- }
- $redis->del($key);
- Db::commit();
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- }
- }
- public static function checkPayingOrder()
- {
- try {
- Db::beginTransaction();
- $timeUnix = strtotime("-30 minutes");
- $orders = Order::where('order_status_system', 'PAYING')
- ->where('order_category', '<>', 'DISHES') // 点餐不自动取消
- // ->where('order_platform','<>','SYSTEM') // 后台产生的订单不自动取消
- ->where(function ($query) {
- $query->where('order_platform', '<>', 'SYSTEM')->orWhereNull('order_platform');
- })
- ->where('order_addtimes', '<', $timeUnix)
- ->get();
- foreach ($orders as $order) {
- // 订单主表
- Order::where('order_id', $order->order_id)->update([
- 'order_is_complete' => 'Y',
- 'order_status_system' => 'CANCEL',
- 'order_status_payment' => 'CANCEL'
- ]);
- $sheets = OrderSheet::where('join_sheet_order_id', $order->order_id)->get();
- foreach ($sheets as $sheet) {
- // 还原库存
- $goodsSku = GoodsSku::where('goods_sku_id', $sheet->join_sheet_goods_sku_id)->first();
- if (!empty($goodsSku) && !empty($goodsSku->goods_sku_storage_json)) {
- $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
- if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
- $skuStorageJson['storage'] = $skuStorageJson['storage'] + $sheet->order_sheet_num;
- $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
- $goodsSku->save();
- }
- }
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $sheet->join_sheet_goods_id)->first();
- if (!empty($goodsRunning)) {
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $sheet->order_sheet_num;
- $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $sheet->order_sheet_num;
- $goodsRunning->save();
- }
- }
- // 订单详情表
- OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'CANCEL']);
- // 支付表
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
- if (!empty($payDetail)) {
- $payExtendJson = [];
- if (!empty($payDetail->pay_extend_json)) {
- $payExtendJson = json_decode($payDetail->pay_extend_json, true);
- }
- $payExtendJson['cancel_times'] = date('Y-m-d H:i:s');
- PayDetail::where('join_pay_order_id', $order->order_groupby)->update([
- 'pay_status' => 'CANCEL',
- 'pay_extend_json' => json_encode($payExtendJson)
- ]);
- }
- }
- Db::commit();
- } catch (\Exception $e) {
- Db::rollBack();
- }
- }
- public static function generateWriteOffData($params)
- {
- return [
- 'charge' => [
- 'charge_amount' => 1,
- 'charge_content' => $params['order_remark'] ?? '',
- 'charge_user_id' => $params['write_off_member_id'],
- 'charge_premises' => $params['dept_premises_id'],
- ],
- 'member_id' => $params['join_order_member_id']
- ];
- }
- public static function generateAppointmentApplyData($params)
- {
- $member = Member::with('cert', 'info')
- ->where('member_id', $params['join_order_member_id'])
- ->first();
- $name = '';
- if (!empty($member) && !empty($member->cert) && !empty($member->cert->member_cert_name)) {
- $name = $member->cert->member_cert_name;
- } else if (!empty($member) && !empty($member->info) && !empty($member->info->member_info_nickname)) {
- $name = $member->info->member_info_nickname;
- }
- return [
- 'name' => $name,
- 'times' => '',
- 'mobile' => !empty($member) ? $member->member_mobile : '',
- 'person' => $params['order_sheet_num'] ?? '',
- 'premises' => $params['dept_premises_id'] ?? ''
- ];
- }
- /**
- * 微信支付宝扫码支付
- */
- public static function qrcodePay($params)
- {
- $log = SupportLog::channel('pay');
- $log->info("PAY_PARAMS", json_decode(json_encode($params), true));
- $params['order_amount_pay'] = floatval($params['order_amount_pay']);
- $qrcodeNbr = $params['qrcode_nbr'];
- $prefix = substr($qrcodeNbr, 0, 2);
- // 模拟数据
- // $result = [
- // 'return_code'=>'SUCCESS',
- // 'result_code' => 'SUCCESS'
- // ];
- // $result=[
- // 'code'=> '10000',
- // 'msg' => 'Success'
- // ];
- // return $result;
- // 微信支付
- if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
- $payData = [
- 'out_trade_no' => $params['orderGroupId'],
- 'body' => '万悦康养订单',
- 'total_fee' => $params['order_amount_pay'] * 100,
- 'auth_code' => $params['qrcode_nbr'],
- ];
- try {
- $config = config('payment.wxpay');
- $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/wxpay';
- Pay::wechat($config)->pos($payData);
- $result = self::findWxpay($params['orderGroupId'], 0);
- }catch (GatewayException $g){
- $result = self::findWxpay($params['orderGroupId'], 0);
- } catch (\Exception $e) {
- $log->error("WXPAY", ['msg' => $e->getMessage()]);
- $result = self::findWxpay($params['orderGroupId'], 0);
- // throw new BusinessException("支付失败");
- }
- try{
- $log->info("WXPAY_RETURN", json_decode(json_encode($result), true));
- }catch (\Exception $e){}
- } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
- $payData = [
- 'out_trade_no' => $params['orderGroupId'],
- 'total_amount' => $params['order_amount_pay'],
- 'subject' => '万悦康养订单',
- 'auth_code' => $params['qrcode_nbr'],
- ];
- try {
- $config = config('payment.alipay');
- $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN').'/notify/orderPay/alipay';
- Pay::alipay($config)->pos($payData);
- $result = self::findAlipay($params['orderGroupId'], 0);
- } catch (GatewayException $g){
- $result = self::findAlipay($params['orderGroupId'], 0);
- } catch (\Exception $e) {
- $log->error("ALIPAY", ['msg' => $e->getMessage()]);
- throw new BusinessException("支付失败");
- }
- try{
- $log->info("ALIPAY_RETURN", json_decode(json_encode($result), true));
- }catch (\Exception $e){}
- } else {
- throw new BusinessException("付款码无效");
- }
- return $result;
- }
- /**
- * @Desc 查询微信支付
- * @Author Gorden
- * @Date 2024/8/16 14:55
- *
- * @param $orderId
- * @param $nbr 循环次数
- * @return mixed|void
- * @throws BusinessException
- */
- public static function findWxpay($orderId, $nbr = 0)
- {
- try {
- $result = Pay::wechat(config('payment.wxpay'))->find($orderId, 'pos');
- $result = json_decode(json_encode($result), true);
- } catch (\Exception $e) {
- SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => $e->getMessage()]);
- }
- 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') {
- SupportLog::channel('pay')->info("FIND_WXPAY_SUCCESS", ['nbr' => $nbr,'order_id'=>$orderId]);
- return $result;
- } else {
- if ($nbr > 2) {
- SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => '订单查询失败','order_id'=>$orderId]);
- return ['msg'=>'订单查询失败'];
- }
- dump('nbr-'.$nbr);
- sleep(5);
- SupportLog::channel('pay')->error("FIND_WXPAY", ['nbr' => $nbr,'order_id'=>$orderId]);
- return self::findWxpay($orderId, $nbr + 1);
- }
- }
- /**
- * @Desc 查询支付宝订单
- * @Author Gorden
- * @Date 2024/8/16 15:16
- *
- * @param $orderId
- * @param $nbr 循环次数
- * @return mixed|void
- * @throws BusinessException
- */
- public static function findAlipay($orderId, $nbr = 0)
- {
- try {
- $result = Pay::alipay(config('payment.alipay'))->find($orderId);
- $result = json_decode(json_encode($result), true);
- } catch (\Exception $e) {
- SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => $e->getMessage()]);
- }
- if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
- SupportLog::channel('pay')->info("FIND_ALIPAY_SUCCESS", ['nbr' => $nbr,'order_id'=>$orderId]);
- return $result;
- } else {
- if ($nbr > 2) {
- SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => '订单查询失败','order_id'=>$orderId]);
- return ['msg'=>'订单查询失败'];
- }
- sleep(5);
- SupportLog::channel('pay')->error("FIND_ALIPAY", ['nbr' => $nbr,'order_id'=>$orderId]);
- return self::findAlipay($orderId, $nbr + 1);
- }
- }
- /**
- * 验证产品库存
- */
- public static function checkGoodsStorage($params)
- {
- foreach ($params['goodsContentList'] as $goods) {
- // 减库存,规格和总库存
- if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') {
- $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
- $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
- if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
- $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
- }
- if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
- throw new BusinessException('库存不足');
- }
- }
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- }
- }
- /**
- * 下单时结算的组合支付payDetail
- */
- public static function createPayDetail($params)
- {
- $insertPayDetailData = [
- 'join_pay_member_id' => $params['join_order_member_id'],
- 'join_pay_order_id' => $params['orderGroupId'],
- 'pay_status' => $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
- 'pay_category' => !empty($params['submit_goods_classify']) ? $params['submit_goods_classify'] : $params['goods_classify'],
- 'pay_amount' => $params['order_amount_pay'],
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_prepayid' => $params['pay_category'],
- 'pay_json_request' => json_encode($params),
- 'pay_json_response' => $params['pay_json_response'] ?? '[]',
- 'pay_addtimes' => time()
- ];
- PayDetail::insert($insertPayDetailData);
- }
- /**
- * 组合支付,PayDetail
- */
- public static function createPayConstituteDetail($params, $payDetail)
- {
- $qrcodePrepayId = '';
- if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
- $qrcodePrepayId = $params['join_order_member_id'] . '-QRCODE';
- }
- if (!$payDetail || ($payDetail->pay_prepayid != $params['pay_category'] && $payDetail->pay_prepayid != $qrcodePrepayId)) {
- $payDetail = new PayDetail();
- $payDetail->join_pay_member_id = $params['join_order_member_id'];
- $payDetail->join_pay_order_id = $params['orderGroupId'];
- $payDetail->pay_category = $params['goods_classify'] ?? '';
- $payDetail->pay_prepayid = $params['pay_category'];
- $payDetail->pay_json_request = json_encode($params);
- $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
- 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
- ]);
- $payDetail->pay_addtimes = time();
- }
- if ($payDetail->pay_prepayid == $qrcodePrepayId) {
- $payDetail->pay_prepayid = $params['pay_category'];
- }
- $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
- 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
- ]);
- $payDetail->pay_amount = $params['order_amount_pay'];
- $payDetail->pay_paytimes = date('Y-m-d H:i:s');
- $payDetail->pay_status = 'SUCCESS';
- $payDetail->save();
- }
- public static $couponClassify=[
- 'wipe'=>'抹零',
- 'custom'=>'自定义优惠金额'
- ];
- }
|