AccountService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. /**
  21. * 交易管理-服务类
  22. * @author laravel开发员
  23. * @since 2020/11/11
  24. * Class AccountService
  25. */
  26. class AccountService extends BaseService
  27. {
  28. public static $instance = null;
  29. /**
  30. * 构造函数
  31. * @author laravel开发员
  32. * @since 2020/11/11
  33. * AccountService constructor.
  34. */
  35. public function __construct()
  36. {
  37. $this->model = new AccountLogModel();
  38. }
  39. /**
  40. * 静态入口
  41. * @return static|null
  42. */
  43. public static function make()
  44. {
  45. if (!self::$instance) {
  46. self::$instance = (new static());
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * @param $params
  52. * @param int $pageSize
  53. * @return array
  54. */
  55. public function getDataList($params, $pageSize = 15)
  56. {
  57. $query = $this->getQuery($params);
  58. $list = $query->select(['a.*'])
  59. ->orderBy('a.create_time','desc')
  60. ->orderBy('a.id','desc')
  61. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  62. $list = $list? $list->toArray() :[];
  63. if($list){
  64. $accountTypes = config('payment.accountTypes');
  65. foreach($list['data'] as &$item){
  66. $item['create_time'] = $item['create_time']? datetime($item['create_time'],'Y-m-d H:i:s') : '';
  67. $item['time_text'] = $item['create_time']? dateFormat($item['create_time'],'Y年m月d日') : '';
  68. $type = isset($item['type'])? intval($item['type']) : 0;
  69. $item['type_text'] = isset($item['remark'])? trim($item['remark']) : '';
  70. if(empty($item['type_text'])){
  71. $item['type_text'] = isset($accountTypes[$type])? $accountTypes[$type] : '收支明细';
  72. }
  73. $item['change_type'] = 1;
  74. if(in_array($type,[1,2,4])){
  75. $item['change_type'] = 2;
  76. }
  77. }
  78. }
  79. return [
  80. 'pageSize'=> $pageSize,
  81. 'total'=>isset($list['total'])? $list['total'] : 0,
  82. 'list'=> isset($list['data'])? $list['data'] : []
  83. ];
  84. }
  85. /**
  86. * 充值记录
  87. * @param $params
  88. * @param int $pageSize
  89. * @return array
  90. */
  91. public function getPayLog($params, $pageSize = 15)
  92. {
  93. $userId = isset($params['user_id'])?$params['user_id'] : 0;
  94. $list = PayOrdersModel::from('pay_orders as a')
  95. ->where(function($query){
  96. $query->where('a.status','>',1)->orWhere(function($query){
  97. $query->where('a.status',1)->orWhere('a.create_time','>=', time() - 300);
  98. });
  99. })
  100. ->where(['user_id'=> $userId,'mark'=>1])
  101. ->select(['a.*'])
  102. ->orderBy('a.create_time','desc')
  103. ->orderBy('a.id','desc')
  104. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  105. $list = $list? $list->toArray() :[];
  106. if($list){
  107. $types = [1=>'话费充值',2=>'电费充值',3=>'燃气充值'];
  108. $statusArr = [1=>'取消支付',2=>'已支付',3=>'充值中',4=>'充值成功',5=>'充值失败资金原路退回',6=>'充值成功部分其他原路退回'];
  109. foreach($list['data'] as &$item){
  110. $item['time_text'] = $item['create_time']? datetime($item['create_time'],'Y/m/d H:i:s') : '';
  111. $type = isset($item['type'])? intval($item['type']) : 0;
  112. $status = isset($item['status'])? intval($item['status']) : 0;
  113. $item['type_text'] = isset($types[$type])? $types[$type] : '充值';
  114. $item['status_text'] = isset($statusArr[$status])? $statusArr[$status] : '充值中';
  115. if($status != 4 && $item['failed_remark']){
  116. $item['status_text'] = $item['failed_remark'];
  117. }
  118. }
  119. }
  120. return [
  121. 'pageSize'=> $pageSize,
  122. 'total'=>isset($list['total'])? $list['total'] : 0,
  123. 'list'=> isset($list['data'])? $list['data'] : []
  124. ];
  125. }
  126. public function getQuery($params)
  127. {
  128. $where = ['a.mark' => 1];
  129. $type = isset($params['type'])? $params['type'] : 0;
  130. if($type>0){
  131. $where['a.type'] = $type;
  132. }
  133. return $this->model->with(['member'])->from("account_logs as a")
  134. ->leftJoin('member as b','b.id','=','a.user_id')
  135. ->where($where)
  136. ->where(function ($query) use($params) {
  137. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  138. $userId = isset($params['user_id'])? $params['user_id'] : 0;
  139. if($userId){
  140. $query->where('a.user_id',$userId);
  141. }
  142. $status = isset($params['status'])? $params['status'] : 0;
  143. if($status){
  144. $query->where('a.status',$status);
  145. }else{
  146. $query->whereNotIn('a.status',[2]);
  147. }
  148. if ($keyword) {
  149. $query->where(function($query) use($keyword){
  150. $query->where('b.nickname','like',"%{$keyword}%")
  151. ->orWhere('b.mobile','like',"%{$keyword}%")
  152. ->orWhere('b.realname','like',"%{$keyword}%");
  153. });
  154. }
  155. $orderNo = isset($params['order_no'])? trim($params['order_no']) : '';
  156. if($orderNo){
  157. $query->where(function($query) use($orderNo){
  158. $query->where('a.source_order_no','like',"%{$orderNo}%");
  159. });
  160. }
  161. })
  162. ->where(function ($query) use($params){
  163. // 日期
  164. $date = isset($params['date']) ? $params['date'] : [];
  165. $start = isset($date[0])? $date[0] : '';
  166. $end = isset($date[1])? $date[1] : '';
  167. $end = $start>=$end? '' : $end;
  168. if ($start) {
  169. $query->where('a.create_time','>=', strtotime($start));
  170. }
  171. if($end){
  172. $query->where('a.create_time','<=', strtotime($end));
  173. }
  174. });
  175. }
  176. /**
  177. * 今日金额统计数据
  178. * @param $userId
  179. * @param int $type
  180. * @return array|mixed
  181. */
  182. public function getTotalByDay($userId, $type=1)
  183. {
  184. $cacheKey = "caches:accounts:total_{$userId}_{$type}";
  185. $data = RedisService::get($cacheKey);
  186. if($data){
  187. return $data;
  188. }
  189. $data = $this->model->where(['user_id'=> $userId,'type'=>$type,'status'=>1,'mark'=>1])
  190. ->where('create_time','>=', strtotime(date('Y-m-d')))
  191. ->sum('money');
  192. if($data){
  193. RedisService::set($cacheKey, $data, rand(5,10));
  194. }
  195. return $data;
  196. }
  197. /**
  198. * 充值套餐
  199. * @param $type
  200. * @return array|mixed
  201. */
  202. public function getPayMealList($type)
  203. {
  204. $cacheKey = "caches:accounts:mealList_{$type}";
  205. $datas = RedisService::get($cacheKey);
  206. if($datas){
  207. return $datas;
  208. }
  209. $datas = PayMealsModel::where(['type'=>$type,'status'=>1,'mark'=>1])
  210. ->orderBy('sort','desc')
  211. ->orderBy('id','asc')
  212. ->get();
  213. $datas = $datas? $datas->toArray() :[];
  214. if($datas){
  215. RedisService::set($cacheKey, $datas, rand(300,600));
  216. }
  217. return $datas;
  218. }
  219. /**
  220. * 生活充值
  221. * @param $userId 用户ID
  222. * @param $params
  223. * @return array|false
  224. */
  225. public function recharge($userId, $params)
  226. {
  227. $mealId = isset($params['id']) ? $params['id'] : 0; // 套餐ID
  228. $account = isset($params['account']) ? $params['account'] : ''; // 充值账号/手机号
  229. $cacheKey = "caches:members:pay:{$userId}_{$mealId}";
  230. if (RedisService::get($cacheKey . '_lock')) {
  231. $this->error = '请不要频繁提交~';
  232. return false;
  233. }
  234. if(empty($account)){
  235. $this->error = '请输入充值账号';
  236. return false;
  237. }
  238. RedisService::set($cacheKey, ['date' => date('Y-m-d H:i:s')], rand(2, 3));
  239. $mealInfo = PayMealsModel::where(['id' => $mealId, 'status' => 1, 'mark' => 1])
  240. ->select(['id','product_id', 'money', 'type', 'discount', 'remark', 'status'])
  241. ->first();
  242. $money = isset($mealInfo['money']) ? floatval($mealInfo['money']) : 0;
  243. $discount = isset($mealInfo['discount']) ? intval($mealInfo['discount']) : 0;
  244. $mealType = isset($mealInfo['type']) && $mealInfo['type'] ? intval($mealInfo['type']) : 1;
  245. $productId= isset($mealInfo['product_id']) ? $mealInfo['product_id'] : 0;
  246. $remark= isset($mealInfo['remark']) ? $mealInfo['remark'] : '';
  247. $price = $discount?moneyFormat($money*$discount/100,2): $money;
  248. if (empty($mealInfo)) {
  249. $this->error = '该套餐不存在';
  250. RedisService::clear($cacheKey . '_lock');
  251. return false;
  252. }
  253. if ($price <= 0 || $money <= 0 || $productId<=0) {
  254. $this->error = '该套餐参数错误';
  255. RedisService::clear($cacheKey . '_lock');
  256. return false;
  257. }
  258. $info = MemberModel::where(['id' => $userId, 'mark' => 1])
  259. ->select(['id', 'openid', 'mobile', 'status'])
  260. ->first();
  261. $openid = isset($info['openid']) ? $info['openid'] : '';
  262. if (!$info || $info['status'] != 1) {
  263. $this->error = 1045;
  264. RedisService::clear($cacheKey . '_lock');
  265. return false;
  266. }
  267. if (empty($openid)) {
  268. $this->error = '用户参数错误,请重新授权登录后尝试~';
  269. RedisService::clear($cacheKey . '_lock');
  270. return false;
  271. }
  272. // 创建订单
  273. $orderNo = get_order_num('PR');
  274. $types = ['','话费充值','电费充值','燃气充值'];
  275. $remark = isset($types[$mealType])? $types[$mealType] : '生活充值';
  276. $order = [
  277. 'order_no' => $orderNo,
  278. 'user_id' => $userId,
  279. 'meal_id' => $mealId,
  280. 'product_id' => $productId,
  281. 'total' => $price,
  282. 'type' => $mealType,
  283. 'account' => $account,
  284. 'discount' => $discount,
  285. 'create_time' => time(),
  286. 'remark' => $remark,
  287. 'status' => 1,
  288. 'mark' => 1
  289. ];
  290. DB::beginTransaction();
  291. if (!$orderId = PayOrdersModel::insertGetId($order)) {
  292. $this->error = '创建充值订单失败';
  293. return false;
  294. }
  295. /* TODO 支付处理 */
  296. $payOrder = [
  297. 'type' => 1,
  298. 'order_no' => $orderNo,
  299. 'pay_money' => $price,
  300. 'body' => $remark,
  301. 'openid' => $openid
  302. ];
  303. // 调起支付
  304. $payment = PaymentService::make()->minPay($info, $payOrder, 'pay');
  305. if (empty($payment)) {
  306. DB::rollBack();
  307. RedisService::clear($cacheKey . '_lock');
  308. $this->error = PaymentService::make()->getError();
  309. return false;
  310. }
  311. // 用户操作记录
  312. DB::commit();
  313. $this->error = '创建充值订单成功,请前往支付~';
  314. // 删除超时订单
  315. PayOrdersModel::where(['status'=>1])->where('create_time','<=', time() - 6 * 3600)->delete();
  316. RedisService::clear($cacheKey . '_lock');
  317. return [
  318. 'order_id' => $orderId,
  319. 'payment' => $payment,
  320. 'total' => $payOrder['pay_money'],
  321. 'pay_type' => 10,
  322. ];
  323. }
  324. }