AccountService.php 19 KB

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