model = new Order(); $this->validate = true; $this->validateClass = new OrderValidate(); } /** * @Desc 列表 * @Author Gorden * @Date 2024/3/28 15:01 * * @param Request $request * @return Response * @throws \support\exception\BusinessException */ public function select(Request $request): Response { $timeType = $request->get('time_type', 'add'); [$where, $format, $limit, $field, $order] = $this->selectInput($request); $where['order_classify'] = 'RECHARGE'; if (!empty($where['order_addtimes']) && $timeType == 'add') { $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]); $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]); } $order = $request->get('order', 'desc'); $orderId = $request->get('orderId'); $field = $field ?? 'order_addtimes'; $orderIds = []; if (!empty($orderId)) { $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%') ->where('order_classify', 'RECHARGE') ->pluck('order_id') ->toArray(); } $goodsName = trim($request->get('goods_name', '')); if (!empty($goodsName)) { $goodsIds = Goods::where('goods_classify', 'RECHARGE') ->where('goods_name', 'like', '%' . $goodsName . '%') ->pluck('goods_id') ->toArray(); $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray(); if (!empty($where['order_id'])) { $orderIds = array_intersect($orderIds, $goodsOrderIds); } else { $orderIds = $goodsOrderIds; } } // 付款时间 $payOrderIds = []; if ($timeType == 'pay' && !empty($where['order_addtimes'])) { $payTimeStart = strtotime($where['order_addtimes'][0]); $payTimeEnd = strtotime($where['order_addtimes'][1]); unset($where['order_addtimes']); $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['RECHARGE']); } if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') { $orderIds = array_intersect($orderIds, $payOrderIds); $orderIds[] = '00'; $where['order_id'] = ['in', implode(',', $orderIds)]; } elseif (!empty($orderId) || !empty($goodsName)) { $orderIds[] = '00'; $where['order_id'] = ['in', implode(',', $orderIds)]; } elseif ($timeType == 'pay') { $payOrderIds[] = '00'; $where['order_id'] = ['in', implode(',', $payOrderIds)]; } $query = $this->doSelect($where, $field, $order); return $this->doFormat($query, $format, $limit); } protected function doSelect(array $where, string $field = null, string $order = 'desc') { $model = $this->model->with([ 'sheets' => function ($query) { $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price'); }, 'member' => function ($query) { $query->select('member_id', 'member_mobile'); }, 'cert' => function ($query) { $query->select('join_cert_member_id', 'member_cert_name'); }, ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id') ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id'); // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id'); foreach ($where as $column => $value) { if (is_array($value)) { if ($value[0] === 'like' || $value[0] === 'not like') { $model = $model->where($column, $value[0], "%$value[1]%"); } elseif (in_array($value[0], ['>', '=', '<', '<>'])) { $model = $model->where($column, $value[0], $value[1]); } elseif ($value[0] == 'in' && !empty($value[1])) { $valArr = $value[1]; if (is_string($value[1])) { $valArr = explode(",", trim($value[1])); } $model = $model->whereIn($column, $valArr); } elseif ($value[0] == 'not in' && !empty($value[1])) { $valArr = $value[1]; if (is_string($value[1])) { $valArr = explode(",", trim($value[1])); } $model = $model->whereNotIn($column, $valArr); } elseif ($value[0] == 'null') { $model = $model->whereNull($column); } elseif ($value[0] == 'not null') { $model = $model->whereNotNull($column); } elseif ($value[0] !== '' || $value[1] !== '') { $model = $model->whereBetween($column, $value); } } else { $model = $model->where($column, $value); } } if ($field) { $model = $model->orderBy($field, $order); } $model = $model->whereJsonContains('order_config_json->order_category', 'RECHARGE') ->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark'); return $model; } public function afterQuery($items) { foreach ($items as &$item) { $sheetDeng = ''; $item['is_crown'] = 'N'; $item['sheet'] = $item['sheets'][0] ?? []; if (!empty($item['sheet'])) { $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first(); if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') { $sheetDeng = ' 等'; } if ($goods && $goods->goods_name && strpos($goods->goods_name, '皇冠') !== false) { $item['is_crown'] = 'Y'; } $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '自定义充值'; $item['sheet']['goods_classify'] = $goods->goods_classify ?? ''; $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']); } unset($item['sheets']); if (isset($item['orders_return_id'])) { $item['return'] = [ 'orders_return_id' => $item['orders_return_id'], 'join_return_order_id' => $item['join_return_order_id'], 'order_return_status' => $item['order_return_status'], 'order_return_apply_json' => $item['order_return_apply_json'], 'order_return_remark' => $item['order_return_remark'] ]; } if (isset($item['join_express_order_id'])) { $item['express'] = [ 'join_express_order_id' => $item['join_express_order_id'], 'order_express_type' => $item['order_express_type'] ]; unset($item['join_express_order_id'], $item['order_express_type']); } $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']); } return $items; } /** * @Desc 下单+支付 * @Author Gorden * @Date 2024/9/5 13:13 * * @param Request $request * @return Response */ public function insert(Request $request): Response { $params = $request->post(); // 判断餐品是否连带着服务或实体 $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify')); $params['goods_classify'] = $goodsClassifys[0]; $orderExtendJson = []; Db::beginTransaction(); try { // 验证线下付款密码 if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) { $password = $params['offline_password']; if ($password != '666888') { throw new BusinessException('密码错误,请重新输入'); } } if (!empty($params['dept_id'])) { $dept = SysDept::where('dept_id', $params['dept_id'])->first(); if (!$dept) { throw new BusinessException("充值场所不存在"); } $params['dept_name'] = $dept->dept_name; $orderExtendJson = ['referee_dept_id' => $params['dept_id'], 'referee_premises' => $params['dept_name']]; } $orderExtendJson['referee'] = $params['referee'] ?? ''; // 下单账户 if (empty($params['join_order_member_id']) && !empty($params['mobile'])) { if (Member::where('member_mobile', $params['mobile'])->exists()) { throw new BusinessException('会员已存在'); } $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up'); // 创建会员 MemberService::createMember($params); } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) { $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id'); } if (empty($params['join_order_member_id'])) { throw new BusinessException('检查下单账户'); } $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up'); $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up'); $systemStatus = 'PAYING'; // 立即结算 if ($params['settlement_now'] == 'Y') { if ($params['goods_classify'] == 'RECHARGE') { $params['order_is_complete'] = 'Y'; $systemStatus = 'DONE'; } } if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) { if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) { $params['pay_category'] = $params['pay_category_sub']; } $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } if ($params['pay_category'] == 'QRCODE' && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码 $result = OrderService::qrcodePay($params); $result = json_encode($result); $params['pay_json_response'] = $result; $result = json_decode($result, true); $prefix = substr($params['qrcode_nbr'], 0, 2); if (in_array($prefix, [10, 11, 12, 13, 14, 15])) { $params['pay_category'] = 'WXPAY'; if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) { $params['order_status_system'] = 'PAYING'; $params['order_status_payment'] = 'PENDING'; $params['order_is_complete'] = 'N'; } else { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) { $params['pay_category'] = 'ALIPAY'; if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) { $params['order_status_system'] = 'PAYING'; $params['order_status_payment'] = 'PENDING'; $params['order_is_complete'] = 'N'; } else { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } else { throw new BusinessException('付款码无效'); } } $params['order_extend_json'] = $orderExtendJson; // 写入主订单 $this->insertMain($params); // 订单详情 $this->insertSheet($params); // 支付记录 $payId = $this->insertPayDetail($params); Db::commit(); if ($params['order_status_payment'] == 'SUCCESS') { // 入收支明细表 // $params['inout_category'] = '会员充值'; // Event::dispatch('statistics.inout.in', $params); // 充值回调 (new \app\admin\controller\notify\RechargeController)->disposePaySuccess($payId); } if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') { _syslog("订单", "支付异常,检查是否有轮询"); return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]); } _syslog("订单", "创建订单成功"); return json_success('创建订单成功'); } catch (BusinessException $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("订单", $e->getMessage()); return json_fail($e->getMessage()); } catch (\Exception $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("订单", "创建订单失败"); return json_fail('创建订单失败'); } } /** * @Desc 支付 * @Author Gorden * @Date 2024/9/5 13:12 * * @param Request $request * @return Response */ public function pay(Request $request) { $params = $request->post(); // 验证线下付款密码 if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) { $password = $params['offline_password']; if ($password != '666888') { return json_fail("密码错误,请重新输入"); } } $order = Order::where('order_id', $params['order_id'])->first(); if (!$order) { return json_fail('订单异常'); } if ($order->order_status_system != 'PAYING') { return json_fail('订单不是可支付状态'); } $params['orderId'] = $params['order_id']; $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up'); $order->order_groupby = $params['orderGroupId']; $goods = Goods::where('goods_id', $params['join_sheet_goods_id']) ->select('goods_id', 'goods_name', 'goods_classify') ->first(); if (!$goods) { return json_fail('产品数据异常'); } $goods = $goods->toArray(); $params['goods_classify'] = $goods['goods_classify'] ?? ''; // 入伙场所 if (!empty($params['dept_id'])) { $orderExtendJson = []; if (!empty($order->order_extend_json)) { $orderExtendJson = json_decode($order->order_extend_json, true); } $dept = SysDept::where('dept_id', $params['dept_id'])->first(); if (!$dept) { throw new BusinessException("入伙场所不存在"); } $params['dept_name'] = $dept->dept_name; $orderExtendJson['dept_id'] = $params['dept_id']; $orderExtendJson['dept_name'] = $params['dept_name']; $order->order_extend_json = json_encode($orderExtendJson); } // 立即结算 if ($params['goods_classify'] == 'RECHARGE') { $order->order_is_complete = 'Y'; $systemStatus = 'DONE'; } $paymentStatus = 'PENDING'; Db::beginTransaction(); try { // 组合支付时,付款码应收金额 $qrcodePayAmount = 0; if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; $paymentStatus = 'SUCCESS'; if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) { $params['pay_category'] = $params['pay_category_sub']; } } if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码 // 提交过来的支付分类 $submitPayCategory = $params['pay_category']; // 账户支付的金额 $accountAmount = $params['order_amount_pay']; if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) { // 组合支付,改成需要付款码需要支付的金额 $params['order_amount_pay'] = $qrcodePayAmount; } // 去支付 $result = OrderService::qrcodePay($params); $result = json_encode($result); $params['pay_json_response'] = $result; $result = json_decode($result, true); $prefix = substr($params['qrcode_nbr'], 0, 2); if (in_array($prefix, [10, 11, 12, 13, 14, 15])) { $params['pay_category'] = 'WXPAY'; if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) { $order->order_status_system = 'PAYING'; $order->order_status_payment = 'PENDING'; $order->order_is_complete = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; $paymentStatus = 'SUCCESS'; } } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) { $params['pay_category'] = 'ALIPAY'; if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) { $order->order_status_system = 'PAYING'; $order->order_status_payment = 'PENDING'; $order->order_is_complete = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; $paymentStatus = 'SUCCESS'; } } else { throw new BusinessException('付款码无效'); } // 账户支付的金额 $params['order_amount_pay'] = $accountAmount; } if ($order->order_status_payment == 'SUCCESS') { $order->order_is_complete = 'Y'; } // 主订单 $order->save(); // sheet if ($order->order_status_payment == 'SUCCESS') { $data = [ 'order_sheet_status' => $systemStatus ]; if (floatval($order->order_amount_paid) < $order->order_amount_total) { $data['order_sheet_status'] = 'BEING'; } OrderSheet::where('join_sheet_order_id', $params['order_id'])->update($data); } // 清除此订单的未支付记录 PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)->where('pay_status', 'WAITING')->delete(); // 重新创建 $payId = $this->insertPayDetail($params); Db::commit(); if ($order->order_status_payment == 'SUCCESS') { // 入收支明细表 $params['inout_category'] = '会员充值'; Event::dispatch('statistics.inout.in', $params); // 加销售量 OrderSheetService::addGoodsSales($params['orderId']); // 充值回调 (new \app\admin\controller\notify\RechargeController)->disposePaySuccess($payId); } if ($order->order_status_payment != 'SUCCESS' && $paymentStatus != 'SUCCESS') { _syslog("订单", "支付异常,检查是否有轮询"); return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]); } _syslog("订单", "订单支付成功"); return json_success('支付成功'); } catch (BusinessException $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "订单支付失败:" . $e->getMessage()); return json_fail("支付失败:" . $e->getMessage()); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "订单支付失败"); return json_fail('支付失败'); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 10:30 * * @param $params * @return void * @throws BusinessException */ public function insertMain($params) { try { $orderCategory = 'NORMAL'; if (!empty($params['order_category'])) { $orderCategory = $params['order_category']; } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { $orderCategory = 'DISHES'; } else if (isset($params['goods_classify'])) { $orderCategory = $params['goods_classify']; } if (empty($params['order_extend_json'])) { $params['order_extend_json'] = []; } else { if (is_json($params['order_extend_json'])) { $params['order_extend_json'] = json_decode($params['order_extend_json'], true); } } // 推荐人 $params['order_extend_json']['referee'] = $params['referee'] ?? ''; $data = [ 'order_id' => $params['orderId'], 'order_groupby' => $params['orderGroupId'], 'join_order_member_id' => $params['join_order_member_id'], 'order_name' => date('Y-m-d H:i:s') . '-订单', 'order_amount_total' => $params['order_amount_total'], 'order_amount_pay' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0, 'order_amount_paid' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0, 'order_category' => $orderCategory, 'order_classify' => $orderCategory, 'order_is_complete' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'Y' : 'N', 'order_status_system' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING', 'order_status_payment' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'PENDING', 'order_status_storage' => $params['order_status_storage'], 'order_platform' => $params['order_platform'], 'order_remark' => $params['order_remark'] ?? '', 'order_discount_json' => $params['order_discount_json'] ?? '[]', 'order_config_json' => json_encode(['order_category' => 'RECHARGE']), 'order_express_json' => $params['order_express_json'] ?? '[]', 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]', 'order_addtimes' => time(), 'order_add_user_id'=>JwtToken::getCurrentId() ]; Order::insert($data); } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException('订单创建信息失败'); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 10:25 * * @param $params * @return void * @throws BusinessException */ public function insertSheet($params) { try { $orderSheetIds = []; foreach ($params['goodsContentList'] as $goods) { //{"unit": "份", "table": null, "premises": "15"} $price = floatval($goods['goods_sales_price']); $extendJson['unit'] = $goods['sku_name']; if (isset($params['submit_premises_id'])) { $extendJson['premises'] = $params['submit_premises_id']; } if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { $extendJson['table'] = null; } $orderSheetStatus = 'PAYING'; if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') { if (floatval($params['order_amount_pay']) >= floatval($params['order_amount_total'])) { $orderSheetStatus = 'DONE'; } else { $orderSheetStatus = 'BEING'; } } $data = [ 'join_sheet_member_id' => $params['join_order_member_id'], 'join_sheet_order_id' => $params['orderId'], 'join_sheet_goods_id' => $goods['goods_id'], 'join_sheet_goods_sku_id' => $goods['sku_id'], 'order_sheet_status' => $orderSheetStatus, 'order_sheet_category' => 'RECHARGE', 'order_sheet_num' => $goods['nbr'], 'order_sheet_price' => $goods['goods_sales_price'], 'order_sheet_price_pay' => $goods['goods_sales_price'], 'order_sheet_amount' => $price * $goods['nbr'], 'order_sheet_pay' => $price * $goods['nbr'], 'order_sheet_task_status' => 'NONE', 'order_sheet_remark' => $params['order_remark'] ?? '', 'order_sheet_addtimes' => time(), 'order_sheet_extend_json' => json_encode($extendJson) ]; $orderSheetId = OrderSheet::insertGetId($data); $orderSheetIds[] = $orderSheetId; // 减库存,规格和总库存 if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) { $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('库存不足'); } $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson); $goodsSku->save(); } $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('库存不足'); } if ($params['order_status_payment'] == 'SUCCESS') { $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr']; } $goodsRunning->save(); } return $orderSheetIds; } catch (\support\exception\BusinessException $e) { dump($e->getMessage() . '||' . $e->getLine()); throw new BusinessException($e->getMessage()); } catch (\Exception $e) { dump($e->getMessage() . '||' . $e->getLine()); throw new BusinessException('订单创建失败'); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 10:35 * * @param $params * @throws BusinessException */ public function insertPayDetail($params) { try { if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) { $payPrepayid = $params['pay_category']; } else if ($params['pay_category'] == 'OFFLINE') { $payPrepayid = 'OFFLINE'; } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') { $payPrepayid = 'OFFLINE_ALIPAY'; } else if ($params['pay_category'] == 'OFFLINE_WXPAY') { $payPrepayid = 'OFFLINE_WXPAY'; } else if ($params['pay_category'] == 'MONEY') { $payPrepayid = 'MONEY'; } else { $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category']; } $sheet = OrderSheet::with('goods')->where('join_sheet_order_id', $params['orderId'])->first(); $payExtendJson = []; if (!empty($sheet->goods)) { $goodsAttributeJson = json_decode($sheet->goods->goods_attribute_json, true); $addedRate = 0; if (!empty($goodsAttributeJson['added'])) { $addedRate = $goodsAttributeJson['added']['nbr']; } $payExtendJson = [ 'added_rate' => $addedRate, 'added_amount' => round($addedRate * $params['order_amount_pay'], 2) ]; } $data = [ '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' => $params['goods_classify'], 'pay_amount' => $params['order_amount_pay'], 'pay_prepayid' => $payPrepayid, 'pay_paytimes' => date('Y-m-d H:i:s'), 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]', 'pay_json_request' => json_encode($params), 'pay_json_response' => $params['pay_json_response'] ?? '[]', 'pay_extend_json' => json_encode($payExtendJson), 'pay_remark' => $params['order_remark'] ?? '', 'pay_addtimes' => time(), ]; $payId = PayDetail::insertGetId($data); return $payId; } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException('创建支付记录失败'); } } /** * @Desc 订单商品详情 * @Author Gorden * @Date 2024/3/29 8:50 * * @param Request $request * @return Response */ public function sheet(Request $request) { try { $orderId = $request->get('order_id'); $orderSheet = OrderSheet::with([ 'member' => function ($query) { $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id', 'member_is_vip', 'member_is_partner', 'member_is_referrer', 'member_is_franchisee'); }, 'goods' => function ($query) { $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express', 'goods_attribute_json'); }, 'memberInfo', 'cert', 'sku' => function ($query) { $query->where('goods_sku_status', 'ON') ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price'); }, 'skus', 'refund' => function ($query) { $query->select('join_return_order_id', 'order_return_status'); } ])->where('join_sheet_order_id', $orderId) ->orderBy('order_sheet_id', 'DESC') ->get() ->toArray(); $order = Order::where('order_id', $orderId)->first(); $express = OrderExpress::where('join_express_order_id', $orderId)->first(); $premises = ''; if ($express && $express->order_express_type == '自提') { $premises = $express->order_express_company; } $sheetAmount = 0; $coupons = []; foreach ($orderSheet as &$item) { $sheetAmount += $item['order_sheet_amount']; if (!empty($item['goods'])) { $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover']; } if (!empty($item['sku'])) { if (!empty($item['sku']['goods_sku_specs_json'])) { $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true); $skuName = ''; foreach ($specsJson as $specsKey => $skuSpecs) { if (is_array($skuSpecs)) { $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';'; } else { $skuName = $skuName . ' ' . $skuSpecs . ';'; } } $item['sku']['goods_sku_title'] = rtrim($skuName, ';'); } } if (!empty($item['skus'])) { foreach ($item['skus'] as $key => $skus) { if (!empty($skus['goods_sku_specs_json'])) { $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']); $skuName = ''; foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) { $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':'); if (is_array($skuSpecs)) { $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; '; } else { $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; '; } } $item['skus'][$key]['sku_name'] = rtrim($skuName, '; '); } } } else { $item['skus'] = []; } // 产品携带的优惠券 if (!empty($item['goods']['goods_attribute_json'])) { $goodsAttributeJson = json_decode($item['goods']['goods_attribute_json'], true); if (isset($goodsAttributeJson['coupon'])) { $couponIds = array_keys($goodsAttributeJson['coupon']); $coupons = Coupon::whereIn('coupon_id', $couponIds) ->select('coupon_id', 'coupon_name', 'coupon_classify', 'coupon_is_period', 'coupon_period_json', 'coupon_addtimes') ->get() ->toArray(); foreach ($coupons as &$coupon) { if (isset($goodsAttributeJson['coupon'][$coupon['coupon_id']])) { $coupon['num'] = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id']) ->where('join_coupon_detail_member_id', $order->join_order_member_id) ->whereJsonContains('coupon_detail_extend_json->order_id', $order->order_id) ->count(); $coupon['used'] = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id']) ->where('join_coupon_detail_member_id', $order->join_order_member_id) ->whereJsonContains('coupon_detail_extend_json->order_id', $order->order_id) ->where('coupon_detail_status', 'USED') ->count(); $coupon['invalid'] = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id']) ->where('join_coupon_detail_member_id', $order->join_order_member_id) ->whereJsonContains('coupon_detail_extend_json->order_id', $order->order_id) ->whereIn('coupon_detail_status', ['DISABLED', 'CANCEL', 'EXPIRED']) ->count(); $coupon['unused'] = $coupon['num'] - $coupon['used'] - $coupon['invalid']; } } } if (isset($goodsAttributeJson['added'])) { $item['goods']['added_amount'] = floatval($goodsAttributeJson['added']['nbr']) * $item['goods']['goods_sales_price']; $item['goods']['added_rate'] = floatval($goodsAttributeJson['added']['nbr']) * 100; } } if (!empty($item['order_sheet_extend_json']) && !$express) { $extendJson = json_decode($item['order_sheet_extend_json'], true); if (isset($extendJson['address_id'])) { $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first(); if (!empty($address)) { $valJson = json_decode($address->client_config_val_json, true); $express = [ 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''), 'order_express_city' => $valJson['city'], 'order_express_mobile' => $valJson['mobile'], 'order_express_person' => $valJson['person'] ]; } } } $item['member']['level'] = '普通会员'; if (!empty($item['member']['join_member_role_id'])) { $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name'); } $item['member_info']['member_info_nickname'] = MemberService::getNickname(!empty($item['member_info']) ? $item['member_info']['member_info_nickname'] : '', (!empty($item['member']) ? $item['member']['member_mobile'] : '')); $item['member_info']['member_info_headimg'] = MemberService::getAvatarUrl(!empty($item['member_info']) && !empty($item['member_info']['member_info_headimg']) ? $item['member_info']['member_info_headimg'] : ''); } $order->sheet_amount = number_format($sheetAmount, 2); $payDetails = PayDetail::where('join_pay_order_id', $order->order_groupby) ->whereJsonContains('join_pay_object_json->order_id', $orderId) ->where('pay_category', '<>', 'REFUND') ->where('pay_status', 'SUCCESS') ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json','pay_remark') ->get(); if (count($payDetails) > 1) { $order->pay_category = 'CONSTITUTE'; } $payDetail = !empty($payDetails) && count($payDetails) > 0 ? $payDetails[0] : []; if (!empty($payDetail) && !empty($payDetail->pay_extend_json)) { $payExtendJson = json_decode($payDetail->pay_extend_json, true); $order->cancel_times = $payExtendJson['cancel_times'] ?? ''; // $payDetail->cancel_times = $payExtendJson['cancel_times'] ?? ''; } if (!empty($payDetail) && !empty($payDetail->pay_prepayid)) { $categoryArray = explode('-', $payDetail->pay_prepayid); if (isset($categoryArray[1])) { $payDetail->pay_category = $categoryArray[1]; } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) { $payDetail->pay_category = $categoryArray[0]; } } $refund = OrderReturn::where('join_return_order_id', $orderId) ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json') ->first(); if (!empty($refund->order_return_refund_json)) { $returnRefundJson = json_decode($refund->order_return_refund_json, true); if (isset($returnRefundJson['user_id'])) { $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name'); $returnRefundJson['person'] = $userName; unset($returnRefundJson['user_id']); } $refund->order_return_refund_json = json_encode($returnRefundJson); } if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); if (isset($orderConfigJson['reach'])) { $order->reach = $orderConfigJson['reach']; } if (isset($orderConfigJson['table'])) { $order->table = $orderConfigJson['table']; } if (isset($orderConfigJson['eat'])) { $order->eat = $orderConfigJson['eat']; } if (isset($orderConfigJson['express'])) { $order->express = $orderConfigJson['express']; } if (isset($orderConfigJson['premises'])) { $order->premises = $orderConfigJson['premises']; } if (isset($orderConfigJson['tableid'])) { $order->dept_table_id = $orderConfigJson['tableid']; } } if (!empty($order->order_extend_json)) { $orderExtendJson = json_decode($order->order_extend_json, true); $order->referee = $orderExtendJson['referee'] ?? ''; if (isset($orderExtendJson['cancel_times'])) { $order->cancel_times = $orderExtendJson['cancel_times']; } if (isset($orderExtendJson['free_remark'])) { $order->free_remark = $orderExtendJson['free_remark']; } if (isset($orderExtendJson['dept_id'])) { $order->dept_id = $orderExtendJson['dept_id']; } } $order->premises = $order->premises ?? $premises; $data = [ 'coupons' => $coupons, 'order' => $order, 'refund' => json_decode(json_encode($refund)), 'sheet' => json_decode(json_encode($orderSheet)), 'express' => json_decode(json_encode($express)), 'payDetail' => json_decode(json_encode($payDetail)), 'payDetails' => json_decode(json_encode($payDetails)) ]; return json_success('', $data); } catch (\Exception $e) { dump($e->getMessage(), $e->getLine()); } } /** * @Desc 获取分期的订单 * @Author Gorden * @Date 2024/9/10 15:14 * * @param Request $request * @return Response */ public function getPaidOrder(Request $request) { $memberId = $request->get('member_id'); if (!$memberId) { return json_fail('参数异常'); } $order = Order::where('join_order_member_id', $memberId) ->where('order_category', 'RECHARGE') ->where('order_status_system', 'PAYING') ->select('order_id', 'order_amount_total', 'order_amount_paid', 'order_amount_pay', 'order_extend_json') ->first(); return json_success('', $order); } /** * @Desc 上传支付凭证 * @Author Gorden * @Date 2024/9/12 10:14 * * @param Request $request * @return Response */ public function uploadTicket(Request $request) { $payId = $request->post('pay_id'); $url = $request->post('url'); if (!$payId || !$url) { return json_fail("参数异常"); } $url = str_replace(getenv("STORAGE_DOMAIN"), '', $url); try { $payDetail = PayDetail::where('pay_id', $payId)->first(); if (!$payDetail) { return json_fail('数据异常'); } $extendJson = []; if (!empty($payDetail->pay_extend_json)) { $extendJson = json_decode($payDetail->pay_extend_json, true); } $extendJson['ticket'] = $url; $payDetail->pay_extend_json = json_encode($extendJson); dump($payDetail->save()); return json_success('success'); } catch (\Exception $e) { return json_fail("上传附件失败"); } } /** * @Desc 查询订单状态 * @Author Gorden * @Date 2024/8/19 11:55 * * @param Request $request * @return Response|void */ public function getOrderPayStatus(Request $request) { $groupId = $request->get('group_id'); if (!$groupId) { return json_fail('参数异常'); } $order = Order::where('order_groupby', $groupId)->first(); if (empty($order)) { return json_fail('订单不存在'); } $order = $order->toArray(); $sheet = OrderSheet::where('join_sheet_order_id', $order['order_id']) ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id') ->first(); $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray(); try { Db::beginTransaction(); $payStatus = 'N'; $payAmount = 0; if (in_array('WXPAY', $payDetailType)) { $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos'); $result = json_decode(json_encode($result), true); // $result = '{"return_code":"SUCCESS","return_msg":"OK","result_code":"SUCCESS","mch_id":"1680393367","appid":"wxc6274da7198e3eb4","openid":"o3JAn6Ii_bAlxS-jbNEC4WnPhdwM","is_subscribe":"N","trade_type":"MICROPAY","trade_state":"SUCCESS","bank_type":"OTHERS","total_fee":"50","fee_type":"CNY","cash_fee":"1000","cash_fee_type":"CNY","transaction_id":"4200067718202409250802875650","out_trade_no":"OD24092518408RV7","attach":[],"time_end":"20240925184009","trade_state_desc":"支付成功","nonce_str":"OeGOkjch4eaV5qIt","sign":"6DCB3BFC594EBC018A2BEE2C3DFEA4E3"}'; // $result = json_decode($result, true); 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') { $payStatus = 'Y'; $payAmount = ($result['total_fee'] / 100); $orderUpdateData['order_status_payment'] = 'SUCCESS'; $orderUpdateData['order_status_system'] = 'DONE'; $orderUpdateData['order_is_complete'] = 'Y'; $orderUpdateData['order_amount_pay'] = $payAmount; // 主订单 Order::where('order_groupby', $groupId)->update($orderUpdateData); // Sheet OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']); // 支付记录 $payDetail = PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->first(); $payDetail->pay_status = 'SUCCESS'; $payDetail->pay_paytimes = date('Y-m-d H:i:s'); $payDetail->pay_json_response = json_encode($result); $payDetail->save(); } } else if (in_array('ALIPAY', $payDetailType)) { $result = Pay::alipay(config('payment.alipay'))->find($groupId); $result = json_decode(json_encode($result), true); // $result = '{"code":"10000","msg":"Success","buyer_logon_id":"138******93","buyer_pay_amount":"5.87","fund_bill_list":[{"amount":"5.69","fund_channel":"ALIPAYACCOUNT"},{"amount":"0.18","fund_channel":"COUPON"},{"amount":"0.13","fund_channel":"DISCOUNT"}],"invoice_amount":"5.69","out_trade_no":"OD2409251550Q07A","point_amount":"0.00","receipt_amount":"0.01","send_pay_date":"2024-09-25 15:50:22","total_amount":"0.01","trade_no":"2024092523001439431419750998","trade_status":"TRADE_SUCCESS","buyer_open_id":"04309N2aVhSZz4cKwN_DN2DQa7ekM3z5n8kscQHsmIZOJsf"}'; // $result = json_decode($result, true); if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') { $payStatus = 'Y'; $payAmount = $result['total_amount']; $orderUpdateData['order_status_payment'] = 'SUCCESS'; $orderUpdateData['order_status_system'] = 'DONE'; $orderUpdateData['order_is_complete'] = 'Y'; $orderUpdateData['order_amount_pay'] = $payAmount; // 主订单 Order::where('order_groupby', $groupId)->update($orderUpdateData); // Sheet OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']); // 支付记录 $payDetail = PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->first(); $payDetail->pay_status = 'SUCCESS'; $payDetail->pay_paytimes = date('Y-m-d H:i:s'); $payDetail->pay_json_response = json_encode($result); $payDetail->save(); } } if ($payStatus == 'Y') { Db::commit(); $params['member_id'] = $order['join_order_member_id']; $params['orderId'] = $order['order_id']; $params['order_amount_pay'] = $payAmount; $params['order_amount_total'] = $order['order_amount_total']; $params['join_sheet_goods_id'] = $sheet->join_sheet_goods_id; if (!empty($order['order_extend_json'])) { $orderExtendJson = json_decode($order['order_extend_json'], true); $params['dept_id'] = $orderExtendJson['dept_id'] ?? ''; $params['dept_name'] = $orderExtendJson['dept_name'] ?? ''; } // 入收支明细表 $params['orderId'] = $order['order_id']; $params['inout_category'] = '会员充值'; Event::dispatch('statistics.inout.in', $params); // 充值回调 (new \app\admin\controller\notify\RechargeController)->disposePaySuccess($payDetail->pay_id); return json_success('success'); } Db::rollBack(); return json_fail('没有查询到记录'); } catch (BusinessException $e) { Db::rollBack(); _syslog("支付轮询", '订单支付异常:' . $e->getMessage()); return json_fail($e->getMessage()); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); return json_fail('查询失败'); } } }