AdvertOrderService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Common;
  12. use App\Models\AdvertModel;
  13. use App\Models\AdvertOrderModel;
  14. use App\Models\MemberModel;
  15. use App\Services\Api\MemberPaymentService;
  16. use App\Services\BaseService;
  17. use App\Services\ConfigService;
  18. use App\Services\RedisService;
  19. /**
  20. * 用户广告订单-服务类
  21. * Class AdvertOrderService
  22. * @package App\Services\Common
  23. */
  24. class AdvertOrderService extends BaseService
  25. {
  26. // 静态对象
  27. protected static $instance = null;
  28. /**
  29. * 构造函数
  30. * @since 2020/11/10
  31. * LoginService constructor.
  32. */
  33. public function __construct()
  34. {
  35. $this->model = new AdvertOrderModel();
  36. $this->advertModel = new AdvertModel();
  37. $this->memberModel = new MemberModel();
  38. }
  39. /**
  40. * 静态入口
  41. * @return static|null
  42. */
  43. public static function make()
  44. {
  45. if (!self::$instance) {
  46. self::$instance = (new static());
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * 购买
  52. * @param $userId
  53. * @param $params
  54. * @return false|int|number
  55. */
  56. public function buy($userId, $params)
  57. {
  58. $id = isset($params['id']) ? intval($params['id']) : 0;
  59. $num = isset($params['num']) ? intval($params['num']) : 0;
  60. if ($id <= 0 || $num<=0) {
  61. $this->error = '1013';
  62. return false;
  63. }
  64. // 验证参数
  65. $config = \App\Services\ConfigService::make()->getConfigOptionByGroup(5);
  66. $tradeOpen = isset($config['trade_usdt_open']) ? $config['trade_usdt_open'] : 0;
  67. $tradeMinNum = isset($config['trade_min_num']) ? $config['trade_min_num'] : 0;
  68. $tradeMaxNum = isset($config['trade_max_num']) ? $config['trade_max_num'] : 0;
  69. $trademinMoney = isset($config['trade_min_money']) ? $config['trade_min_money'] : 0;
  70. $tradeMaxMoney = isset($config['trade_max_money']) ? $config['trade_max_money'] : 0;
  71. $tradePrice = isset($config['usdt_buy_price']) ? $config['usdt_buy_price'] : 0;
  72. $tradeLimitNum = isset($config['trade_no_catch']) ? $config['trade_no_catch'] : 0;
  73. // 是否开启交易
  74. if ($tradeOpen != 1) {
  75. $this->error = '1013';
  76. return false;
  77. }
  78. $info = AdvertService::make()->getInfo($id);
  79. $tradeType = isset($info['type'])? $info['type'] : 0;
  80. $priceType = isset($info['price_type'])? $info['price_type'] : 0;
  81. $price = isset($info['price'])? $info['price'] : 0;
  82. $businessId = isset($info['business_id'])? $info['business_id'] : 0;
  83. if(empty($info) || $info['status'] != 1){
  84. $this->error = '4001';
  85. return false;
  86. }
  87. if ($tradePrice <= 0 && $priceType == 2) {
  88. $this->error = '3002';
  89. return false;
  90. }
  91. // 验证数量或金额
  92. if ($priceType == 2) {
  93. $price = floatval($tradePrice + $price);
  94. }
  95. $total = floatval($price * $num);
  96. // 用户信息
  97. $userInfo = MemberService::make()->getInfo($userId);
  98. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  99. $idcardCheck = isset($userInfo['idcard_check']) ? $userInfo['idcard_check'] : 0;
  100. $username = isset($userInfo['username']) && $userInfo['username'] ? format_account($userInfo['username']) : '';
  101. if ($status != 1) {
  102. $this->error = '2009';
  103. return false;
  104. }
  105. // 未处理订单
  106. $noCatchOrder = $this->checkOrderNoCatch($userId, 1);
  107. if ($tradeLimitNum > 0 && $noCatchOrder >= $tradeLimitNum) {
  108. $this->error = lang(3005, ['num' => $tradeLimitNum]);
  109. return false;
  110. }
  111. // 交易商家
  112. $businessInfo = MemberService::make()->getInfo($businessId);
  113. if (empty($businessInfo)) {
  114. $this->error = '3004';
  115. return false;
  116. }
  117. // 购买者身份信息
  118. $idcardData = [
  119. 'idcard' => isset($userInfo['idcard']) ? $userInfo['idcard'] : '',
  120. 'idcard_check' => isset($userInfo['idcard_check']) ? $userInfo['idcard_check'] : 0,
  121. 'idcard_front_img' => isset($userInfo['idcard_front_img']) ? $userInfo['idcard_front_img'] : '',
  122. 'idcard_back_img' => isset($userInfo['idcard_back_img']) ? $userInfo['idcard_back_img'] : '',
  123. 'idcard_hand_img' => isset($userInfo['idcard_hand_img']) ? $userInfo['idcard_hand_img'] : '',
  124. ];
  125. // 收款方式
  126. $payment = MemberPaymentService::make()->getPayment($businessInfo['id']);
  127. if (empty($payment)) {
  128. $this->error = '3015';
  129. return false;
  130. }
  131. $this->model->startTrans();
  132. $orderNo = get_order_num('OT');
  133. $data = [
  134. 'user_id' => $userId,
  135. 'business_id' => isset($businessInfo['id']) ? $businessInfo['id'] : 0,
  136. 'order_no' => $orderNo,
  137. 'type' => 1,
  138. 'pay_type' => isset($params['pay_type']) ? floatval($params['pay_type']) : 1,
  139. 'price' => $price,
  140. 'num' => $num,
  141. 'total' => $total,
  142. 'payment_id' => isset($payment['id']) ? intval($payment['id']) : 0,
  143. 'idcard_data' => $idcardData ? json_encode($idcardData, 256) : '',
  144. 'payment_data' => $payment ? json_encode($payment, 256) : '',
  145. 'create_time' => time(),
  146. 'update_time' => time(),
  147. 'status' => 1,
  148. 'mark' => 1,
  149. ];
  150. if (!$order = $this->model->edit($data)) {
  151. $this->model->rollBack();
  152. $this->error = '3023';
  153. return false;
  154. }
  155. if(!$this->memberModel->where(['id'=> $businessInfo['id']])->decrement('usdt_num', $num)){
  156. $this->model->rollBack();
  157. $this->error = '3020';
  158. return false;
  159. }
  160. $data = [
  161. 'order_no'=> $orderNo,
  162. 'user_id'=> $businessInfo['id'],
  163. 'type'=> 2,
  164. 'pay_type'=> 1,
  165. 'trade_type'=> 2,
  166. 'change_type'=> 2,
  167. 'num'=> $num,
  168. 'total'=> $total,
  169. 'balance'=> floatval($businessInfo['usdt_num']-$num),
  170. 'create_time'=> time(),
  171. 'update_time'=> time(),
  172. 'status'=> 1,
  173. 'mark'=>1,
  174. 'remark'=> '交易员卖出',
  175. ];
  176. if(!$this->capitalModel->edit($data)){
  177. $this->model->rollBack();
  178. $this->error = '3014';
  179. return false;
  180. }
  181. // 订单通知
  182. $data = [
  183. 'from_uid' => $userId,
  184. 'to_uid' => $businessInfo['id'],
  185. 'type' => 2,
  186. 'order_no' => $orderNo,
  187. 'chat_key' => ChatMessageService::make()->getChatKey($userId, $businessInfo['id']),
  188. 'message' => "来自用户{$username}的购买订单,金额{$total},单号{$orderNo},时间" . date('Y-m-d H:i:s'),
  189. 'message_type' => 1,
  190. 'create_time' => time(),
  191. 'update_time' => time(),
  192. 'status' => 1,
  193. 'mark' => 1,
  194. ];
  195. if (!ChatMessageService::make()->pushMessage($data)) {
  196. $this->model->rollBack();
  197. $this->error = '3031';
  198. return false;
  199. }
  200. $this->model->commit();
  201. return $order;
  202. }
  203. /**
  204. * 购买
  205. * @param $userId
  206. * @param $params
  207. * @return false|int|number
  208. */
  209. public function sell($userId, $params)
  210. {
  211. $id = isset($params['id']) ? intval($params['id']) : 0;
  212. $num = isset($params['num']) ? intval($params['num']) : 0;
  213. if ($id <= 0 || $num<=0) {
  214. $this->error = '1013';
  215. return false;
  216. }
  217. // 验证参数
  218. $config = \App\Services\ConfigService::make()->getConfigOptionByGroup(5);
  219. $tradeOpen = isset($config['trade_usdt_open']) ? $config['trade_usdt_open'] : 0;
  220. $tradeMinNum = isset($config['trade_min_num']) ? $config['trade_min_num'] : 0;
  221. $tradeMaxNum = isset($config['trade_max_num']) ? $config['trade_max_num'] : 0;
  222. $trademinMoney = isset($config['trade_min_money']) ? $config['trade_min_money'] : 0;
  223. $tradeMaxMoney = isset($config['trade_max_money']) ? $config['trade_max_money'] : 0;
  224. $tradePrice = isset($config['usdt_buy_price']) ? $config['usdt_sell_price'] : 0;
  225. $tradeLimitNum = isset($config['trade_no_catch']) ? $config['trade_no_catch'] : 0;
  226. // 是否开启交易
  227. if ($tradeOpen != 1) {
  228. $this->error = '1013';
  229. return false;
  230. }
  231. $info = AdvertService::make()->getInfo($id);
  232. $tradeType = isset($info['type'])? $info['type'] : 0;
  233. $priceType = isset($info['price_type'])? $info['price_type'] : 0;
  234. $price = isset($info['price'])? $info['price'] : 0;
  235. $businessId = isset($info['business_id'])? $info['business_id'] : 0;
  236. if(empty($info) || $info['status'] != 1){
  237. $this->error = '4001';
  238. return false;
  239. }
  240. if ($tradePrice <= 0 && $priceType == 2) {
  241. $this->error = '3002';
  242. return false;
  243. }
  244. // 验证数量或金额
  245. if ($priceType == 2) {
  246. $price = floatval($tradePrice + $price);
  247. }
  248. $total = floatval($price * $num);
  249. // 用户信息
  250. $userInfo = MemberService::make()->getInfo($userId);
  251. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  252. $idcardCheck = isset($userInfo['idcard_check']) ? $userInfo['idcard_check'] : 0;
  253. $username = isset($userInfo['username']) && $userInfo['username'] ? format_account($userInfo['username']) : '';
  254. if ($status != 1) {
  255. $this->error = '2009';
  256. return false;
  257. }
  258. // 未处理订单
  259. $noCatchOrder = $this->checkOrderNoCatch($userId, 2);
  260. if ($tradeLimitNum > 0 && $noCatchOrder >= $tradeLimitNum) {
  261. $this->error = lang(3005, ['num' => $tradeLimitNum]);
  262. return false;
  263. }
  264. // 交易商家
  265. $businessInfo = MemberService::make()->getInfo($businessId);
  266. if (empty($businessInfo)) {
  267. $this->error = '3004';
  268. return false;
  269. }
  270. // 购买者身份信息
  271. $idcardData = [
  272. 'idcard' => isset($userInfo['idcard']) ? $userInfo['idcard'] : '',
  273. 'idcard_check' => isset($userInfo['idcard_check']) ? $userInfo['idcard_check'] : 0,
  274. 'idcard_front_img' => isset($userInfo['idcard_front_img']) ? $userInfo['idcard_front_img'] : '',
  275. 'idcard_back_img' => isset($userInfo['idcard_back_img']) ? $userInfo['idcard_back_img'] : '',
  276. 'idcard_hand_img' => isset($userInfo['idcard_hand_img']) ? $userInfo['idcard_hand_img'] : '',
  277. ];
  278. // 收款方式
  279. $payment = MemberPaymentService::make()->getPayment($userId);
  280. if (empty($payment)) {
  281. $this->error = '3015';
  282. return false;
  283. }
  284. $this->model->startTrans();
  285. $orderNo = get_order_num('OT');
  286. $data = [
  287. 'user_id' => $userId,
  288. 'business_id' => isset($businessInfo['id']) ? $businessInfo['id'] : 0,
  289. 'order_no' => $orderNo,
  290. 'type' => 1,
  291. 'pay_type' => isset($params['pay_type']) ? floatval($params['pay_type']) : 1,
  292. 'price' => $price,
  293. 'num' => $num,
  294. 'total' => $total,
  295. 'payment_id' => isset($payment['id']) ? intval($payment['id']) : 0,
  296. 'idcard_data' => $idcardData ? json_encode($idcardData, 256) : '',
  297. 'payment_data' => $payment ? json_encode($payment, 256) : '',
  298. 'create_time' => time(),
  299. 'update_time' => time(),
  300. 'status' => 1,
  301. 'mark' => 1,
  302. ];
  303. if (!$order = $this->model->edit($data)) {
  304. $this->model->rollBack();
  305. $this->error = '3023';
  306. return false;
  307. }
  308. if(!$this->memberModel->where(['id'=> $businessInfo['id']])->decrement('usdt_num', $num)){
  309. $this->model->rollBack();
  310. $this->error = '3020';
  311. return false;
  312. }
  313. $data = [
  314. 'order_no'=> $orderNo,
  315. 'user_id'=> $businessInfo['id'],
  316. 'type'=> 2,
  317. 'pay_type'=> 1,
  318. 'trade_type'=> 2,
  319. 'change_type'=> 2,
  320. 'num'=> $num,
  321. 'total'=> $total,
  322. 'balance'=> floatval($businessInfo['usdt_num']-$num),
  323. 'create_time'=> time(),
  324. 'update_time'=> time(),
  325. 'status'=> 1,
  326. 'mark'=>1,
  327. 'remark'=> '交易员卖出',
  328. ];
  329. if(!$this->capitalModel->edit($data)){
  330. $this->model->rollBack();
  331. $this->error = '3014';
  332. return false;
  333. }
  334. // 订单通知
  335. $data = [
  336. 'from_uid' => $userId,
  337. 'to_uid' => $businessInfo['id'],
  338. 'type' => 2,
  339. 'order_no' => $orderNo,
  340. 'chat_key' => ChatMessageService::make()->getChatKey($userId, $businessInfo['id']),
  341. 'message' => "来自用户{$username}的购买订单,金额{$total},单号{$orderNo},时间" . date('Y-m-d H:i:s'),
  342. 'message_type' => 1,
  343. 'create_time' => time(),
  344. 'update_time' => time(),
  345. 'status' => 1,
  346. 'mark' => 1,
  347. ];
  348. if (!ChatMessageService::make()->pushMessage($data)) {
  349. $this->model->rollBack();
  350. $this->error = '3031';
  351. return false;
  352. }
  353. $this->model->commit();
  354. return $order;
  355. }
  356. /**
  357. * 获取未支付或处理的订单数
  358. * @param $userId
  359. * @param int $type
  360. * @return mixed
  361. */
  362. public function checkOrderNoCatch($userId, $type = 1)
  363. {
  364. return $this->model->where(['user_id' => $userId, 'type' => $type, 'mark' => 1])
  365. ->whereIn('status', [1, 2, 7])
  366. ->count('id');
  367. }
  368. /**
  369. * 自动取消广告订单处理
  370. * @return false
  371. */
  372. public function catchInvalidOrder(){
  373. $cacheKey = "caches:adverts:cancels:";
  374. if(RedisService::get($cacheKey.'lock')){
  375. return false;
  376. }
  377. RedisService::set($cacheKey.'lock', 1, rand(3, 5));
  378. $overtime = ConfigService::make()->getConfigByCode('trade_order_overtime');
  379. $cancelTime = ConfigService::make()->getConfigByCode('trade_order_cancel');
  380. $catchNum = ConfigService::make()->getConfigByCode('trade_order_catch_num');
  381. $catchNum = $catchNum > 0 ? $catchNum : 200;
  382. // 处理超时订单
  383. if ($overtime > 0) {
  384. $this->model->where(['mark' => 1])
  385. ->where('status', '<=', 2)
  386. ->where('create_time', '<=', time() - $overtime * 60)
  387. ->update(['status' => 7, 'catch_at' => time()]);
  388. }
  389. if ($cancelTime <= 0) {
  390. $this->error = '1023';
  391. return false;
  392. }
  393. $fail = 0;
  394. $success = 0;
  395. $this->model->where(function ($query) use ($cancelTime) {
  396. // 已更新为超时的订单
  397. $query->where(['mark' => 1, 'status' => 7])
  398. ->where('catch_at', '<=', time() - $cancelTime * 60);
  399. })
  400. ->orWhere(function ($query) use ($cancelTime, $overtime) {
  401. $query->where('mark', '=', 1)
  402. ->where('status', '<=', 2)
  403. ->where('create_time', '<=', time() - ($cancelTime + $overtime) * 60);
  404. })
  405. ->select(['id', 'user_id', 'business_id','advert_id','order_no', 'type', 'num','total'])
  406. ->take($catchNum)
  407. ->get()
  408. ->each(function ($item, $k) use($cacheKey, &$fail, &$success){
  409. // 客户卖出订单退还
  410. $date = date('Y-m-d H:i:s');
  411. $type = isset($item['type']) ? $item['type'] : 0;
  412. if ($type == 2) {
  413. if(!$this->orderReback($item['user_id'], $item)){
  414. $fail++;
  415. RedisService::set($cacheKey."order_{$item['order_no']}:u{$item['user_id']}_fail", ['order'=> $item,'msg'=> lang($this->error),'date'=> $date], 3600);
  416. }else{
  417. $success++;
  418. RedisService::set($cacheKey."order_{$item['order_no']}:u{$item['user_id']}_success", ['order'=> $item,'msg'=> lang($this->error),'date'=> $date], 3600);
  419. }
  420. }
  421. else{
  422. if(!$this->orderReback($item['business_id'], $item)){
  423. $fail++;
  424. RedisService::set($cacheKey."order_{$item['order_no']}:b{$item['business_id']}_fail", ['order'=> $item,'msg'=> lang($this->error),'date'=> $date], 3600);
  425. }else{
  426. $success++;
  427. RedisService::set($cacheKey."order_{$item['order_no']}:b{$item['business_id']}_success", ['order'=> $item,'msg'=> lang($this->error),'date'=> $date], 3600);
  428. }
  429. }
  430. });
  431. return ['success'=> $success,'fail'=> $fail];
  432. }
  433. /**
  434. * 订单取消退还处理
  435. * @param $userId
  436. * @param $orderInfo
  437. * @return bool
  438. */
  439. protected function orderReback($userId, $orderInfo){
  440. try {
  441. if($orderInfo['num']<=0){
  442. return false;
  443. }
  444. $this->model->startTrans();
  445. $updateData = ['status'=> 8, 'update_time'=> time(),'catch_at'=>time(),'exception_remark'=>'系统取消'];
  446. if(!$this->model->where(['id'=> $orderInfo['id']])->update($updateData)){
  447. $this->model->rollBack();
  448. $this->error = '3043';
  449. return false;
  450. }
  451. $info = $this->memberModel->where(['id' => $userId, 'status' => 1, 'mark' => 1])->select(['id', 'username', 'usdt_num', 'user_type'])->first();
  452. if (empty($info)) {
  453. $this->model->rollBack();
  454. $this->error = '3019';
  455. return false;
  456. }
  457. // 退还币给客户
  458. if (!$this->memberModel->where(['id' => $userId, 'mark' => 1])->increment('usdt_num', $orderInfo['num'])) {
  459. $this->model->rollBack();
  460. $this->error = '3019';
  461. return false;
  462. }
  463. // 明细处理
  464. $data = [
  465. 'order_no' => $orderInfo['order_no'],
  466. 'user_id' => $userId,
  467. 'type' => 3,
  468. 'pay_type' => 1,
  469. 'trade_type' => 2,
  470. 'change_type' => 1,
  471. 'num' => $orderInfo['num'],
  472. 'total' => $orderInfo['total'],
  473. 'balance' => floatval($info['usdt_num'] + $orderInfo['num']),
  474. 'create_time' => time(),
  475. 'update_time' => time(),
  476. 'remark' => '系统自动取消退还',
  477. 'status' => 1,
  478. 'mark' => 1,
  479. ];
  480. if (!$this->capitalModel->edit($data)) {
  481. $this->error = '3014';
  482. $this->model->rollBack();
  483. return false;
  484. }
  485. $this->model->commit();
  486. $this->error = '3044';
  487. return true;
  488. } catch (\Exception $exception){
  489. $this->error = $exception->getMessage();
  490. return false;
  491. }
  492. }
  493. }