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

484 lines
16 KiB

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