AccountService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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\Api;
  12. use App\Models\AccountLogModel;
  13. use App\Models\BalanceLogModel;
  14. use App\Models\MemberModel;
  15. use App\Models\PayMealsModel;
  16. use App\Models\PayOrdersModel;
  17. use App\Services\BaseService;
  18. use App\Services\ConfigService;
  19. use App\Services\PaymentService;
  20. use App\Services\RedisService;
  21. use Illuminate\Support\Facades\DB;
  22. /**
  23. * 交易管理-服务类
  24. * @author laravel开发员
  25. * @since 2020/11/11
  26. * Class AccountService
  27. */
  28. class AccountService extends BaseService
  29. {
  30. public static $instance = null;
  31. /**
  32. * 构造函数
  33. * @author laravel开发员
  34. * @since 2020/11/11
  35. * AccountService constructor.
  36. */
  37. public function __construct()
  38. {
  39. $this->model = new AccountLogModel();
  40. }
  41. /**
  42. * 静态入口
  43. * @return static|null
  44. */
  45. public static function make()
  46. {
  47. if (!self::$instance) {
  48. self::$instance = (new static());
  49. }
  50. return self::$instance;
  51. }
  52. /**
  53. * @param $params
  54. * @param int $pageSize
  55. * @return array
  56. */
  57. public function getDataList($params, $pageSize = 15)
  58. {
  59. $query = $this->getQuery($params);
  60. $list = $query->select(['a.*'])
  61. ->orderBy('a.create_time','desc')
  62. ->orderBy('a.id','desc')
  63. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  64. $list = $list? $list->toArray() :[];
  65. if($list){
  66. $accountTypes = config('payment.accountTypes');
  67. foreach($list['data'] as &$item){
  68. $item['create_time'] = $item['create_time']? datetime($item['create_time'],'Y-m-d H:i:s') : '';
  69. $item['time_text'] = $item['create_time']? dateFormat($item['create_time'],'Y年m月d日') : '';
  70. $type = isset($item['type'])? intval($item['type']) : 0;
  71. $item['type_text'] = isset($item['remark'])? trim($item['remark']) : '';
  72. if(empty($item['type_text'])){
  73. $item['type_text'] = isset($accountTypes[$type])? $accountTypes[$type] : '收支明细';
  74. }
  75. $item['change_type'] = 1;
  76. if(in_array($type,[1,2,4])){
  77. $item['change_type'] = 2;
  78. }
  79. }
  80. }
  81. $userd = isset($params['user_id'])?$params['user_id']:0;
  82. return [
  83. 'pageSize'=> $pageSize,
  84. 'count'=> $this->getReceiveCount($userd),
  85. 'total'=>isset($list['total'])? $list['total'] : 0,
  86. 'list'=> isset($list['data'])? $list['data'] : []
  87. ];
  88. }
  89. /**
  90. * @param $userId
  91. * @return array|mixed
  92. */
  93. public function getReceiveCount($userId)
  94. {
  95. $cacheKey = "caches:accounts:receive_{$userId}";
  96. $data = RedisService::get($cacheKey);
  97. if($data){
  98. return $data;
  99. }
  100. $data = BalanceLogModel::where(['user_id'=>$userId,'type'=>2,'mark'=>1])->where(function($query){
  101. $query->whereNull('complete_at');
  102. })->count('id');
  103. RedisService::set($cacheKey, $data, rand(10,20));
  104. return $data;
  105. }
  106. /**
  107. * 充值记录
  108. * @param $params
  109. * @param int $pageSize
  110. * @return array
  111. */
  112. public function getPayLog($params, $pageSize = 15)
  113. {
  114. $userId = isset($params['user_id'])?$params['user_id'] : 0;
  115. $type = isset($params['type'])?$params['type'] : 0;
  116. $where = ['type'=>$type,'user_id'=> $userId,'mark'=>1];
  117. if($type<=0){
  118. unset($where['type']);
  119. }
  120. $list = PayOrdersModel::from('pay_orders as a')
  121. ->where(function($query){
  122. $query->where('a.status','>',1)->orWhere(function($query){
  123. $query->where('a.status',1)->orWhere('a.create_time','>=', time() - 300);
  124. });
  125. })
  126. ->where($where)
  127. ->select(['a.*'])
  128. ->orderBy('a.create_time','desc')
  129. ->orderBy('a.id','desc')
  130. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  131. $list = $list? $list->toArray() :[];
  132. if($list){
  133. $types = [1=>'话费充值',2=>'电费充值',3=>'燃气充值'];
  134. $statusArr = [1=>'取消支付',2=>'已支付',3=>'充值中',4=>'充值成功',5=>'充值失败资金原路退回',6=>'充值成功部分其他原路退回'];
  135. foreach($list['data'] as &$item){
  136. $item['time_text'] = $item['create_time']? datetime($item['create_time'],'Y/m/d H:i:s') : '';
  137. $type = isset($item['type'])? intval($item['type']) : 0;
  138. $status = isset($item['status'])? intval($item['status']) : 0;
  139. $item['type_text'] = isset($types[$type])? $types[$type] : '充值';
  140. $item['status_text'] = isset($statusArr[$status])? $statusArr[$status] : '充值中';
  141. if($status != 4 && $item['failed_remark']){
  142. $item['status_text'] = $item['failed_remark'];
  143. }
  144. }
  145. }
  146. return [
  147. 'pageSize'=> $pageSize,
  148. 'total'=>isset($list['total'])? $list['total'] : 0,
  149. 'list'=> isset($list['data'])? $list['data'] : []
  150. ];
  151. }
  152. /**
  153. * 充值订单详情
  154. * @param $no
  155. */
  156. public function getPayOrderInfo($no)
  157. {
  158. $where = ['a.order_no'=>$no, 'a.mark' => 1];
  159. $statusArr = [1 => '待支付', 2 => '已付款', 3 => '充值中', 4 => '充值成功',5=>'充值失败',6=>'部分成功'];
  160. $info = PayOrdersModel::from('pay_orders as a')
  161. ->with(['meal'])
  162. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  163. ->where($where)
  164. ->select(['a.*'])
  165. ->first();
  166. if ($info) {
  167. $info = $info->toArray();
  168. $info['store'] = [
  169. 'name'=> ConfigService::make()->getConfigByCode('app_name'),
  170. 'logo'=> get_image_url(ConfigService::make()->getConfigByCode('app_logo'))
  171. ];
  172. $info['meal']['goods_name'] = ['','话费充值','电费充值','燃气充值'][$info['meal']['type']];
  173. $info['meal']['sku_type'] = 1;
  174. $info['meal']['unit'] = '次';
  175. $info['meal']['num'] = 1;
  176. $info['meal']['price'] = $info['pay_total'];
  177. $info['meal']['total'] = $info['pay_total'];
  178. $info['meal']['thumb'] = get_image_url('/images/goods/goods.jpeg');
  179. $info['order_goods'] = [$info['meal']];
  180. unset($info['meal']);
  181. $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
  182. $info['pay_at'] = $info['pay_at'] ? datetime(strtotime($info['pay_at']), 'Y-m-d H:i:s') : '未支付';
  183. $status = isset($info['status']) ? $info['status'] : 0;
  184. $info['delivery_company'] = '卡密';
  185. $info['status_text'] = '待支付';
  186. if ($status) {
  187. $info['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
  188. }
  189. }
  190. return $info;
  191. }
  192. public function getQuery($params)
  193. {
  194. $where = ['a.mark' => 1];
  195. $type = isset($params['type'])? $params['type'] : 0;
  196. if($type>0){
  197. $where['a.type'] = $type;
  198. }
  199. return $this->model->with(['member','withdraw'])
  200. ->from("account_logs as a")
  201. ->leftJoin('member as b','b.id','=','a.user_id')
  202. ->where($where)
  203. ->where(function ($query) use($params) {
  204. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  205. $userId = isset($params['user_id'])? $params['user_id'] : 0;
  206. if($userId){
  207. $query->where('a.user_id',$userId);
  208. }
  209. $status = isset($params['status'])? $params['status'] : 0;
  210. if($status){
  211. $query->where('a.status',$status);
  212. }else{
  213. $query->whereNotIn('a.status',[2]);
  214. }
  215. if ($keyword) {
  216. $query->where(function($query) use($keyword){
  217. $query->where('b.nickname','like',"%{$keyword}%")
  218. ->orWhere('b.mobile','like',"%{$keyword}%")
  219. ->orWhere('b.realname','like',"%{$keyword}%");
  220. });
  221. }
  222. $orderNo = isset($params['order_no'])? trim($params['order_no']) : '';
  223. if($orderNo){
  224. $query->where(function($query) use($orderNo){
  225. $query->where('a.source_order_no','like',"%{$orderNo}%");
  226. });
  227. }
  228. })
  229. ->where(function ($query) use($params){
  230. // 日期
  231. $date = isset($params['date']) ? $params['date'] : [];
  232. $start = isset($date[0])? $date[0] : '';
  233. $end = isset($date[1])? $date[1] : '';
  234. $end = $start>=$end? '' : $end;
  235. if ($start) {
  236. $query->where('a.create_time','>=', strtotime($start));
  237. }
  238. if($end){
  239. $query->where('a.create_time','<=', strtotime($end));
  240. }
  241. });
  242. }
  243. /**
  244. * 今日金额统计数据
  245. * @param $userId
  246. * @param int $type
  247. * @return array|mixed
  248. */
  249. public function getTotalByDay($userId, $type=1)
  250. {
  251. $cacheKey = "caches:accounts:total_{$userId}_{$type}";
  252. $data = RedisService::get($cacheKey);
  253. if($data){
  254. return $data;
  255. }
  256. $data = $this->model->where(['user_id'=> $userId,'type'=>$type,'status'=>1,'mark'=>1])
  257. ->where('create_time','>=', strtotime(date('Y-m-d')))
  258. ->sum('money');
  259. if($data){
  260. RedisService::set($cacheKey, $data, rand(5,10));
  261. }
  262. return $data;
  263. }
  264. /**
  265. * 充值套餐
  266. * @param $type
  267. * @return array|mixed
  268. */
  269. public function getPayMealList($params)
  270. {
  271. $type = isset($params['type'])?$params['type'] : 0;
  272. $gasType = isset($params['gas_type'])?$params['gas_type'] : 0;
  273. $phoneService = isset($params['phone_service'])?$params['phone_service'] : 0;
  274. $phoneType = isset($params['phone_type'])?$params['phone_type'] : 0;
  275. $electricType = isset($params['electric_type'])?$params['electric_type'] : 0;
  276. $cacheKey = "caches:accounts:mealList_{$type}:".md5(json_encode($params));
  277. $datas = RedisService::get($cacheKey);
  278. if($datas){
  279. return $datas;
  280. }
  281. $where = ['type'=>$type,'status'=>1,'mark'=>1];
  282. if($type==1){
  283. if($phoneType){
  284. $where['phone_type'] = $phoneType;
  285. }
  286. }else if($type==2){
  287. if($electricType){
  288. $where['electric_type'] = $electricType;
  289. }
  290. }else if($type==3){
  291. if($gasType){
  292. $where['gas_type'] = $gasType;
  293. }
  294. }
  295. $datas = PayMealsModel::where($where)
  296. ->where(function($query) use($phoneService, $type){
  297. if($type==1 && $phoneService){
  298. $query->where('phone_service',$phoneService)->orWhere('phone_service',0);
  299. }
  300. })
  301. ->orderBy('sort','desc')
  302. ->orderBy('id','asc')
  303. ->get();
  304. $datas = $datas? $datas->toArray() :[];
  305. if($datas){
  306. RedisService::set($cacheKey, $datas, rand(300,600));
  307. }
  308. return $datas;
  309. }
  310. /**
  311. * 生活充值
  312. * @param $userId 用户ID
  313. * @param $params
  314. * @return array|false
  315. */
  316. public function recharge($userId, $params)
  317. {
  318. $mealId = isset($params['id']) ? $params['id'] : 0; // 套餐ID
  319. $account = isset($params['account']) ? $params['account'] : ''; // 充值账号/手机号
  320. $electricType = isset($params['electric_type']) ? intval($params['electric_type']) : 0; // 电费充值类型
  321. $ytype = isset($params['ytype']) ? intval($params['ytype']) : 1; // 电费充值:三要素验证,1-身份证后6位,2-银行卡后六位,3-营业执照后六位
  322. $area = isset($params['area']) ? trim($params['area']) : ''; // 电费充值:省份/直辖市
  323. $idCardNo = isset($params['id_card_no']) ? trim($params['id_card_no']) : ''; // 电费充值:三要素验证,身份证后6位/银行卡后6位/营业执照后6位
  324. $city = isset($params['city']) ? trim($params['city']) : ''; // 电费充值:地级市名
  325. $cacheKey = "caches:members:pay:{$userId}_{$mealId}";
  326. if (RedisService::get($cacheKey . '_lock')) {
  327. $this->error = '请不要频繁提交~';
  328. return false;
  329. }
  330. if(empty($account)){
  331. $this->error = '请输入充值账号';
  332. return false;
  333. }
  334. RedisService::set($cacheKey, ['date' => date('Y-m-d H:i:s')], rand(2, 3));
  335. $mealInfo = PayMealsModel::where(['id' => $mealId, 'status' => 1, 'mark' => 1])
  336. ->select(['id','product_id','gift', 'money', 'type', 'discount', 'remark', 'status'])
  337. ->first();
  338. $money = isset($mealInfo['money']) ? floatval($mealInfo['money']) : 0;
  339. $discount = isset($mealInfo['discount']) ? intval($mealInfo['discount']) : 0;
  340. $mealType = isset($mealInfo['type']) && $mealInfo['type'] ? intval($mealInfo['type']) : 1;
  341. $productId = isset($mealInfo['product_id']) ? $mealInfo['product_id'] : 0;
  342. $gift = isset($mealInfo['gift']) ? $mealInfo['gift'] : '';
  343. $price = $discount?moneyFormat($money*$discount/100,2): $money;
  344. if (empty($mealInfo)) {
  345. $this->error = '该套餐不存在';
  346. RedisService::clear($cacheKey . '_lock');
  347. return false;
  348. }
  349. if ($price <= 0 || $money <= 0 || $productId<=0) {
  350. $this->error = '该套餐参数错误';
  351. RedisService::clear($cacheKey . '_lock');
  352. return false;
  353. }
  354. if($mealType==2 && empty($area)){
  355. $this->error = '请选择省份/直辖市';
  356. RedisService::clear($cacheKey . '_lock');
  357. return false;
  358. }
  359. if($mealType==2 && empty($city)){
  360. $this->error = '请选择地级市名';
  361. RedisService::clear($cacheKey . '_lock');
  362. return false;
  363. }
  364. // 电费验证
  365. if($mealType==2 && $electricType==3){
  366. if(in_array($area,['广东','广西','海南','贵州','云南'])){
  367. if($ytype<=0){
  368. $this->error = '请选择三要素验证类型';
  369. RedisService::clear($cacheKey . '_lock');
  370. return false;
  371. }
  372. if(empty($idCardNo)){
  373. $this->error = "请填写".(['验证参数','身份证后6位','银行卡后6位','营业执照后6位'][$ytype]);
  374. RedisService::clear($cacheKey . '_lock');
  375. return false;
  376. }
  377. }
  378. }
  379. $system = isset($params['system']) && $params['system'] ? $params['system'] : [];
  380. $platform = isset($system['platform']) && $system['platform']? $system['platform'] : 'mp';
  381. $info = MemberModel::where(['id' => $userId, 'mark' => 1])
  382. ->select(['id', 'openid','parent_id', 'mobile', 'status'])
  383. ->first();
  384. $parentId = isset($info['parent_id']) ? $info['parent_id'] : 0;
  385. $openid = isset($info['openid']) ? $info['openid'] : '';
  386. if (!$info || $info['status'] != 1) {
  387. $this->error = 1045;
  388. RedisService::clear($cacheKey . '_lock');
  389. return false;
  390. }
  391. if (empty($openid)) {
  392. $this->error = '用户参数错误,请重新授权登录后尝试~';
  393. RedisService::clear($cacheKey . '_lock');
  394. return false;
  395. }
  396. // 推荐消费者的佣金
  397. $agentDirectBonusRate = ConfigService::make()->getConfigByCode('agent_direct_bonus_rate', 0);
  398. $agentDirectBonusRate = $agentDirectBonusRate>0 && $agentDirectBonusRate<100? $agentDirectBonusRate : 0;
  399. $recBonus = moneyFormat($agentDirectBonusRate * $price/100, 2);
  400. // 创建订单
  401. $orderNo = get_order_num('PR');
  402. $types = ['','话费充值','电费充值','燃气充值'];
  403. $remark = isset($types[$mealType])? $types[$mealType] : '生活充值';
  404. $order = [
  405. 'order_no' => $orderNo,
  406. 'user_id' => $userId,
  407. 'meal_id' => $mealId,
  408. 'product_id' => $productId,
  409. 'total' => $money,
  410. 'pay_total' => $price,
  411. 'type' => $mealType,
  412. 'account' => $account,
  413. 'discount' => $discount,
  414. 'area' => $area,
  415. 'city' => $city,
  416. 'ytype' => $ytype,
  417. 'rec_bonus_id' => $parentId,
  418. 'rec_bonus_rate' => $agentDirectBonusRate,
  419. 'rec_bonus' => $recBonus,
  420. 'bonus_settle' => 2,
  421. 'id_card_no' => $idCardNo,
  422. 'create_time' => time(),
  423. 'gift' => $gift,
  424. 'remark' => $remark,
  425. 'status' => 1,
  426. 'mark' => 1
  427. ];
  428. DB::beginTransaction();
  429. if (!$orderId = PayOrdersModel::insertGetId($order)) {
  430. $this->error = '创建充值订单失败';
  431. return false;
  432. }
  433. if(env('PAY_DEBUG')){
  434. $price = 0.1;
  435. }
  436. /* TODO 支付处理 */
  437. $payOrder = [
  438. 'type' => 1,
  439. 'order_no' => $orderNo,
  440. 'pay_money' => $price,
  441. 'body' => $remark,
  442. 'openid' => $openid
  443. ];
  444. // 调起支付
  445. // 调起支付
  446. if($platform == 'wechat'){
  447. $payment = PaymentService::make()->mpPay($info, $payOrder, 'pay');
  448. }else{
  449. $payment = PaymentService::make()->minPay($info, $payOrder, 'pay');
  450. }
  451. if (empty($payment)) {
  452. DB::rollBack();
  453. RedisService::clear($cacheKey . '_lock');
  454. $this->error = PaymentService::make()->getError();
  455. return false;
  456. }
  457. // 用户操作记录
  458. DB::commit();
  459. $this->error = '创建充值订单成功,请前往支付~';
  460. // 删除超时订单
  461. PayOrdersModel::where(['status'=>1])->where('create_time','<=', time() - 6 * 3600)->delete();
  462. RedisService::clear($cacheKey . '_lock');
  463. return [
  464. 'order_id' => $orderId,
  465. 'payment' => $payment,
  466. 'total' => $payOrder['pay_money'],
  467. 'pay_type' => 10,
  468. ];
  469. }
  470. /**
  471. * 收款确认
  472. * @param $userId
  473. * @param $params
  474. * @return bool
  475. */
  476. public function confirm($userId,$params)
  477. {
  478. RedisService::set("caches:rrr:{$userId}", $params, 500);
  479. $logId = isset($params['id']) ? $params['id'] : 0; // 提现记录ID
  480. $status = isset($params['status']) ? $params['status'] : 1; // 提现记录ID
  481. $info = BalanceLogModel::where(['id'=>$logId,'mark'=>1])->first();
  482. if(empty($info)){
  483. $this->error = '提现记录不存在~';
  484. return false;
  485. }
  486. $info->receive_status = $status;
  487. $info->receive_at = date('Y-m-d H:i:s');
  488. $info->update_time = time();
  489. $info->save();
  490. $this->error = '提现收款成功';
  491. return true;
  492. }
  493. }