only(['page', 'status']); $request->validate([ 'page' => 'regex:/^\d+$/', 'status' => 'nullable|regex:/^\d+(,\d+)*$/' ], [ 'page.regex' => '页码错误', 'status.regex' => '订单状态错误' ]); $order_list = Order::where('user_id', $this->user_id); if (isset($formData['status'])) { if (preg_match('/^\d+$/', $formData['status'])) { $order_list = $order_list->where('status', $formData['status']); } else { $order_list = $order_list->whereIn('status', explode(',', $formData['status'])); } } $order_list = $order_list->select('id', 'agent_product_id', 'product_id', 'title', 'picture', 'price', 'num', 'status', 'timeout', 'created_at') ->orderBy('id', 'DESC') ->simplePaginate(15) ->toArray(); $time = time(); $prefix = Storage::disk('public')->url(''); foreach ($order_list['data'] as &$v) { //图片加上域名 if (strpos($v['picture'], $prefix) === false) { $v['picture'] = $prefix . $v['picture']; } if (strpos($v['picture'], $prefix) === false) { $v['picture'] = $prefix . $v['picture']; } if (!empty($v['pictures']) && is_array($v['pictures'])) { $v['pictures'] = array_map(function($item) use ($prefix) { return strpos($item, $prefix) === false ? $prefix . $item : $item; }, $v['pictures']); } //未付款订单提示剩余付款时间 if ($v['timeout'] !== null) { $second = strtotime($v['timeout']) - $time; if ($second > 0) { $text_arr = [ Status::UNPAID => '付款', Status::OFFLINE_UNPAID => '线下付款', Status::PAY_EARNEST => '付尾款', ]; if (isset($text_arr[$v['status']])) { $v['status_text'] = '请在' . ceil($second / 60) . "分钟内" . ($text_arr[$v['status']] ?? '付款'); } } else if ($second < 0 && $v['status'] == Status::PAY_EARNEST) { $v['status_text'] = '尾款支付已超时'; } /*else { //此部分由定时处理 $timeout_ids[] = $v['id']; $v['status'] = Status::CANCEL; $v['status_text'] = '已取消'; //此部分已由定时任务处理 Product::query()->find($v['product_id'])->increment('stock', $v['num']); }*/ } } return $this->success($order_list); } //提交订单 public function create(Request $request) { $formData = $request->only(['id', 'name', 'mobile', 'pay_type', 'num']); $formData = array_map(fn($v) => trim($v), $formData); //过滤,删除首尾空 //表单验证 $pay_type_values = join(',', array_keys(PayType::array())); $request->validate([ 'id' => ['required', 'regex:/^\d+$/'], 'name' => ['required', 'between:2,20'], 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'], 'pay_type' => ['required', 'in:' . $pay_type_values], 'num' => ['required', 'min:1'], ], [ 'id.required' => '未指定产品ID', 'name.required' => '请输入联系人姓名', 'mobile.required' => '请输入联系手机号', 'id.regex' => '产品ID错误', 'name.between' => '联系人姓名在2~20字符之间', 'mobile.regex' => '请输入11位手机号', 'pay_type.required' => '请选择支付方式', 'pay_type.in' => '不存在此支付方式', 'num.required' => '请输入购买数量', 'num.min' => '购买数量输入错误', ]); $ap = AgentProduct::query() ->with(['coupon', 'product', 'agentCloudProduct:id,price']) ->where('stock', '>=', $formData['num']) ->where(['id' => $formData['id'], 'status' => ProductStatus::ON_SALE, 'agent_id' => $this->agent_id]) //判断agent_id,防止新入驻小程序的演示产品被下单 ->whereDoesntHave('agentProductItem', function ($query) { return $query->whereHas('product', function ($query) { return $query->where('stock', '<=', 0)->orWhere('status', '<>', ProductStatus::ON_SALE); }); }) ->first(); if (!$ap || !$ap->product) { return $this->error('产品已下架或库存不足'); } $coupon_ids = []; if ($ap->coupon) { foreach ($ap->coupon as $v) { $coupon_ids[] = $v['id']; } } DB::beginTransaction(); try { $price = $this->calc($ap->price, $formData['num'], $formData['pay_type'], $ap); //供应商产品表减库存 $product_ids = explode(',', $ap->product_ids); $affect_row = Product::query() ->where('stock', '>=', $formData['num']) //乐观锁 ->whereIn('id', $product_ids) ->decrement('stock', $formData['num']); if ($affect_row != count($product_ids)) { throw new \Exception('供应产品库存不足'); } //代理商产品表减库存 $affect_row = AgentProduct::query() ->where('stock', '>=', $formData['num']) //乐观锁 ->where('id', $ap->id) ->decrement('stock', $formData['num']); if (!$affect_row) { throw new \Exception('商户产品库存不足'); } //未付款时定金/订金的超时时间依然使用默认的订单超时时间,付定金/订金之后才使用定金超时时间 $order_timeout = AgentSetting::val($this->agent_id, 'order_timeout') ?? 60; //默认60分钟 $timeout = date('Y-m-d H:i:s', time() + $order_timeout * 60); //60 * 分钟转为秒 // 存入订单表 $order = Order::query()->create([ 'user_id' => $this->user_id, 'agent_id' => $this->agent_id, 'order_no' => $this->getOrderNo(), 'num' => $formData['num'], 'price' => $price, 'name' => $formData['name'], 'mobile' => $formData['mobile'], 'title' => $ap->title, 'picture' => $ap->picture, 'agent_product_id' => $ap->id, 'product_id' => $ap->product_id, 'product_ids' => $ap->product->product_ids ?? $ap->product_id, 'status' => $formData['pay_type'] == PayType::OFFLINE ? Status::OFFLINE_UNPAID : Status::UNPAID, 'pay_type' => $formData['pay_type'], 'coupon_id' => join(',', $coupon_ids), 'guide_id' => $ap->guide_id, 'guide_price' => $ap->guide_price, 'timeout' => $timeout, 'agent_cloud_pid' => $ap->agent_cloud_pid, 'agent_cloud_price' => $ap->agentCloudProduct->price ?? 0, ]); //存入订单产品表 $supplier_product_info = Product::whereIn('id', $product_ids) ->orderBy('id')->get(['id AS product_id', 'supplier_id', 'price'])->toArray(); $order_id = $order->id; $agent_id = $this->agent_id; $agent_product_id = $ap->id; foreach ($supplier_product_info as &$v) { $v['order_id'] = $order_id; $v['agent_id'] = $agent_id; $v['agent_product_id'] = $agent_product_id; $v['num'] = $formData['num']; } OrderProductItem::insert($supplier_product_info); DB::commit(); } catch (\Exception $e) { DB::rollBack(); return $this->error($e->getMessage()); } if ($formData['pay_type'] == PayType::OFFLINE) { //线下支付 return $this->success(['id' => $order_id], '操作成功,请及时联系客服付款'); } else { //在线支付或定金支付 /*$config = $this->payConfig($order, $price); if (!empty($config['paySign'])) { return $this->success($config); } else { return $this->error($config['err_code_des'] ?? join(',', $config)); }*/ // TODO 跳转支付专用 return $this->success(['id' => $order->id, 'jump' => true, 'jump_appid' => AdminSetting::val('payee_appid')]); } } //申请退款 public function refund(Request $request) { $formData = $request->only(['id', 'desc', 'pictures']); $request->validate([ 'id' => 'required|integer', 'desc' => 'required|string', 'pictures' => 'nullable|array', ], [ '*.required' => '内容输入不完整', 'pictures.array' => '图片必须是数组', ]); //去掉图片地址前的域名 $prefix = Storage::disk('public')->url(''); foreach ($formData['pictures'] as &$v) { $v = str_replace($prefix, '', $v); } //TODO 需要后台处理,然后向微信发起退款申请 $order = Order::firstWhere(['id' => $formData['id'], 'user_id' => $this->user_id]); if (!$order) { return $this->error('订单不存在'); } //订金/定金/首付款不允许退款,只有付全款才能申请退款 if (!in_array($order->status, [Status::PAID, Status::PAID_RETAINAGE])) { return $this->error('当前订单状态不允许退款'); } $order->refund_info = [ 'desc' => strip_tags($formData['desc']), 'refund_no' => $this->getOrderNo(), //退款单号 'pictures' => $formData['pictures'] ?? [], 'old_status' => $order->status, ]; $order->status = Status::REFUNDING; $order->save(); return $this->success(); } //获取应付金额及相关产品信息 public function getPrice(Request $request) { $formData = $request->only(['id', 'num', 'pay_type']); $request->validate([ 'id' => 'required|integer', 'num' => 'required|integer', 'pay_type' => 'required|integer', ], [ '*.required' => '参数缺失', '*.integer' => '参数类型错误', ]); if (!$formData['num'] || $formData['num'] < 1) { return $this->error('未指定产品数量'); } $ap = AgentProduct::query() ->has('product') ->with('coupon:agent_product_id,type,detail,agent_id,tag,start_at,end_at') ->find($formData['id'], ['id', 'price', 'original_price', 'product_id', 'title', 'pictures', 'earnest', 'earnest_timeout', 'deposit', 'deposit_timeout']); if (!$ap) { return $this->error('产品信息不存在'); } $prefix = Storage::disk('public')->url(''); $ap->pictures = array_map(fn($v) => $prefix . $v, $ap->pictures); //如果是线下支付,显示的价格跟在线全款支付价格一样 if ($formData['pay_type'] == PayType::OFFLINE) { $formData['pay_type'] = PayType::ONLINE; } $ap->final_price = $this->calc($ap->price, $formData['num'], $formData['pay_type'], $ap); $ap->num = $formData['num']; return $this->success($ap); } //订单支付(在订单列表发起) public function pay(Request $request) { $id = (int)request()->input('id'); //订单信息 $order = Order::query() ->with('agentProduct') ->where(['user_id' => $this->user_id, 'agent_id' => $this->agent_id]) ->whereRaw('`timeout` >= NOW()') ->whereIn('status', [Status::UNPAID, Status::PAY_EARNEST]) ->find($id); if (!$order) { return $this->error('订单已支付或已超时'); } // TODO 跳转支付专用 return $this->success(['id' => $id, 'jump' => true, 'jump_appid' => AdminSetting::val('payee_appid')]); /*$ap = AgentProduct::with('coupon')->find($order->agent_product_id); //如果已经付定金或首付款,则仅支付尾款 if ($order->status == Status::PAY_EARNEST) { $price = $order->price - $order->paid_money; } else { $price = $this->calc($order->price, $order->num, $order->pay_type, $ap); } $config = $this->payConfig($order, $price); if (!empty($config['paySign'])) { return $this->success($config); } else { return $this->error($config['err_code_des'] ?? join(',', $config)); }*/ } //获取支付配置信息 private function payConfig($order, $price) { //用户openid $openid = User::query()->where('id', $this->user_id)->value('openid'); //此处要用where,value()用find有BUG //代理商信息 $agent = Agent::query()->find($this->agent_id); $config = config('wechat.payment.default'); $config = array_merge($config, [ 'app_id' => $agent->appid, 'mch_id' => $agent->mchid, 'key' => $agent->mchkey, ]); $app = Factory::payment($config); try { $result = $app->order->unify([ 'body' => $order->title, 'out_trade_no' => $order->order_no . '-' . $order->status, //后面加status,主要是为了方便微信支付回调时区分定金(首付款)和尾款支付 'total_fee' => round($price * 100), //支付金额单位为分 'notify_url' => route('wxpay_notify', ['agent_id' => $this->agent_id]), // 支付结果通知网址,如果不设置则会使用配置里的默认地址 'trade_type' => 'JSAPI', 'openid' => $openid, 'profit_sharing' => 'Y', //Y分账,N不分账,默认不分账,Y大写 ]); } catch (InvalidArgumentException | InvalidConfigException | GuzzleException $e) { return ['error' => $e->getMessage(), 'file' => basename($e->getFile()), 'line' => $e->getLine()]; } if (empty($result['prepay_id'])) { return $result; } $jssdk = $app->jssdk; return $jssdk->bridgeConfig($result['prepay_id'], false) + ['id' => $order->id, 'order_no' => $order->order_no]; // 返回数组 } //订单详情 public function show() { $id = (int)request()->input('id'); $fields = ['id', 'agent_id', 'order_no', 'agent_product_id', 'num', 'price', 'name', 'mobile', 'title', 'picture', 'status', 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'verify_code', 'created_at']; $order = Order::with('agent:id,appid,appsecret') ->where('user_id', $this->user_id) ->find($id, $fields); if (!$order) { return $this->error('订单不存在'); } //订单ID和核销码拼接,查询时通过订单ID和核销码来查询,这样核销码不用建索引 $order->verify_code = $order->verify_code ? $order->id . '-' . $order->verify_code : ''; //如果有核销码,生成核销二维码 if ($order->verify_code) { $setting = AdminSetting::val(['service_appid', 'service_appsecret', 'service_token', 'service_aeskey']); $config = [ 'app_id' => $setting['service_appid'], 'secret' => $setting['service_appsecret'], 'token' => $setting['service_token'], 'aes_key' => $setting['service_aeskey'], ]; $app = Factory::openPlatform($config); $refreshToken = $app->getAuthorizer($order->agent->appid)['authorization_info']['authorizer_refresh_token'] ?? null; if (!$refreshToken) { return $this->error('获取refresh_token失败'); } $app = $app->miniProgram($order->agent->appid, $refreshToken); $response = $app->app_code->getUnlimit($order->verify_code, ['page' => 'pages/verification/index']); if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) { $filename = $response->saveAs(storage_path('app/public/verify_code'), $order->verify_code); $order->verify_qrcode = Storage::disk('public')->url('verify_code/' . $filename); } } unset($order->agent, $order->agent_id); //必须unset掉$order->agent,否则会造成appsecret泄漏 $order->coupon = Coupon::query() ->whereIn('id', $order->coupon_id) ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,]) ->get(['tag']); return $this->success($order); } /** * 计算最终价格(扣除优惠券之后的价格) * $price:原价;$coupon:优惠券;$num:产品数量;$pay_type:支付方式 * @param float $price * @param float $num * @param int $pay_type * @param AgentProduct $agent_product * @return float */ private function calc(float $price, float $num, int $pay_type, AgentProduct $agent_product): float { /** 修改需要同步修改sharePay里面的 */ //根据支付方式计算价格 if (in_array($pay_type, [PayType::DEPOSIT_PAY, PayType::EARNEST_PAY, PayType::DOWN_PAYMENT])) { if ($pay_type == PayType::DEPOSIT_PAY && $agent_product->deposit && $agent_product->deposit_timeout) { return $agent_product->deposit; } else if ($pay_type == PayType::EARNEST_PAY && $agent_product->earnest && $agent_product->earnest_timeout) { return $agent_product->earnest; } } $total_price = $price * $num; /*//没有任何优惠券时直接返回最终价 if ($coupon && $coupon->isEmpty()) { return $total_price; } $coupon = $coupon->toArray(); foreach ($coupon as $v) { // TODO 未判断优惠券有效期 if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减 if ($total_price >= $v['detail']['full']) { $total_price -= $v['detail']['reduction']; } } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折 $total_price *= $v['detail']['discount']; } }*/ return round($total_price, 2); } // 生成订单号 private function getOrderNo(): string { list($micro, $sec) = explode(' ', microtime()); $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT); return date('ymdHis', $sec) . $micro . mt_rand(1000, 9999); } }