AccountService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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\PaymentService;
  18. use App\Services\RedisService;
  19. use Illuminate\Support\Facades\DB;
  20. use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
  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. $list = PayOrdersModel::from('pay_orders as a')
  96. ->where(function($query){
  97. $query->where('a.status','>',1)->orWhere(function($query){
  98. $query->where('a.status',1)->orWhere('a.create_time','>=', time() - 300);
  99. });
  100. })
  101. ->where(['user_id'=> $userId,'mark'=>1])
  102. ->select(['a.*'])
  103. ->orderBy('a.create_time','desc')
  104. ->orderBy('a.id','desc')
  105. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  106. $list = $list? $list->toArray() :[];
  107. if($list){
  108. $types = [1=>'话费充值',2=>'电费充值',3=>'燃气充值'];
  109. $statusArr = [1=>'取消支付',2=>'已支付',3=>'充值中',4=>'充值成功',5=>'充值失败资金原路退回',6=>'充值成功部分其他原路退回'];
  110. foreach($list['data'] as &$item){
  111. $item['time_text'] = $item['create_time']? datetime($item['create_time'],'Y/m/d H:i:s') : '';
  112. $type = isset($item['type'])? intval($item['type']) : 0;
  113. $status = isset($item['status'])? intval($item['status']) : 0;
  114. $item['type_text'] = isset($types[$type])? $types[$type] : '充值';
  115. $item['status_text'] = isset($statusArr[$status])? $statusArr[$status] : '充值中';
  116. if($status != 4 && $item['failed_remark']){
  117. $item['status_text'] = $item['failed_remark'];
  118. }
  119. }
  120. }
  121. return [
  122. 'pageSize'=> $pageSize,
  123. 'total'=>isset($list['total'])? $list['total'] : 0,
  124. 'list'=> isset($list['data'])? $list['data'] : []
  125. ];
  126. }
  127. public function getQuery($params)
  128. {
  129. $where = ['a.mark' => 1];
  130. $type = isset($params['type'])? $params['type'] : 0;
  131. if($type>0){
  132. $where['a.type'] = $type;
  133. }
  134. return $this->model->with(['member'])->from("account_logs as a")
  135. ->leftJoin('member as b','b.id','=','a.user_id')
  136. ->where($where)
  137. ->where(function ($query) use($params) {
  138. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  139. $userId = isset($params['user_id'])? $params['user_id'] : 0;
  140. if($userId){
  141. $query->where('a.user_id',$userId);
  142. }
  143. $status = isset($params['status'])? $params['status'] : 0;
  144. if($status){
  145. $query->where('a.status',$status);
  146. }else{
  147. $query->whereNotIn('a.status',[2]);
  148. }
  149. if ($keyword) {
  150. $query->where(function($query) use($keyword){
  151. $query->where('b.nickname','like',"%{$keyword}%")
  152. ->orWhere('b.mobile','like',"%{$keyword}%")
  153. ->orWhere('b.realname','like',"%{$keyword}%");
  154. });
  155. }
  156. $orderNo = isset($params['order_no'])? trim($params['order_no']) : '';
  157. if($orderNo){
  158. $query->where(function($query) use($orderNo){
  159. $query->where('a.source_order_no','like',"%{$orderNo}%");
  160. });
  161. }
  162. })
  163. ->where(function ($query) use($params){
  164. // 日期
  165. $date = isset($params['date']) ? $params['date'] : [];
  166. $start = isset($date[0])? $date[0] : '';
  167. $end = isset($date[1])? $date[1] : '';
  168. $end = $start>=$end? '' : $end;
  169. if ($start) {
  170. $query->where('a.create_time','>=', strtotime($start));
  171. }
  172. if($end){
  173. $query->where('a.create_time','<=', strtotime($end));
  174. }
  175. });
  176. }
  177. /**
  178. * 今日金额统计数据
  179. * @param $userId
  180. * @param int $type
  181. * @return array|mixed
  182. */
  183. public function getTotalByDay($userId, $type=1)
  184. {
  185. $cacheKey = "caches:accounts:total_{$userId}_{$type}";
  186. $data = RedisService::get($cacheKey);
  187. if($data){
  188. return $data;
  189. }
  190. $data = $this->model->where(['user_id'=> $userId,'type'=>$type,'status'=>1,'mark'=>1])
  191. ->where('create_time','>=', strtotime(date('Y-m-d')))
  192. ->sum('money');
  193. if($data){
  194. RedisService::set($cacheKey, $data, rand(5,10));
  195. }
  196. return $data;
  197. }
  198. /**
  199. * 充值套餐
  200. * @param $type
  201. * @return array|mixed
  202. */
  203. public function getPayMealList($type)
  204. {
  205. $cacheKey = "caches:accounts:mealList_{$type}";
  206. $datas = RedisService::get($cacheKey);
  207. if($datas){
  208. return $datas;
  209. }
  210. $datas = PayMealsModel::where(['type'=>$type,'status'=>1,'mark'=>1])
  211. ->orderBy('sort','desc')
  212. ->orderBy('id','asc')
  213. ->get();
  214. $datas = $datas? $datas->toArray() :[];
  215. if($datas){
  216. RedisService::set($cacheKey, $datas, rand(300,600));
  217. }
  218. return $datas;
  219. }
  220. /**
  221. * 生活充值
  222. * @param $userId 用户ID
  223. * @param $params
  224. * @return array|false
  225. */
  226. public function recharge($userId, $params)
  227. {
  228. $mealId = isset($params['id']) ? $params['id'] : 0; // 套餐ID
  229. $account = isset($params['account']) ? $params['account'] : ''; // 充值账号/手机号
  230. $cacheKey = "caches:members:pay:{$userId}_{$mealId}";
  231. if (RedisService::get($cacheKey . '_lock')) {
  232. $this->error = '请不要频繁提交~';
  233. return false;
  234. }
  235. if(empty($account)){
  236. $this->error = '请输入充值账号';
  237. return false;
  238. }
  239. RedisService::set($cacheKey, ['date' => date('Y-m-d H:i:s')], rand(2, 3));
  240. $mealInfo = PayMealsModel::where(['id' => $mealId, 'status' => 1, 'mark' => 1])
  241. ->select(['id','product_id', 'money', 'type', 'discount', 'remark', 'status'])
  242. ->first();
  243. $money = isset($mealInfo['money']) ? floatval($mealInfo['money']) : 0;
  244. $discount = isset($mealInfo['discount']) ? intval($mealInfo['discount']) : 0;
  245. $mealType = isset($mealInfo['type']) && $mealInfo['type'] ? intval($mealInfo['type']) : 1;
  246. $productId= isset($mealInfo['product_id']) ? $mealInfo['product_id'] : 0;
  247. $remark= isset($mealInfo['remark']) ? $mealInfo['remark'] : '';
  248. $price = $discount?moneyFormat($money*$discount/100,2): $money;
  249. if (empty($mealInfo)) {
  250. $this->error = '该套餐不存在';
  251. RedisService::clear($cacheKey . '_lock');
  252. return false;
  253. }
  254. if ($price <= 0 || $money <= 0 || $productId<=0) {
  255. $this->error = '该套餐参数错误';
  256. RedisService::clear($cacheKey . '_lock');
  257. return false;
  258. }
  259. $info = MemberModel::where(['id' => $userId, 'mark' => 1])
  260. ->select(['id', 'openid', 'mobile', 'status'])
  261. ->first();
  262. $openid = isset($info['openid']) ? $info['openid'] : '';
  263. if (!$info || $info['status'] != 1) {
  264. $this->error = 1045;
  265. RedisService::clear($cacheKey . '_lock');
  266. return false;
  267. }
  268. if (empty($openid)) {
  269. $this->error = '用户参数错误,请重新授权登录后尝试~';
  270. RedisService::clear($cacheKey . '_lock');
  271. return false;
  272. }
  273. // 创建订单
  274. $orderNo = get_order_num('PR');
  275. $types = ['','话费充值','电费充值','燃气充值'];
  276. $remark = isset($types[$mealType])? $types[$mealType] : '生活充值';
  277. $order = [
  278. 'order_no' => $orderNo,
  279. 'user_id' => $userId,
  280. 'meal_id' => $mealId,
  281. 'product_id' => $productId,
  282. 'total' => $price,
  283. 'type' => $mealType,
  284. 'account' => $account,
  285. 'discount' => $discount,
  286. 'create_time' => time(),
  287. 'remark' => $remark,
  288. 'status' => 1,
  289. 'mark' => 1
  290. ];
  291. DB::beginTransaction();
  292. if (!$orderId = PayOrdersModel::insertGetId($order)) {
  293. $this->error = '创建充值订单失败';
  294. return false;
  295. }
  296. /* TODO 支付处理 */
  297. $payOrder = [
  298. 'type' => 1,
  299. 'order_no' => $orderNo,
  300. 'pay_money' => $price,
  301. 'body' => $remark,
  302. 'openid' => $openid
  303. ];
  304. // 调起支付
  305. $payment = PaymentService::make()->minPay($info, $payOrder, 'pay');
  306. if (empty($payment)) {
  307. DB::rollBack();
  308. RedisService::clear($cacheKey . '_lock');
  309. $this->error = PaymentService::make()->getError();
  310. return false;
  311. }
  312. // 用户操作记录
  313. DB::commit();
  314. $this->error = '创建充值订单成功,请前往支付~';
  315. // 删除超时订单
  316. PayOrdersModel::where(['status'=>1])->where('create_time','<=', time() - 6 * 3600)->delete();
  317. RedisService::clear($cacheKey . '_lock');
  318. return [
  319. 'order_id' => $orderId,
  320. 'payment' => $payment,
  321. 'total' => $payOrder['pay_money'],
  322. 'pay_type' => 10,
  323. ];
  324. }
  325. }