海南旅游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.

475 lines
16 KiB

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