海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

473 lines
15 KiB

5 years ago
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Common\PayType;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\Agent;
  6. use App\Models\AgentProduct;
  7. use App\Models\AgentSetting;
  8. use App\Models\Coupon;
  9. use App\Models\OrderProductItem;
  10. use App\Models\Product;
  11. use App\Models\User;
  12. use App\Models\Order;
  13. use EasyWeChat\Factory;
  14. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  15. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  16. use GuzzleHttp\Exception\GuzzleException;
  17. use Illuminate\Database\Eloquent\Model;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\DB;
  20. use App\Common\OrderStatus as Status;
  21. use Illuminate\Support\Facades\Storage;
  22. /**
  23. * 订单
  24. * Class OrderController
  25. * @package App\Http\Controllers\Api
  26. */
  27. class OrderController extends Controller
  28. {
  29. private $earnest = 200; //定金和首款默认金额 TODO 定金支付和首款支付暂定为200
  30. //订单列表
  31. public function index(Request $request)
  32. {
  33. $formData = $request->only(['page', 'status']);
  34. $request->validate([
  35. 'page' => 'regex:/^\d+$/',
  36. 'status' => 'nullable|regex:/^\d+(,\d+)*$/'
  37. ], [
  38. 'page.regex' => '页码错误',
  39. 'status.regex' => '订单状态错误'
  40. ]);
  41. $order_list = Order::where('user_id', $this->user_id);
  42. if (isset($formData['status'])) {
  43. if (preg_match('/^\d+$/', $formData['status'])) {
  44. $order_list = $order_list->where('status', $formData['status']);
  45. } else {
  46. $order_list = $order_list->whereIn('status', explode(',', $formData['status']));
  47. }
  48. }
  49. $order_list = $order_list->select('id', 'agent_product_id', 'product_id', 'title', 'picture', 'price', 'num', 'status', 'timeout', 'created_at')
  50. ->orderBy('id', 'DESC')
  51. ->simplePaginate(15)
  52. ->toArray();
  53. $time = time();
  54. $prefix = Storage::disk('public')->url('');
  55. foreach ($order_list['data'] as &$v) {
  56. //图片加上域名
  57. if (strpos($v['picture'], $prefix) === false) {
  58. $v['picture'] = $prefix . $v['picture'];
  59. }
  60. if (strpos($v['picture'], $prefix) === false) {
  61. $v['picture'] = $prefix . $v['picture'];
  62. }
  63. if (!empty($v['pictures']) && is_array($v['pictures'])) {
  64. $v['pictures'] = array_map(function($item) use ($prefix) {
  65. return strpos($item, $prefix) === false ? $prefix . $item : $item;
  66. }, $v['pictures']);
  67. }
  68. //未付款订单提示剩余付款时间
  69. if ($v['timeout'] !== null) {
  70. $second = strtotime($v['timeout']) - $time;
  71. if ($second > 0 && $v['status'] == Status::UNPAID) {
  72. $v['status_text'] = '请在' . ceil($second / 60) . "分钟内付款";
  73. } else if ($second > 0 && $v['status'] == Status::OFFLINE_UNPAID) {
  74. $v['status_text'] = '请在' . ceil($second / 60) . "分钟内线下付款";
  75. } else if ($second < 0 && $v['status'] == Status::PAY_EARNEST) {
  76. $v['status_text'] = '尾款支付已超时';
  77. } /*else { //此部分由定时处理
  78. $timeout_ids[] = $v['id'];
  79. $v['status'] = Status::CANCEL;
  80. $v['status_text'] = '已取消';
  81. //此部分已由定时任务处理
  82. Product::query()->find($v['product_id'])->increment('stock', $v['num']);
  83. }*/
  84. }
  85. }
  86. return $this->success($order_list);
  87. }
  88. //提交订单
  89. public function create(Request $request)
  90. {
  91. $formData = $request->only(['id', 'name', 'mobile', 'pay_type', 'num']);
  92. $formData = array_map(fn($v) => trim($v), $formData); //过滤,删除首尾空
  93. //表单验证
  94. $pay_type_values = join(',', array_keys(PayType::array()));
  95. $request->validate([
  96. 'id' => ['required', 'regex:/^\d+$/'],
  97. 'name' => ['required', 'between:2,20'],
  98. 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
  99. 'pay_type' => ['required', 'in:' . $pay_type_values],
  100. 'num' => ['required', 'min:1'],
  101. ], [
  102. 'id.required' => '未指定产品ID',
  103. 'name.required' => '请输入联系人姓名',
  104. 'mobile.required' => '请输入联系手机号',
  105. 'id.regex' => '产品ID错误',
  106. 'name.between' => '联系人姓名在2~20字符之间',
  107. 'mobile.regex' => '请输入11位手机号',
  108. 'pay_type.required' => '请选择支付方式',
  109. 'pay_type.in' => '不存在此支付方式',
  110. 'num.required' => '请输入购买数量',
  111. 'num.min' => '购买数量输入错误',
  112. ]);
  113. $ap = AgentProduct::query()
  114. ->where('id', $formData['id'])
  115. ->with(['coupon', 'product', 'agentCloudProduct:id,price'])
  116. ->has('product')
  117. ->first();
  118. if (!$ap || !$ap->product) {
  119. $this->error('产品不存在或已下架');
  120. }
  121. $coupon_ids = [];
  122. if ($ap->coupon) {
  123. foreach ($ap->coupon as $v) {
  124. $coupon_ids[] = $v['id'];
  125. }
  126. }
  127. DB::beginTransaction();
  128. try {
  129. $price = $this->calc($ap->price, $formData['num'], $formData['pay_type'], $ap);
  130. //供应商产品表减库存
  131. $product_ids = explode(',', $ap->product_ids);
  132. $affect_row = Product::query()
  133. ->where('stock', '>=', $formData['num']) //乐观锁
  134. ->whereIn('id', $product_ids)
  135. ->decrement('stock', $formData['num']);
  136. if ($affect_row != count($product_ids)) {
  137. throw new \Exception('供应产品库存不足');
  138. }
  139. //代理商产品表减库存
  140. $affect_row = AgentProduct::query()
  141. ->where('stock', '>=', $formData['num']) //乐观锁
  142. ->where('id', $ap->id)
  143. ->decrement('stock', $formData['num']);
  144. if (!$affect_row) {
  145. throw new \Exception('商户产品库存不足');
  146. }
  147. //未付款时定金/订金的超时时间依然使用默认的订单超时时间,付定金/订金之后才使用定金超时时间
  148. $order_timeout = AgentSetting::val($this->agent_id, 'order_timeout') ?? 60; //默认60分钟
  149. $timeout = date('Y-m-d H:i:s', time() + $order_timeout * 60); //60 * 分钟转为秒
  150. // 存入订单表
  151. $order = Order::query()->create([
  152. 'user_id' => $this->user_id,
  153. 'agent_id' => $this->agent_id,
  154. 'order_no' => $this->getOrderNo(),
  155. 'num' => $formData['num'],
  156. 'price' => $price,
  157. 'name' => $formData['name'],
  158. 'mobile' => $formData['mobile'],
  159. 'title' => $ap->title,
  160. 'picture' => $ap->picture,
  161. 'agent_product_id' => $ap->id,
  162. 'product_id' => $ap->product_id,
  163. 'product_ids' => $ap->product->product_ids ?? $ap->product_id,
  164. 'status' => $formData['pay_type'] == PayType::OFFLINE ? Status::OFFLINE_UNPAID : Status::UNPAID,
  165. 'pay_type' => $formData['pay_type'],
  166. 'coupon_id' => join(',', $coupon_ids),
  167. 'guide_id' => $ap->guide_id,
  168. 'timeout' => $timeout,
  169. 'agent_cloud_pid' => $ap->agent_cloud_pid,
  170. 'agent_cloud_price' => $ap->agentCloudProduct->price,
  171. ]);
  172. //存入订单产品表
  173. $supplier_product_info = Product::whereIn('id', $product_ids)
  174. ->orderBy('id')->get(['id AS product_id', 'supplier_id', 'price'])->toArray();
  175. $order_id = $order->id;
  176. $agent_id = $this->agent_id;
  177. $agent_product_id = $ap->id;
  178. foreach ($supplier_product_info as &$v) {
  179. $v['order_id'] = $order_id;
  180. $v['agent_id'] = $agent_id;
  181. $v['agent_product_id'] = $agent_product_id;
  182. $v['num'] = $formData['num'];
  183. }
  184. OrderProductItem::insert($supplier_product_info);
  185. DB::commit();
  186. } catch (\Exception $e) {
  187. DB::rollBack();
  188. return $this->error($e->getMessage());
  189. }
  190. if ($formData['pay_type'] == PayType::OFFLINE) { //线下支付
  191. return $this->success(['id' => $order_id], '操作成功,请及时联系客服付款');
  192. } else { //在线支付或定金支付
  193. $config = $this->payConfig($order, $price);
  194. if (!empty($config['paySign'])) {
  195. return $this->success($config);
  196. } else {
  197. return $this->error($config['err_code_des'] ?? join(',', $config));
  198. }
  199. }
  200. }
  201. //申请退款
  202. public function refund(Request $request)
  203. {
  204. $formData = $request->only(['id', 'desc', 'pictures']);
  205. $request->validate([
  206. 'id' => 'required|integer',
  207. 'desc' => 'required|string',
  208. 'pictures' => 'nullable|array',
  209. ], [
  210. '*.required' => '内容输入不完整',
  211. 'pictures.array' => '图片必须是数组',
  212. ]);
  213. //去掉图片地址前的域名
  214. $prefix = Storage::disk('public')->url('');
  215. foreach ($formData['pictures'] as &$v) {
  216. $v = str_replace($prefix, '', $v);
  217. }
  218. //TODO 需要后台处理,然后向微信发起退款申请
  219. $order = Order::firstWhere(['id' => $formData['id'], 'user_id' => $this->user_id]);
  220. if (!$order) {
  221. return $this->error('订单不存在');
  222. }
  223. //订金/定金/首付款不允许退款,只有付全款才能申请退款
  224. if (!in_array($order->status, [Status::PAID, Status::PAID_RETAINAGE])) {
  225. return $this->error('当前订单状态不允许退款');
  226. }
  227. $order->refund_info = [
  228. 'desc' => strip_tags($formData['desc']),
  229. 'refund_no' => $this->getOrderNo(), //退款单号
  230. 'pictures' => $formData['pictures'] ?? [],
  231. 'old_status' => $order->status,
  232. ];
  233. $order->status = Status::REFUNDING;
  234. $order->save();
  235. return $this->success();
  236. }
  237. //获取应付金额及相关产品信息
  238. public function getPrice(Request $request)
  239. {
  240. $formData = $request->only(['id', 'num', 'pay_type']);
  241. $request->validate([
  242. 'id' => 'required|integer',
  243. 'num' => 'required|integer',
  244. 'pay_type' => 'required|integer',
  245. ], [
  246. '*.required' => '参数缺失',
  247. '*.integer' => '参数类型错误',
  248. ]);
  249. if (!$formData['num'] || $formData['num'] < 1) {
  250. return $this->error('未指定产品数量');
  251. }
  252. $ap = AgentProduct::query()
  253. ->has('product')
  254. ->with('coupon:agent_product_id,type,detail,agent_id,tag,start_at,end_at')
  255. ->find($formData['id'], ['id', 'price', 'original_price', 'product_id', 'title', 'pictures', 'earnest', 'earnest_timeout', 'deposit', 'deposit_timeout']);
  256. if (!$ap) {
  257. return $this->error('产品信息不存在');
  258. }
  259. $prefix = Storage::disk('public')->url('');
  260. $ap->pictures = array_map(fn($v) => $prefix . $v, $ap->pictures);
  261. //如果是线下支付,显示的价格跟在线全款支付价格一样
  262. if ($formData['pay_type'] == PayType::OFFLINE) {
  263. $formData['pay_type'] = PayType::ONLINE;
  264. }
  265. $ap->final_price = $this->calc($ap->price, $formData['num'], $formData['pay_type'], $ap);
  266. $ap->num = $formData['num'];
  267. return $this->success($ap);
  268. }
  269. //订单支付(在订单列表发起)
  270. public function pay(Request $request)
  271. {
  272. $id = (int)request()->input('id');
  273. //订单信息
  274. $order = Order::query()
  275. ->with('agentProduct')
  276. ->where(['user_id' => $this->user_id, 'agent_id' => $this->agent_id])
  277. ->whereRaw('`timeout` >= NOW()')
  278. ->whereIn('status', [Status::UNPAID, Status::PAY_EARNEST])
  279. ->find($id);
  280. if (!$order) {
  281. return $this->error('订单已支付或已超时');
  282. }
  283. $ap = AgentProduct::with('coupon')->find($order->agent_product_id);
  284. //如果已经付定金或首付款,则仅支付尾款
  285. if ($order->status == Status::PAY_EARNEST) {
  286. $price = $order->price - $order->paid_money;
  287. } else {
  288. $price = $this->calc($order->price, $order->num, $order->pay_type, $ap);
  289. }
  290. $config = $this->payConfig($order, $price);
  291. if (!empty($config['paySign'])) {
  292. return $this->success($config);
  293. } else {
  294. return $this->error($config['err_code_des'] ?? join(',', $config));
  295. }
  296. }
  297. //获取支付配置信息
  298. private function payConfig($order, $price)
  299. {
  300. //用户openid
  301. $openid = User::query()->where('id', $this->user_id)->value('openid'); //此处要用where,value()用find有BUG
  302. //代理商信息
  303. $agent = Agent::query()->find($this->agent_id);
  304. $config = config('wechat.payment.default');
  305. $config = array_merge($config, [
  306. 'app_id' => $agent->appid,
  307. 'mch_id' => $agent->mchid,
  308. 'key' => $agent->mchkey,
  309. ]);
  310. $app = Factory::payment($config);
  311. try {
  312. $result = $app->order->unify([
  313. 'body' => $order->title,
  314. 'out_trade_no' => $order->order_no . '-' . $order->status, //后面加status,主要是为了方便微信支付回调时区分定金(首付款)和尾款支付
  315. 'total_fee' => 1, //TODO 测试暂时注释 round($price * 100), //支付金额单位为分
  316. 'notify_url' => route('wxpay_notify', ['agent_id' => $this->agent_id]), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  317. 'trade_type' => 'JSAPI',
  318. 'openid' => $openid,
  319. 'profit_sharing' => 'Y', //Y分账,N不分账,默认不分账,Y大写
  320. ]);
  321. } catch (InvalidArgumentException | InvalidConfigException | GuzzleException $e) {
  322. return ['error' => $e->getMessage(), 'line' => $e->getLine()];
  323. }
  324. if (empty($result['prepay_id'])) {
  325. return $result;
  326. }
  327. $jssdk = $app->jssdk;
  328. return $jssdk->bridgeConfig($result['prepay_id'], false) + ['id' => $order->id, 'order_no' => $order->order_no]; // 返回数组
  329. }
  330. //订单详情
  331. public function show()
  332. {
  333. $id = (int)request()->input('id');
  334. $fields = ['id', 'agent_id', 'order_no', 'agent_product_id', 'num', 'price', 'name', 'mobile', 'title', 'picture', 'status',
  335. 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'verify_code', 'created_at'];
  336. $order = Order::with('agent:id,appid,appsecret')
  337. ->where('user_id', $this->user_id)
  338. ->find($id, $fields);
  339. if (!$order) {
  340. return $this->error('订单不存在');
  341. }
  342. //订单ID和核销码拼接,查询时通过订单ID和核销码来查询,这样核销码不用建索引
  343. $order->verify_code = $order->verify_code ? $order->id . '-' . $order->verify_code : '';
  344. //如果有核销码,生成核销二维码
  345. if ($order->verify_code) {
  346. $config = [
  347. 'app_id' => $order->agent->appid,
  348. 'secret' => $order->agent->appsecret,
  349. ];
  350. $app = Factory::miniProgram($config);
  351. $response = $app->app_code->getUnlimit($order->verify_code, ['page' => 'pages/verification/index']);
  352. if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
  353. $filename = $response->saveAs(storage_path('app/public/verify_code'), $order->verify_code);
  354. $order->verify_qrcode = Storage::disk('public')->url('verify_code/' . $filename);
  355. }
  356. }
  357. unset($order->agent, $order->agent_id); //必须unset掉$order->agent,否则会造成appsecret泄漏
  358. $order->coupon = Coupon::query()
  359. ->whereIn('id', $order->coupon_id)
  360. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  361. ->get(['tag']);
  362. return $this->success($order);
  363. }
  364. /**
  365. * 计算最终价格(扣除优惠券之后的价格)
  366. * $price:原价;$coupon:优惠券;$num:产品数量;$pay_type:支付方式
  367. * @param float $price
  368. * @param int $num
  369. * @param int $pay_type
  370. * @param Model $agent_product
  371. * @return float
  372. */
  373. private function calc($price, $num, $pay_type, $agent_product)
  374. {
  375. //根据支付方式计算价格
  376. if (in_array($pay_type, [PayType::DEPOSIT_PAY, PayType::EARNEST_PAY, PayType::DOWN_PAYMENT])) {
  377. if ($pay_type == PayType::DEPOSIT_PAY && $agent_product->deposit && $agent_product->deposit_timeout) {
  378. return $agent_product->deposit;
  379. }
  380. if ($pay_type == PayType::EARNEST_PAY && $agent_product->earnest && $agent_product->earnest_timeout) {
  381. return $agent_product->earnest;
  382. }
  383. }
  384. $total_price = $price * $num;
  385. /*//没有任何优惠券时直接返回最终价
  386. if ($coupon && $coupon->isEmpty()) {
  387. return $total_price;
  388. }
  389. $coupon = $coupon->toArray();
  390. foreach ($coupon as $v) {
  391. // TODO 未判断优惠券有效期
  392. if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减
  393. if ($total_price >= $v['detail']['full']) {
  394. $total_price -= $v['detail']['reduction'];
  395. }
  396. } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折
  397. $total_price *= $v['detail']['discount'];
  398. }
  399. }*/
  400. return round($total_price, 2);
  401. }
  402. // 生成订单号
  403. private function getOrderNo(): string
  404. {
  405. list($micro, $sec) = explode(' ', microtime());
  406. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  407. return date('ymdHis', $sec) . $micro . mt_rand(1000, 9999);
  408. }
  409. }