| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742 |
- <?php
- namespace api\modules\v1\controllers\user;
- use addons\MerchantAuth\common\models\MerchantAuthLog;
- use api\controllers\OnAuthController;
- use common\enums\ApiStatusEnum;
- use common\enums\UserWalletEnum;
- use common\enums\WithdrawEnum;
- use common\logic\user\ScoreLogic;
- use common\models\common\BalanceLog;
- use common\models\common\PlatformSetting;
- use common\models\mall\MallAddons;
- use common\models\user\User;
- use common\models\user\UserWallet;
- use common\models\user\UserWithdrawLog;
- use common\enums\StatusEnum;
- use common\enums\WithdrawWayEnum;
- use common\globals\GlobalInvoke;
- use common\models\wechat\WechatTransferLog;
- use Yii;
- use yii\helpers\Json;
- use yii\db\Exception;
- use common\models\user\UserPartitionRelationship;
- use services\common\UserWalletService;
- use common\helpers\BcHelper;
- use common\helpers\LockHelper;
- use common\models\common\UserBankCard;
- use common\models\user\UserFreezeCommission;
- use common\models\user\WithdrawsLimitLog;
- class BalanceController extends OnAuthController
- {
- public $modelClass = '';
- /**
- *
- * 不用进行登录验证的方法
- *
- * 例如: ['index', 'update', 'create', 'view', 'delete']
- * 默认全部需要验证
- *
- * @var array
- */
- // protected $authOptional = ['login', 'mobile-login', 'sms-code', 'register', 'up-pwd'];
- /**
- * 余额详情
- * @return mixed|void
- */
- public function actionDetail()
- {
- $user_wallet = UserWallet::findOne(['user_id' => $this->user_id]);
- $data['now_balance'] = $user_wallet['balance'] ?? 0;
- $data['today_income'] = BalanceLog::find()->where(['mall_id'=>$this->mall_id,'user_id'=>$this->user_id,'change_type'=>'add'])
- ->andWhere(['between','created_at',strtotime(date('Y-m-d')),time()])->sum('change_num') ?? 0;
- //$data['today_income'] = 0;
- $data['withdraw_num'] = $user_wallet['balance_withdrawal'];
- $data['use_num'] = 0;
- $data['top_up_num'] = 0;
- $query = BalanceLog::find()->where(['mall_id'=>$this->mall_id,'user_id'=>$this->user_id,'capital_type'=>UserWalletEnum::CONSUMPTION_ORDER]);
- $use_num = $query->andWhere(['source_table'=>'transaction','status'=>StatusEnum::ENABLED,'change_type'=>'sub'])->sum('change_num');
- $query = BalanceLog::find()->where(['mall_id'=>$this->mall_id,'user_id'=>$this->user_id,'change_type'=>'add','from_type'=>UserWalletEnum::RECHARGE]);
- $top_up_num = $query->sum('change_num');
- $data['use_num'] = $use_num??0;
- $data['top_up_num'] = $top_up_num??0;
- $balance_config = Yii::$app->services->setting->mall->get($this->mall_id, 'balance');
- $data['is_balance_transfer'] = $balance_config['is_balance_transfer'] ?? 0;
- $data['is_balance_score'] = $balance_config['is_balance_score'] ?? 0;
- return $this->success('操作成功', $data);
- }
- /**
- * 余额充值/消费/提现记录
- * @return mixed|void
- */
- public function actionList()
- {
- $params = \Yii::$app->request->get();
- $res = Yii::$app->services->validate->validate($params, [
- [['type'], 'required', 'message' => 'type,必传'],
- [['start_date', 'end_date', 'capital_type', 'limit'], 'safe'],
- ]);
- if ($res === false) return $this->error(Yii::$app->services->validate->getErrorMessage());
- $where = [];
- $where[] = ['mall_id' => $this->mall_id];
- $where[] = ['user_id' => $this->user_id];
- $where[]=['!=','status',-1];
- if($params['type'] == 2){
- $params['select'] = 'id,num as change_num,order_no,actual_num,poundage_num,exchange_score_num,type,status,created_at,content';
- $params['order'] = 'id desc';
- $where[] = ['from' => 2];
- $params['where'] = $where;
- $list = UserWithdrawLog::listPage($params);
- if($list['list']){
- $ids = array_column($list['list'], 'id');
- if ($this->platform == 'mp-wx') {
- $mini_program = Yii::$app->services->setting->mall->get($this->mall_id, 'mini_program', true);
- $appId = $mini_program['app_id'] ?? '';
- } else {
- $wechat_conf = Yii::$app->services->setting->mall->get($this->mall_id, 'wechat', true);
- $appId = $wechat_conf['app_id'] ?? '';
- }
- $wechat_transfer_log_list = \common\models\wechat\WechatTransferLog::lists(['where' => [['cash_id' => $ids]], 'index' => 'cash_id']);
- foreach ($list['list'] as &$v) {
- $v['transfer_result'] = [];
- if (isset($wechat_transfer_log_list[$v['id']])) {
- $payment_conf = \Yii::$app->services->setting->mall->get($this->mall_id, 'pay.wechat', true);
- $payment_conf = json_decode($payment_conf, true);
- $mchId = $payment_conf['wechat_mch_id'] ?? '';
- $wechat_transfer = $wechat_transfer_log_list[$v['id']];
- $transfer_result = json_decode($wechat_transfer['transfer_result'], true);
- $transfer_result['mchId'] = $mchId;
- $transfer_result['appId'] = $appId;
- $v['transfer_result'] = $transfer_result;
- }
- $content = json_decode($v['content'],true);
- $check_remark = '';
- $v['desc'] = '提现'.$v['change_num'];
- $v['created_at'] = date("Y-m-d H:i:s",$v["created_at"]);
- // 提现状态 0--申请 1--同意 2--已打款 3--驳回
- switch ($v['status']){
- case 0:
- $v['status_text'] = '申请';
- break;
- case 1:
- $v['status_text'] = '同意';
- break;
- case 2:
- $v['status_text'] = '已打款';
- break;
- case 3:
- $v['status_text'] = '驳回';
- $check_remark = $content['reject_content']??'';
- break;
- default:
- $v['status_text'] = '';
- break;
- }
- $v['check_remark'] = $check_remark;
- // 提现方式 auto--自动打款 wechat--微信打款 alipay--支付宝打款 bank--银行转账 balance--打款到余额
- switch ($v['type']){
- case 'auto':
- $v['type_text'] = '自动打款';
- break;
- case 'wechat':
- $v['type_text'] = '微信';
- break;
- case 'alipay':
- $v['type_text'] = '支付宝';
- break;
- case 'bank':
- $v['type_text'] = '银行转账';
- break;
- case 'balance':
- $v['type_text'] = '打款到余额';
- break;
- default:
- $v['type_text'] = '';
- break;
- }
- };
- }
- }else{
- if ($params['type'] == 3) {
- $where[] = ['change_type' => 'sub'];
- $where[] = ['from_type' => UserWalletEnum::CONSUME];//消费
- $where[] = ['source_table' => 'transaction'];//消费
- }
- if ($params['type'] == 1) {
- $where[] = ['change_type' => 'add'];
- $where[] = ['from_type' => UserWalletEnum::RECHARGE];//充值
- }
- if (!empty($params['start_date']) && !empty($params['end_date'])) {
- $params['end_date'] .= '23:59:59';
- $where[] = ['between','created_at',strtotime($params['start_date']),strtotime($params['end_date'])];
- }
- if (!empty($params['capital_type'])) {
- $where[] = ['capital_type' => $params['capital_type']];
- }
- $params['select'] = 'id,change_type,change_num,current_num,desc,created_at,user_id';
- $params['order'] = 'id desc';
- $params['where'] = $where;
- $list = BalanceLog::listPage($params);
- }
- return $this->success('操作成功', $list);
- }
- /**
- * 余额充值资金类型map
- * @return mixed|void
- */
- public function actionBalanceRechargeFrom()
- {
- return $this->success('操作成功', UserWalletEnum::getRechargeCapitalTypeMap());
- }
- /**
- * 余额/佣金提现
- * from 1/佣金 2/余额
- * User: wniu
- * Date: 2021/10/26
- * Time: 3:31 下午
- *
- * @throws \Exception
- */
- public function actionWithdraw()
- {
- $key = sprintf('Withdraw:%s', $this->user_id);
- if (LockHelper::fLock($key)) return $this->error('请勿频繁请求');
- $params = \Yii::$app->request->post();
- $params['mall_id'] = $this->mall_id;
- $params['user_id'] = $this->user_id;
- $params['need_auth'] = 1;
- $params['MerchantAuth'] = 1;
- try {
- UserWithdrawLog::withdrawCheck($params,$key);
- }catch (\Exception $e){
- LockHelper::unFLock($key);
- return $this->error($e->getMessage());
- }
- $form = new UserWithdrawLog();
- $params['mall_id'] = $this->mall_id;
- $params['user_id'] = $this->user_id;
- $params['x-app-platform'] = $this->platform;
- $form->attributes = $params;
- $data = $form->saveRecord($params);
- if($data['state']) {
- LockHelper::unFLock($key);
- return $this->success('操作成功', $data['data']);
- } else {
- LockHelper::unFLock($key);
- return $this->error($data['msg']);
- }
- }
- /**
- * @Author: 广东七件事 ganxiaohao
- * @Date: 2020-05-29
- * @Time: 19:40
- * @Note:提现相关设置
- */
- public function actionCashSetting()
- {
- $params = \Yii::$app->request->post();
- $res = Yii::$app->services->validate->validate($params, [
- [['from'], 'required', 'message' => '参数丢失'],
- [['from'], 'in', 'range' => [1, 2, 3,4]],
- [['source'], 'safe'],
- ]);
- if ($res === false) return $this->error(Yii::$app->services->validate->getErrorMessage());
- $user_balance = UserWallet::getOne([['user_id' => $this->user_id, 'status' => 1]], true, [], false, 'balance,commission,score');
- $is_need_redirect = 0;
- $repurchase_redirect_url = '';
- $repurchase_prompt = '';
- $pay_password_status = 0;
- $is_hidden_money_unit = 0;
- if($params['from'] == 1) {//佣金
- $payment = \Yii::$app->services->setting->mall->get($this->mall_id, 'withdraw_income');
- if (!$payment) {
- return $this->error('暂未开启提现功能');
- }
- $isCash = $payment["is_income_cash"];
- $cashType = $payment['cash_type'];
- $cashServiceFee = isset($payment["cash_service_fee"]) ? $payment["cash_service_fee"] : 10;
- $cashIncomeServiceFee = isset($payment["cash_income_service_fee"]) ? $payment["cash_income_service_fee"] : 10;
- $minMoney = $payment['min_money'];
- $maxMoney = $payment['day_max_money'];
- $withdrawal_rule = isset($payment['profit_withdrawal_rule']) ? $payment['profit_withdrawal_rule'] : '手续费费率';
- $withdrawal_multiple = isset($payment['income_cash_multiple']) ? $payment['income_cash_multiple'] : 0;
- $userMoney = $user_balance['commission'];
- $freeze_commission = UserFreezeCommission::handlePromotionCenter($this->mall_id, $this->user_id);
- if (!empty($freeze_commission['is_freeze_commission'])) {
- $userMoney -= $freeze_commission['freeze_amount'];
- $userMoney < 0 && $userMoney = 0;
- }
- $is_show_balance_withdraws_limit_text = (int)((new UserWithdrawLog())->inBalanceWithdrawTotalWeightLimitSelectedByType($params['from'], WithdrawEnum::LIMIT_STRATEGY, $payment)); // 提现到余额是否需要显示可提现文案
- $withdraws_limit_enable = isset($payment["withdraws_limit_enable"]) ? $payment["withdraws_limit_enable"] : 0;
- $withdraws_limit_money = isset($payment["withdraws_limit_money"]) && is_numeric($payment["withdraws_limit_money"]) ? $payment["withdraws_limit_money"] : 0;
- $is_independent_balance_withdraw = $payment["is_independent_balance_withdraw"] ?? 0; // 是否开启独立余额提现
- $withdrawsLimitLogs = WithdrawsLimitLog::lists([
- 'where' => [
- ['user_id' => $this->user_id, 'status' => StatusEnum::ENABLED, 'from' => 1]
- ],
- 'select' => 'amount, type',
- 'index' => 'type'
- ]);
- if (!empty($withdraws_limit_enable)) {
- if (isset($withdrawsLimitLogs[WithdrawsLimitLog::COMMON_LIMIT]['amount'])) {
- $withdraws_limit_money = $withdrawsLimitLogs[WithdrawsLimitLog::COMMON_LIMIT]['amount'];
- }
- if ($is_independent_balance_withdraw) {
- $independent_balance_withdraw_max_amount = $withdrawsLimitLogs[WithdrawsLimitLog::BALANCE_LIMIT]['amount'] ?? ($payment['independent_balance_withdraw_max_amount'] ?? 0);
- } else {
- $independent_balance_withdraw_max_amount = $withdraws_limit_money;
- }
- $independent_balance_withdraw_max_amount = max($independent_balance_withdraw_max_amount, 0);
- }
- $difference = UserWithdrawLog::doRepurchaseCheck($payment, $this->user, $this->mall_id);
- if ($difference < 0) {
- $is_need_redirect = 1;
- $repurchase_redirect_url = $payment['repurchase_redirect_url'];
- $repurchase_prompt = '您需复购' . abs($difference) . '元,就能提现';
- }
- $pay_password_status = $payment['enable_password'] ?? 0;
- $is_hidden_money_unit = $payment['is_hidden_money_unit'] ?? 0;
- //todo 获取可提现佣金-待优化成功事件调用
- if (!empty($params['source']) && MallAddons::isInstall($this->mall_id, $params['source'])) {
- switch ($params['source']) {
- case 'FireProtection':
- $fire_protection_user = \addons\FireProtection\common\models\FireProtectionUser::findOne(['user_id' => $this->user_id, 'status' => StatusEnum::ENABLED]);
- if (isset($fire_protection_user)) {
- $userMoney = $fire_protection_user['withdrawable_money'];
- }
- break;
- }
- }
- }elseif ($params['from'] == 4) {
- //积分提现
- $payment = \Yii::$app->services->setting->mall->get($this->mall_id, 'score');
- if (!$payment || !$payment['score_cash_status']) {
- return $this->error('暂未开启提现功能');
- }
- $isCash = $payment["score_cash_status"];
- $cashType = $payment['score_cash_type'];
- $cashServiceFee = $payment["score_cash_service_fee"] ?? 10;
- $minMoney = $payment['score_cash_min_money'];
- $maxMoney = $payment['score_cash_day_max_money'] ?? 0;
- $withdrawal_rule = '手续费费率';
- $withdrawal_multiple = 0;
- $userMoney = $user_balance['score'];
- //$show_notice = '您有1000积分,可用积分为200,10积分=1元,可提现20元';
- $radio = $payment['score_cash_radio'] ?? 1;
- $score_cash_today_limit = $payment['score_cash_today_limit'] ?? 0;
- $score_can_cash_arr = ScoreLogic::userTodayCanCashNum($this->mall_id,$this->user_id);
- $show_notice = '您有'.$userMoney.'积分,可用积分为'.$score_can_cash_arr['can_cash_num'].','.$radio.'积分=1元,可提现'.$score_can_cash_arr['can_cash_price'].'元';
- $score_cash_today_limit = $payment['score_cash_today_limit'] ?? 0;
- $question_mark = '';
- if($score_cash_today_limit > 0) $question_mark = '每天可提现的积分不超过00:00所持积分的'.$score_cash_today_limit.'%';
- if($maxMoney > 0){
- $question_mark = ($question_mark ? $question_mark.',' :'').'每日提现金额上限为'.$maxMoney.'元';
- }
- $userMoney = $score_can_cash_arr['can_cash_num'];
- $withdraws_limit_enable = 0;
- $withdraws_limit_money = 0;
- $pay_password_status = $payment['enable_password'] ?? 0;
- }else{
- $payment = \Yii::$app->services->setting->mall->get($this->mall_id, 'withdraw_balance');
- if (!$payment) {
- return $this->error('暂未开启提现功能');
- }
- $isCash = $payment["balance_cash_status"];
- $cashType = $payment['balance_cash_type'];
- $cashServiceFee = isset($payment["balance_cash_service_fee"]) ? $payment["balance_cash_service_fee"] : 10;
- $minMoney = $payment['balance_min_money'];
- $maxMoney = $payment['balance_day_max_money'];
- $withdrawal_rule = isset($payment['profit_withdrawal_rule']) ? $payment['profit_withdrawal_rule'] : '手续费费率';
- $withdrawal_multiple = isset($payment['balance_cash_multiple']) ? $payment['balance_cash_multiple'] : 0;
- $userMoney = $user_balance['balance'];
- $withdraws_limit_enable = 0;
- $withdraws_limit_money = 0;
- $pay_password_status = $payment['enable_password'] ?? 0;
- }
- // $balance_config = \Yii::$app->services->setting->mall->get($this->mall_id, 'pay.balance');
- // $pay_password_status = 0;
- // if ($balance_config) {
- // $balance_config = Json::decode($balance_config);
- // $pay_password_status = isset($balance_config["pay_password_status"]) ? $balance_config["pay_password_status"] : 0;
- // }
- if (!$isCash) {
- return $this->error('系统未开启提现功能');
- }
- if (!$cashType) {
- return $this->error('系统未设置提现方式');
- }
- $cash__type_name = [];
- $get_system_setting = PlatformSetting::getConfByGroup('system', true);
- if(!empty($cashType)){
- $cash_type = Json::decode($cashType);
- $cash__type_name = [];
- $default_withdraw_way = WithdrawWayEnum::getDefaultWithDrawWayMap(WithdrawWayEnum::WITHDRAW_TYPE_2);
- $extension_withdraw_way = GlobalInvoke::exec(GlobalInvoke::INVOKE_GET_WITHDRAW_EXTENSION_WAY,$this->mall_id,['mall_id'=>$this->mall_id]);
- $all_withdraw = array_merge($default_withdraw_way,$extension_withdraw_way);
- $cash_type_keys = array_keys($all_withdraw);
- if (in_array('bank', $cash_type_keys) || in_array('joinpay', $cash_type_keys)) {
- $bank_card_list = UserBankCard::getUserCardList($this->user_id, $this->mall_id);
- }
- // dd($cash_type);
- foreach ($cash_type as $i => $item) {
- if(isset($all_withdraw[$item])){
- $taxFee = 0;
- $name = '';
- if(isset($all_withdraw[$item])){
- if(is_array($all_withdraw[$item])){
- $name = $all_withdraw[$item]['name']??'';
- $taxFee = $all_withdraw[$item]['taxFee']??0;
- }else{
- $name = $all_withdraw[$item];
- }
- }
- $cash__type_name[$i]['type'] = $item;
- $cash__type_name[$i]['taxFee'] = $taxFee;
- $cash__type_name[$i]['name'] = $name;
- $cash__type_name[$i]['img'] = $get_system_setting['api_url']['value'].'/resources/img/payment/'.$item.'.png';
- if ('bank' == $item || 'joinpay' == $item || 'yunfast_pay' == $item) {
- $cash__type_name[$i]['bank_card_list'] = $bank_card_list;
- }
- }
- }
- }
- $password = User::getOne([['id' => $this->user_id]], true, '', '', 'transaction_password');
- $isTransactionPassword = false;
- $transaction_password = $password['transaction_password'];
- $transaction_password = trim($transaction_password);
- if(!empty($transaction_password)){
- $isTransactionPassword = true;
- }
- //检测是否需要实名认证
- $need_auth = GlobalInvoke::exec(GlobalInvoke::REAL_AUTH, $this->mall_id, ['user_id' => $this->user_id,'mall_id' => $this->mall_id,'type' => 'cash']);
- if($need_auth === true){
- //需要先进行实名认证
- return $this->error('请先进行实名认证',[],ApiStatusEnum::CODE_ERROR_NEED_REAL_AUTH);
- }
- $userWithdrawLog = UserWithdrawLog::getOne([
- ['user_id'=>$this->user_id],
- ['type'=>['alipay_tax','alipay']]
- ],true,[],'id desc');
- $aliAccountInfo = [];
- if(!empty($userWithdrawLog)){
- $extra = json_decode($userWithdrawLog['extra'],true);
- if(!empty($extra)){
- $aliAccountInfo = [
- 'name'=>$extra['name'],
- 'mobile'=>$extra['mobile'],
- 'id_card'=>$extra['id_card']??'',
- ];
- }
- }
- //商家认证
- $addons_auth = [];
- if(MallAddons::isInstall($this->mall_id,'MerchantAuth')){
- $configs = Yii::$app->services->setting->addons->get($this->mall_id, 'MerchantAuth', 'basic');
- $is_pass = 1;
- if(!empty($configs['is_force'])){
- //强制需要认证
- $res = MerchantAuthLog::getOne([
- ['mall_id'=>$this->mall_id],
- ['user_id'=>$this->user_id],
- ['status'=>1]
- ]);
- if(empty($res) || empty($res['progress'])) {
- $is_pass = 0;
- }elseif ($configs['is_force'] == 2 && $res['progress'] != 2) {
- $is_pass = 0;
- }
- }
- $addons_auth[] = ['addons'=>'MerchantAuth','is_pass' => $is_pass];
- }
- return $this->success('操作成功', [
- 'addons_auth'=>$addons_auth,
- 'notice'=>[
- 'content'=>'',
- 'icon'=>''
- ],
- 'setting' => [
- 'cash_type_name' => $cash__type_name,
- 'cash_service_fee' => $cashServiceFee,
- 'min_money' => $minMoney,
- 'cash_income_service_fee' => isset($cashIncomeServiceFee) ? $cashIncomeServiceFee : 0,
- 'day_max_money' => $maxMoney,
- 'withdrawal_rule' => $withdrawal_rule,
- 'pay_password_status' => intval($pay_password_status),
- 'multiple' => $withdrawal_multiple ?? 0,
- 'withdraws_limit_enable' => $withdraws_limit_enable ?? 0,
- 'withdraws_limit_money' => $withdraws_limit_money ?? 0,
- 'is_independent_balance_withdraw' => $is_independent_balance_withdraw ?? 0,
- 'independent_balance_withdraw_max_amount' => $independent_balance_withdraw_max_amount ?? 0,
- 'is_show_balance_withdraws_limit_text' => $is_show_balance_withdraws_limit_text ?? 1,
- 'is_hidden_money_unit' => $is_hidden_money_unit,
- 'show_notice' => $show_notice ?? '',
- 'question_mark' => $question_mark ?? ''
- ],
- 'user_info' => [
- 'income' => $userMoney,
- 'is_transaction_password' => $isTransactionPassword
- ],
- 'ali_account_info'=>$aliAccountInfo,
- 'repurchase_limit'=>[
- 'is_need_redirect' => $is_need_redirect,
- 'repurchase_redirect_url' => $repurchase_redirect_url,
- 'repurchase_prompt' => $repurchase_prompt
- ]
- ], ApiStatusEnum::CODE_SUCCESS, 0);
- }
- /**
- * 余额转送/转入页面
- * @Author: lun
- * @DateTime: 2021/11/24 0024 11:04
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @return mixed|void
- */
- public function actionTransfer()
- {
- $form = Yii::$app->request->get();
- $rules = [[['type'], 'required'], [['type'], 'in', 'range' => ['score', 'balance']]];
- $res = Yii::$app->services->validate->validate($form, $rules);
- if ($res === false) return $this->error(Yii::$app->services->validate->getErrorMessage());
- // 查询用户余额
- $score = UserWallet::find()->select('balance')->where(['mall_id'=>$this->mall_id,'user_id'=>$this->user_id,'status'=>StatusEnum::ENABLED])->scalar();
- // 获取转送配置
- $config = Yii::$app->services->setting->mall->get($this->mall_id, 'balance');
- $score_name = Yii::$app->services->setting->mall->get($this->mall_id, 'score.score_name');
- if ($form['type'] == 'balance') {
- $ratio = $config['forwarding_charge'];
- $explain = "转送手续费:{$ratio}%";
- } elseif ($form['type'] == 'score') {
- $ratio = $config['balance_score_ratio'];
- $explain = "1元兑换{$ratio}个{$score_name}";
- }
- $pay_password_status = $config['enable_password'] ?? 0;
- $transaction_password = User::find()->select('transaction_password')->where(['mall_id'=>$this->mall_id,'id'=>$this->user_id,'status'=>StatusEnum::ENABLED])->scalar();
- $is_transaction_password = empty(trim($transaction_password)) ? false : true;
- $data = ['capital' => $score, 'explain' => $explain, 'ratio' => $ratio];
- $data = array_merge($data, compact('pay_password_status', 'is_transaction_password'));
- return $this->success('操作成功', $data);
- }
- /**
- * 余额转送提交
- * @Author: lun
- * @DateTime: 2021/11/24 0024 11:08
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @return mixed|void
- */
- public function actionTransferBalance()
- {
- if (Yii::$app->request->isPost) {
- $form = Yii::$app->request->post();
- $rules = [
- [['balance','user_id'], 'required'],
- [['balance','user_id'], 'integer'],
- [['balance'], 'compare', 'compareValue' => 0, 'operator' => '>'],
- [['transaction_password'], 'string'],
- ];
- $res = Yii::$app->services->validate->validate($form, $rules);
- if ($res === false) return $this->error(Yii::$app->services->validate->getErrorMessage());
- $key = sprintf('TransferBalance:%s', $this->user_id);
- try {
- if (LockHelper::fLock($key, 3)) throw new Exception('请勿频繁请求');
- // 检测转送用户是否是本人
- if ($form['user_id'] == $this->user_id) throw new Exception('赠送的用户不能是本人哦');
- // 检查用户是否存在
- $receive_user = User::getUser([['id' => $form['user_id']]], 'id');
- if (empty($receive_user)) throw new Exception('赠送的用户不存在');
- // 获取配置
- $config = Yii::$app->services->setting->mall->get($this->mall_id, 'balance');
- if (empty($config['is_balance_transfer'])) throw new Exception('余额转增功能尚未开启');
- $check_password_result = UserWithdrawLog::checkPassword($this->user_id, $form['transaction_password'], $config);
- if(is_array($check_password_result)){
- throw new Exception($check_password_result['msg']);
- }
- if (!empty($config['balance_transfer_permission'])) {
- $parent_ids = UserPartitionRelationship::getParentIdArr($this->user_id);// 获取上级
- $child_ids = UserPartitionRelationship::getChildIdArr($this->user_id);// 获取下级
- if (!in_array($receive_user->id, array_merge($parent_ids, $child_ids))) throw new Exception('转送会员不在你的团队中');
- }
- $fee = bcdiv($form['balance'] * $config['forwarding_charge'], 100, 2);// 手续费
- $sub_balance = bcadd($form['balance'], $fee, 2);// 最终扣减余额额度
- $give_user = $this->user_id;// 转出用户
- $receive = '用户:'.$receive_user->id;// 接收用户
- $fee_str = $fee <= 0 ? '' : ',手续费'.$fee;
- // 查询用户余额
- $user_wallet = UserWallet::find()->select('id,balance')->where(['mall_id'=>$this->mall_id,'user_id'=>$this->user_id,'status'=>StatusEnum::ENABLED])->asArray()->one();
- if (empty($user_wallet) || ($user_wallet['balance'] < $sub_balance)) throw new Exception('余额额度不足');
- // 组合用户
- $list = [['user_id'=>$this->user_id,'type' => 'sub'], ['user_id'=>$receive_user->id,'type'=>'add']];
- //循环生成
- foreach ($list as $item) {
- $insert_wallet[] = [
- 'mall_id' => $this->mall_id,
- 'user_id' => $item['user_id'],
- 'is_frozen' => false,
- 'wallet_type' => UserWalletService::WALLET_TYPE_BALANCE,
- 'money' => $item['type'] == 'sub' ? -$sub_balance : $form['balance'],
- // 'desc' => $item['type'] == 'sub' ? '余额转送'. $form['balance'].'元,手续费'.$fee : '余额转送'. $form['balance'].'元',
- 'desc' => $item['type'] == 'sub' ? '余额转给'.$receive.$fee_str : $give_user.'余额转送',
- 'source_table' => UserWallet::tableName(),
- 'source_table_id' => $user_wallet['id'],
- 'from_type' => UserWalletEnum::TRANSFER,
- 'capital_type'=> UserWalletEnum::TRANSFER_GIVE
- ];
- }
- // 异步处理积分
- if ($insert_wallet) {
- $res = UserWalletService::batchHandle($insert_wallet);
- if (empty($res)) throw new Exception(UserWalletService::getStaticError());
- }
- // LockHelper::unFLock($key);
- $this->success('转送成功');
- } catch (\Exception $e) {
- // LockHelper::unFLock($key);
- return $this->error('赠送失败:' . $e->getMessage());
- }
- }
- }
- /**
- * 余额转入积分
- * @Author: lun
- * @DateTime: 2021/11/24 0024 14:58
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @return mixed|void
- * @throws \Exception
- */
- public function actionTransferScore()
- {
- if (Yii::$app->request->isPost) {
- $form = Yii::$app->request->post();
- $rules = [
- [['balance'], 'required'],
- [['balance'], 'integer'],
- [['balance'], 'compare', 'compareValue' => 0, 'operator' => '>'],
- [['transaction_password'], 'string'],
- ];
- $res = Yii::$app->services->validate->validate($form, $rules);
- if ($res === false) return $this->error(Yii::$app->services->validate->getErrorMessage());
- }
- $key = sprintf('TransferScore:%s', $this->user_id);
- try {
- if (LockHelper::fLock($key, 3)) throw new Exception('请勿频繁请求');
- // 获取配置
- $config = Yii::$app->services->setting->mall->get($this->mall_id, 'balance');
- if (empty($config['is_balance_score'])) throw new Exception('余额转积分功能尚未开启');
- if (empty($config['balance_score_ratio'])) throw new Exception('余额转积分功能尚未开启');
- $score = BcHelper::floorFloat(($form['balance'] * $config['balance_score_ratio']),2);// 保留两位小数,向下取整
- $check_password_result = UserWithdrawLog::checkPassword($this->user_id, $form['transaction_password'], $config);
- if(is_array($check_password_result)){
- throw new Exception($check_password_result['msg']);
- }
- // 查询用户余额
- $user_wallet = UserWallet::find()->select('id,balance')->where(['mall_id'=>$this->mall_id,'user_id'=>$this->user_id,'status'=>StatusEnum::ENABLED])->asArray()->one();
- if (empty($user_wallet) || ($user_wallet['balance'] < $form['balance'])) throw new Exception('余额额度不足');
- //扣余额
- $insert_wallet[] = [
- 'mall_id' => $this->mall_id,
- 'user_id' => $this->user_id,
- 'is_frozen' => false,
- 'wallet_type' => UserWalletService::WALLET_TYPE_BALANCE,
- 'money' => -$form['balance'],
- 'desc' => '余额转入积分',
- 'source_table' => UserWallet::tableName(),
- 'source_table_id' => $user_wallet['id'],
- 'from_type' => UserWalletEnum::TRANSFER,
- 'capital_type'=> UserWalletEnum::TRANSFER_SCORE
- ];
- //加积分
- $insert_wallet[] = [
- 'mall_id' => $this->mall_id,
- 'user_id' => $this->user_id,
- 'is_frozen' => false,
- 'wallet_type' => UserWalletService::WALLET_TYPE_SCORE,
- 'money' => $score,
- 'desc' => '余额转入积分',
- 'source_table' => UserWallet::tableName(),
- 'source_table_id' => $user_wallet['id'],
- 'from_type' => UserWalletEnum::RECHARGE,
- 'capital_type'=> UserWalletEnum::RECHARGE_BALANCE
- ];
- // 异步处理积分
- if ($insert_wallet) {
- $res = UserWalletService::batchHandle($insert_wallet);
- if (empty($res)) throw new Exception(UserWalletService::getStaticError());
- }
- // LockHelper::unFLock($key);
- $this->success('转入成功');
- } catch (\Exception $e) {
- // LockHelper::unFLock($key);
- return $this->error('转积分失败:' . $e->getMessage());
- }
- }
- //获取上一次提现的账号信息
- public function actionGetPrevInfo()
- {
- $request = Yii::$app->request;
- if ($request->isGet) {
- try {
- $get = $request->get();
- $res = Yii::$app->services->validate->validate($get, [
- // [['from'], 'integer'],
- [['type', 'source'], 'string'],
- [['from'], 'safe']
- ]);
- if (!$res) throw new Exception(Yii::$app->services->validate->getErrorMessage());
- $info = (new UserWalletService())->getPrevInfo($this->mall_id, $this->user_id, $get);
- return $this->success('获取成功', $info);
- } catch (\Exception $e) {
- return $this->error($e->getMessage());
- }
- }
- }
- }
|