AccountService.php 12 KB

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