| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services\Api;
- use App\Models\AccountLogModel;
- use App\Models\MemberModel;
- use App\Models\PayMealsModel;
- use App\Models\PayOrdersModel;
- use App\Services\BaseService;
- use App\Services\ConfigService;
- use App\Services\PaymentService;
- use App\Services\RedisService;
- use Illuminate\Support\Facades\DB;
- /**
- * 交易管理-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * Class AccountService
- */
- class AccountService extends BaseService
- {
- public static $instance = null;
- /**
- * 构造函数
- * @author laravel开发员
- * @since 2020/11/11
- * AccountService constructor.
- */
- public function __construct()
- {
- $this->model = new AccountLogModel();
- }
- /**
- * 静态入口
- * @return static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = (new static());
- }
- return self::$instance;
- }
- /**
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getDataList($params, $pageSize = 15)
- {
- $query = $this->getQuery($params);
- $list = $query->select(['a.*'])
- ->orderBy('a.create_time','desc')
- ->orderBy('a.id','desc')
- ->paginate($pageSize > 0 ? $pageSize : 9999999);
- $list = $list? $list->toArray() :[];
- if($list){
- $accountTypes = config('payment.accountTypes');
- foreach($list['data'] as &$item){
- $item['create_time'] = $item['create_time']? datetime($item['create_time'],'Y-m-d H:i:s') : '';
- $item['time_text'] = $item['create_time']? dateFormat($item['create_time'],'Y年m月d日') : '';
- $type = isset($item['type'])? intval($item['type']) : 0;
- $item['type_text'] = isset($item['remark'])? trim($item['remark']) : '';
- if(empty($item['type_text'])){
- $item['type_text'] = isset($accountTypes[$type])? $accountTypes[$type] : '收支明细';
- }
- $item['change_type'] = 1;
- if(in_array($type,[1,2,4])){
- $item['change_type'] = 2;
- }
- }
- }
- return [
- 'pageSize'=> $pageSize,
- 'total'=>isset($list['total'])? $list['total'] : 0,
- 'list'=> isset($list['data'])? $list['data'] : []
- ];
- }
- /**
- * 充值记录
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getPayLog($params, $pageSize = 15)
- {
- $userId = isset($params['user_id'])?$params['user_id'] : 0;
- $type = isset($params['type'])?$params['type'] : 0;
- $where = ['type'=>$type,'user_id'=> $userId,'mark'=>1];
- if($type<=0){
- unset($where['type']);
- }
- $list = PayOrdersModel::from('pay_orders as a')
- ->where(function($query){
- $query->where('a.status','>',1)->orWhere(function($query){
- $query->where('a.status',1)->orWhere('a.create_time','>=', time() - 300);
- });
- })
- ->where($where)
- ->select(['a.*'])
- ->orderBy('a.create_time','desc')
- ->orderBy('a.id','desc')
- ->paginate($pageSize > 0 ? $pageSize : 9999999);
- $list = $list? $list->toArray() :[];
- if($list){
- $types = [1=>'话费充值',2=>'电费充值',3=>'燃气充值'];
- $statusArr = [1=>'取消支付',2=>'已支付',3=>'充值中',4=>'充值成功',5=>'充值失败资金原路退回',6=>'充值成功部分其他原路退回'];
- foreach($list['data'] as &$item){
- $item['time_text'] = $item['create_time']? datetime($item['create_time'],'Y/m/d H:i:s') : '';
- $type = isset($item['type'])? intval($item['type']) : 0;
- $status = isset($item['status'])? intval($item['status']) : 0;
- $item['type_text'] = isset($types[$type])? $types[$type] : '充值';
- $item['status_text'] = isset($statusArr[$status])? $statusArr[$status] : '充值中';
- if($status != 4 && $item['failed_remark']){
- $item['status_text'] = $item['failed_remark'];
- }
- }
- }
- return [
- 'pageSize'=> $pageSize,
- 'total'=>isset($list['total'])? $list['total'] : 0,
- 'list'=> isset($list['data'])? $list['data'] : []
- ];
- }
- /**
- * 充值订单详情
- * @param $no
- */
- public function getPayOrderInfo($no)
- {
- $where = ['a.order_no'=>$no, 'a.mark' => 1];
- $statusArr = [1 => '待支付', 2 => '已付款', 3 => '充值中', 4 => '充值成功',5=>'充值失败',6=>'部分成功'];
- $info = PayOrdersModel::from('pay_orders as a')
- ->with(['meal'])
- ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
- ->where($where)
- ->select(['a.*'])
- ->first();
- if ($info) {
- $info = $info->toArray();
- $info['store'] = [
- 'name'=> ConfigService::make()->getConfigByCode('app_name'),
- 'logo'=> get_image_url(ConfigService::make()->getConfigByCode('app_logo'))
- ];
- $info['meal']['goods_name'] = ['','话费充值','电费充值','燃气充值'][$info['meal']['type']];
- $info['meal']['sku_type'] = 1;
- $info['meal']['unit'] = '次';
- $info['meal']['num'] = 1;
- $info['meal']['price'] = $info['pay_total'];
- $info['meal']['total'] = $info['pay_total'];
- $info['meal']['thumb'] = get_image_url('/images/goods/goods.jpeg');
- $info['order_goods'] = [$info['meal']];
- unset($info['meal']);
- $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d H:i:s') : '';
- $info['pay_at'] = $info['pay_at'] ? datetime(strtotime($info['pay_at']), 'Y-m-d H:i:s') : '未支付';
- $status = isset($info['status']) ? $info['status'] : 0;
- $info['delivery_company'] = '卡密';
- $info['status_text'] = '待支付';
- if ($status) {
- $info['status_text'] = isset($statusArr[$status]) ? $statusArr[$status] : '';
- }
- }
- return $info;
- }
- public function getQuery($params)
- {
- $where = ['a.mark' => 1];
- $type = isset($params['type'])? $params['type'] : 0;
- if($type>0){
- $where['a.type'] = $type;
- }
- return $this->model->with(['member'])->from("account_logs as a")
- ->leftJoin('member as b','b.id','=','a.user_id')
- ->where($where)
- ->where(function ($query) use($params) {
- $keyword = isset($params['keyword']) ? $params['keyword'] : '';
- $userId = isset($params['user_id'])? $params['user_id'] : 0;
- if($userId){
- $query->where('a.user_id',$userId);
- }
- $status = isset($params['status'])? $params['status'] : 0;
- if($status){
- $query->where('a.status',$status);
- }else{
- $query->whereNotIn('a.status',[2]);
- }
- if ($keyword) {
- $query->where(function($query) use($keyword){
- $query->where('b.nickname','like',"%{$keyword}%")
- ->orWhere('b.mobile','like',"%{$keyword}%")
- ->orWhere('b.realname','like',"%{$keyword}%");
- });
- }
- $orderNo = isset($params['order_no'])? trim($params['order_no']) : '';
- if($orderNo){
- $query->where(function($query) use($orderNo){
- $query->where('a.source_order_no','like',"%{$orderNo}%");
- });
- }
- })
- ->where(function ($query) use($params){
- // 日期
- $date = isset($params['date']) ? $params['date'] : [];
- $start = isset($date[0])? $date[0] : '';
- $end = isset($date[1])? $date[1] : '';
- $end = $start>=$end? '' : $end;
- if ($start) {
- $query->where('a.create_time','>=', strtotime($start));
- }
- if($end){
- $query->where('a.create_time','<=', strtotime($end));
- }
- });
- }
- /**
- * 今日金额统计数据
- * @param $userId
- * @param int $type
- * @return array|mixed
- */
- public function getTotalByDay($userId, $type=1)
- {
- $cacheKey = "caches:accounts:total_{$userId}_{$type}";
- $data = RedisService::get($cacheKey);
- if($data){
- return $data;
- }
- $data = $this->model->where(['user_id'=> $userId,'type'=>$type,'status'=>1,'mark'=>1])
- ->where('create_time','>=', strtotime(date('Y-m-d')))
- ->sum('money');
- if($data){
- RedisService::set($cacheKey, $data, rand(5,10));
- }
- return $data;
- }
- /**
- * 充值套餐
- * @param $type
- * @return array|mixed
- */
- public function getPayMealList($params)
- {
- $type = isset($params['type'])?$params['type'] : 0;
- $gasType = isset($params['gas_type'])?$params['gas_type'] : 0;
- $phoneService = isset($params['phone_service'])?$params['phone_service'] : 0;
- $phoneType = isset($params['phone_type'])?$params['phone_type'] : 0;
- $electricType = isset($params['electric_type'])?$params['electric_type'] : 0;
- $cacheKey = "caches:accounts:mealList_{$type}:".md5(json_encode($params));
- $datas = RedisService::get($cacheKey);
- if($datas){
- return $datas;
- }
- $where = ['type'=>$type,'status'=>1,'mark'=>1];
- if($type==1){
- if($phoneType){
- $where['phone_type'] = $phoneType;
- }
- }else if($type==2){
- if($electricType){
- $where['electric_type'] = $electricType;
- }
- }else if($type==3){
- if($gasType){
- $where['gas_type'] = $gasType;
- }
- }
- $datas = PayMealsModel::where($where)
- ->where(function($query) use($phoneService, $type){
- if($type==1 && $phoneService){
- $query->where('phone_service',$phoneService)->orWhere('phone_service',0);
- }
- })
- ->orderBy('sort','desc')
- ->orderBy('id','asc')
- ->get();
- $datas = $datas? $datas->toArray() :[];
- if($datas){
- RedisService::set($cacheKey, $datas, rand(300,600));
- }
- return $datas;
- }
- /**
- * 生活充值
- * @param $userId 用户ID
- * @param $params
- * @return array|false
- */
- public function recharge($userId, $params)
- {
- $mealId = isset($params['id']) ? $params['id'] : 0; // 套餐ID
- $account = isset($params['account']) ? $params['account'] : ''; // 充值账号/手机号
- $electricType = isset($params['electric_type']) ? intval($params['electric_type']) : 0; // 电费充值类型
- $ytype = isset($params['ytype']) ? intval($params['ytype']) : 1; // 电费充值:三要素验证,1-身份证后6位,2-银行卡后六位,3-营业执照后六位
- $area = isset($params['area']) ? trim($params['area']) : ''; // 电费充值:省份/直辖市
- $idCardNo = isset($params['id_card_no']) ? trim($params['id_card_no']) : ''; // 电费充值:三要素验证,身份证后6位/银行卡后6位/营业执照后6位
- $city = isset($params['city']) ? trim($params['city']) : ''; // 电费充值:地级市名
- $cacheKey = "caches:members:pay:{$userId}_{$mealId}";
- if (RedisService::get($cacheKey . '_lock')) {
- $this->error = '请不要频繁提交~';
- return false;
- }
- if(empty($account)){
- $this->error = '请输入充值账号';
- return false;
- }
- RedisService::set($cacheKey, ['date' => date('Y-m-d H:i:s')], rand(2, 3));
- $mealInfo = PayMealsModel::where(['id' => $mealId, 'status' => 1, 'mark' => 1])
- ->select(['id','product_id', 'money', 'type', 'discount', 'remark', 'status'])
- ->first();
- $money = isset($mealInfo['money']) ? floatval($mealInfo['money']) : 0;
- $discount = isset($mealInfo['discount']) ? intval($mealInfo['discount']) : 0;
- $mealType = isset($mealInfo['type']) && $mealInfo['type'] ? intval($mealInfo['type']) : 1;
- $productId= isset($mealInfo['product_id']) ? $mealInfo['product_id'] : 0;
- $price = $discount?moneyFormat($money*$discount/100,2): $money;
- if (empty($mealInfo)) {
- $this->error = '该套餐不存在';
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- if ($price <= 0 || $money <= 0 || $productId<=0) {
- $this->error = '该套餐参数错误';
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- if($mealType==2 && empty($area)){
- $this->error = '请选择省份/直辖市';
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- if($mealType==2 && empty($city)){
- $this->error = '请选择地级市名';
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 电费验证
- if($mealType==2 && $electricType==3){
- if(in_array($area,['广东','广西','海南','贵州','云南'])){
- if($ytype<=0){
- $this->error = '请选择三要素验证类型';
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- if(empty($idCardNo)){
- $this->error = "请填写".(['验证参数','身份证后6位','银行卡后6位','营业执照后6位'][$ytype]);
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- }
- }
- $system = isset($params['system']) && $params['system'] ? $params['system'] : [];
- $platform = isset($system['platform']) && $system['platform']? $system['platform'] : 'mp';
- $info = MemberModel::where(['id' => $userId, 'mark' => 1])
- ->select(['id', 'openid','parent_id', 'mobile', 'status'])
- ->first();
- $parentId = isset($info['parent_id']) ? $info['parent_id'] : 0;
- $openid = isset($info['openid']) ? $info['openid'] : '';
- if (!$info || $info['status'] != 1) {
- $this->error = 1045;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- if (empty($openid)) {
- $this->error = '用户参数错误,请重新授权登录后尝试~';
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 推荐消费者的佣金
- $agentDirectBonusRate = ConfigService::make()->getConfigByCode('agent_direct_bonus_rate', 0);
- $agentDirectBonusRate = $agentDirectBonusRate>0 && $agentDirectBonusRate<100? $agentDirectBonusRate : 0;
- $recBonus = moneyFormat($agentDirectBonusRate * $price/100, 2);
- // 创建订单
- $orderNo = get_order_num('PR');
- $types = ['','话费充值','电费充值','燃气充值'];
- $remark = isset($types[$mealType])? $types[$mealType] : '生活充值';
- $order = [
- 'order_no' => $orderNo,
- 'user_id' => $userId,
- 'meal_id' => $mealId,
- 'product_id' => $productId,
- 'total' => $money,
- 'pay_total' => $price,
- 'type' => $mealType,
- 'account' => $account,
- 'discount' => $discount,
- 'area' => $area,
- 'city' => $city,
- 'ytype' => $ytype,
- 'rec_bonus_id' => $parentId,
- 'rec_bonus_rate' => $agentDirectBonusRate,
- 'rec_bonus' => $recBonus,
- 'bonus_settle' => 2,
- 'id_card_no' => $idCardNo,
- 'create_time' => time(),
- 'remark' => $remark,
- 'status' => 1,
- 'mark' => 1
- ];
- DB::beginTransaction();
- if (!$orderId = PayOrdersModel::insertGetId($order)) {
- $this->error = '创建充值订单失败';
- return false;
- }
- if(env('PAY_DEBUG')){
- $price = 0.1;
- }
- /* TODO 支付处理 */
- $payOrder = [
- 'type' => 1,
- 'order_no' => $orderNo,
- 'pay_money' => $price,
- 'body' => $remark,
- 'openid' => $openid
- ];
- // 调起支付
- // 调起支付
- if($platform == 'wechat'){
- $payment = PaymentService::make()->mpPay($info, $payOrder, 'pay');
- }else{
- $payment = PaymentService::make()->minPay($info, $payOrder, 'pay');
- }
- if (empty($payment)) {
- DB::rollBack();
- RedisService::clear($cacheKey . '_lock');
- $this->error = PaymentService::make()->getError();
- return false;
- }
- // 用户操作记录
- DB::commit();
- $this->error = '创建充值订单成功,请前往支付~';
- // 删除超时订单
- PayOrdersModel::where(['status'=>1])->where('create_time','<=', time() - 6 * 3600)->delete();
- RedisService::clear($cacheKey . '_lock');
- return [
- 'order_id' => $orderId,
- 'payment' => $payment,
- 'total' => $payOrder['pay_money'],
- 'pay_type' => 10,
- ];
- }
- }
|