AccountService.php 18 KB

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