| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004 |
- <?php
- namespace addons\Store\common\models;
- use addons\Alitopay\common\enums\AlitoapyEnum;
- use addons\Alitopay\common\services\AlipayService;
- use addons\Alitopay\common\services\SettingService;
- use addons\AvoidTax\common\service\UserService;
- use addons\JoinPay\common\global_func\withdraw_way\WithdrawWay;
- use addons\JoinPay\common\models\JoinPayUserBankcard;
- use common\components\export\CsvTool;
- use common\enums\DownloadEnum;
- use common\enums\PayTypeEnum;
- use common\enums\RedisKeyEnum;
- use common\enums\StatusEnum;
- use addons\Store\common\enums\StoreEnum;
- use common\enums\UserWalletEnum;
- use common\helpers\LockHelper;
- use common\helpers\StringHelper;
- use common\logic\common\PaymentLogic;
- use common\models\base\BaseActiveRecord;
- use common\models\common\Download;
- use common\models\common\PaymentTransfer;
- use common\models\common\UserBankCard;
- use common\models\user\User;
- use common\models\user\UserInfo;
- use services\common\PayService;
- use services\common\UserWalletService;
- use Yii;
- use yii\db\Exception;
- use yii\helpers\Json;
- /**
- * This is the model class for table "qimall_addons_store_withdraw_log".
- *
- * @property int $id
- * @property int $mall_id 商城id
- * @property int $store_id 门店id
- * @property int $user_id 会员id
- * @property string $order_no 提现订单号
- * @property float $num 提现金额
- * @property float $actual_num 实际到账金额
- * @property float $poundage_num 手续费扣除金额
- * @property float $poundage_ratio 手续费比例
- * @property string $type 提现方式 bank--银行转账 balance--打款到余额
- * @property string $extra 额外信息
- * @property int $withdraw_status 提现状态 0--待打款 --已打款 2--驳回 3--提现失败
- * @property int $status 状态[0禁用 1启用 -1删除]
- * @property string $remark 备注
- * @property int|null $created_at 添加时间戳
- * @property int|null $updated_at 更新时间戳
- */
- class StoreWithdrawLog extends BaseActiveRecord
- {
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_store_withdraw_log}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['mall_id', 'store_id', 'user_id', 'withdraw_status', 'status', 'created_at', 'updated_at'], 'integer'],
- [['num', 'actual_num', 'poundage_num', 'poundage_ratio'], 'number'],
- [['extra'], 'string'],
- [['order_no', 'remark'], 'string', 'max' => 255],
- [['type'], 'string', 'max' => 45],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'mall_id' => '商城id',
- 'store_id' => '门店id',
- 'user_id' => '会员id',
- 'order_no' => '提现订单号',
- 'num' => '提现金额',
- 'actual_num' => '实际到账金额',
- 'poundage_num' => '手续费扣除金额',
- 'poundage_ratio' => '手续费比例',
- 'type' => '提现方式 bank--银行转账 balance--打款到余额',
- 'extra' => '额外信息',
- 'content' => '用户额外输入信息',
- 'withdraw_status' => '提现状态 0--待打款 --已打款 2--驳回 ',
- 'status' => '态 0--申请 1--同意 2--已打款 3--驳回 4--失败',
- 'remark' => '备注',
- 'created_at' => '添加时间戳',
- 'updated_at' => '更新时间戳',
- ];
- }
- /**
- * User: wniu
- * Date: 2021/10/25
- * Time: 6:02 下午
- * *
- * @param $params
- * @return false|int[]
- * @throws Exception
- */
- public function saveRecord($params)
- {
- if(!empty($params['type'])){
- switch ($params['type']){
- case "joinpay":
- case "bank":
- if(empty($params['bank_account'])||empty($params['bank_name'])||empty($params['name'])){
- return [
- 'state' => false,
- 'msg' => '请选择银行卡!'
- ];
- }
- break;
- case "wechat":
- if(empty($params['wechat_qrcode'])){
- return [
- 'state' => false,
- 'msg' => '请上传收款码!'
- ];
- }
- break;
- case "alipay_tax":
- if(empty($params['id_card'])){
- return [
- 'state' => false,
- 'msg' => '请填写支付宝身份证号码!'
- ];
- }
- if(empty($params['mobile'])){
- return [
- 'state' => false,
- 'msg' => '请填写支付宝账号!'
- ];
- }
- if(empty($params['name'])){
- return [
- 'state' => false,
- 'msg' => '请填写支付宝真实姓名!'
- ];
- }
- break;
- case "alipay_offline":
- case "alitopay":
- if(empty($params['name'])){
- return [
- 'state' => false,
- 'msg' => '请填写支付宝真实姓名!'
- ];
- }
- if(empty($params['mobile'])){
- return [
- 'state' => false,
- 'msg' => '请填写支付宝账号!'
- ];
- }
- break;
- }
- }
- if ($params['price'] <= 0) {
- return [
- 'state' => false,
- 'msg' => '提现金额必须大于0!'
- ];
- }
- $exists = self::find()->where([
- 'mall_id' => $params['mall_id'], 'withdraw_status' => 0, 'user_id' => $params['user_id']
- ])->asArray()->one();// mycat不支持exists()用法
- if ($exists) {
- return [
- 'state' => false,
- 'msg' => '尚有未审核的提现申请!'
- ];
- }
- $store = Store::getOne([['id' => $params['store_id']]], false, [], false, 'id,mall_id,user_id,balance,total_expenses');
- //手续费设置
- $poundage_ratio = 0;
- //需要提现手续费金额
- $cash_amount = $params['price'];
- if ($params['type'] != 'balance') {
- $finance = \Yii::$app->services->setting->addons->get($params['mall_id'], StoreEnum::ADDONS_NAME, 'finance');
- $storeSetting = StoreSettings::findOne(['store_id' => $this->store_id]);
- // 走的独立设置
- if (!empty($storeSetting->is_enable_withdraw_setting)) {
- $finance['balance_cash_service_fee_limit'] = $storeSetting->balance_cash_service_fee_limit;
- $finance['balance_cash_service_fee_month'] = $storeSetting->balance_cash_service_fee_month;
- $finance['balance_cash_service_fee_diff'] = $storeSetting->balance_cash_service_fee_diff;
- $finance['balance_cash_service_fee'] = $storeSetting->balance_cash_service_fee;
- }
- if (!empty($finance['balance_cash_service_fee_limit'])) {
- $month_start = strtotime(date('Y-m-01 00:00:00'));
- $month_end = time();
- $cash_total = self::find()
- ->where(['mall_id' => $params['mall_id'], 'withdraw_status' => [0, 1], 'user_id' => $params['user_id'], 'status' => StatusEnum::ENABLED])
- ->andWhere(['>=', 'created_at', $month_start])
- ->andWhere(['!=', 'type', 'balance'])
- ->andWhere(['<', 'created_at', $month_end])
- ->sum('num') ?? 0;
- if ($params['price'] + $cash_total > $finance['balance_cash_service_fee_month']) {
- $poundage_ratio = $finance['balance_cash_service_fee_diff'] ?? 0;
- $cash_amount = bcsub(bcadd($params['price'], $cash_total, 2), $finance['balance_cash_service_fee_month'], 2);
- if ($cash_amount > $params['price']) {
- $cash_amount = $params['price'];
- }
- }
- } else {
- if (isset($finance['balance_cash_service_fee'])) {
- $poundage_ratio = $finance['balance_cash_service_fee'] ?? 0;
- } else {
- $poundage_ratio = \Yii::$app->services->setting->mall->get($params['mall_id'], 'withdraw_balance.balance_cash_service_fee');
- }
- }
- }
- if ($store['balance'] < $params['price']) {
- return [
- 'state' => false,
- 'msg' => '提现金额超出可提现金额!'
- ];
- }
- if (!$params['type']) {
- return [
- 'state' => false,
- 'msg' => '请选择提现方式!'
- ];
- }
- if ($params['type'] == 'wechat') {
- if (!isset($params['wechat_qrcode'])) {
- return [
- 'state' => false,
- 'msg' => '请上传微信收款码!'
- ];
- }
- }
- if ($params['type'] == 'alipay') {
- if (!$params['mobile']) {
- return [
- 'state' => false,
- 'msg' => '请填写支付宝账号!'
- ];
- }
- if (!$params['name']) {
- return [
- 'state' => false,
- 'msg' => '请填写支付宝姓名!'
- ];
- }
- }
- if ($params['type'] == 'paid') {//代付银行卡
- if (!$params['name']) {
- return [
- 'state' => false,
- 'msg' => '请填写持卡人!'
- ];
- }
- if (!$params['bank_account']) {
- return [
- 'state' => false,
- 'msg' => '请填写银行卡号!'
- ];
- }
- }
- if ($params['type'] == 'alipay_tax') {
- if (!$params['mobile']) {
- return [
- 'state' => false,
- 'msg' => '请填写支付宝账号(手机号)'
- ];
- }
- if (!$params['name']) {
- return [
- 'state' => false,
- 'msg' => '请填写支付宝姓名'
- ];
- }
- if (!$params['id_card']) {
- return [
- 'state' => false,
- 'msg' => '请填写身份证信息'
- ];
- }
- $service = new \addons\AvoidTax\common\service\UserService(['mall_id' => $params['mall_id']]);
- $res = $service->checkSign($params['user_id']);
- if ($res === false) {
- $res = $service->goToSing($params['user_id'], $params['mobile'], $params['id_card'], $params['name']);
- if (!$res) {
- return [
- 'state' => false,
- 'msg' => $service->error
- ];
- }
- // 跳转url签约
- return [
- 'state' => true,
- 'data' => $res
- ];
- }
- }
- $cash = new StoreWithdrawLog();
- $cash->mall_id = $params['mall_id'];
- $cash->user_id = $store['user_id'];
- $cash->store_id = $store['id'];
- $cash->num = $params['price'];
- $cash->actual_num = $params['price'];
- $cash->order_no = StringHelper::generateOrderNo('tx');
- $cash->status = StatusEnum::ENABLED;
- $cash->remark = $params['remark'] ?? '';
- $cash->content = Json::encode(['user_content' => $params['content']]);
- $cash->type = $params['type'];
- $cash->extra = Json::encode([
- 'name' => $params['name'],
- 'mobile' => $params['mobile'],
- 'bank_name' => $params['bank_name'],
- 'bank_account' => (string)$params['bank_account'],
- 'bank_account_type' => $params['bank_account_type'],
- 'wechat_qrcode' => $params['wechat_qrcode'],
- 'id_card' => $params['id_card'] ?? '',
- 'receive_bank_chanel_no' => $params['receive_bank_chanel_no'] ?? ''
- ], JSON_UNESCAPED_UNICODE);
- if ($poundage_ratio < 0 || $poundage_ratio > 100) {
- return [
- 'state' => false,
- 'msg' => '手续费设置不正确!'
- ];
- }
- //手续费
- $poundage = 0;
- if ($poundage_ratio > 0 && $poundage_ratio < 100) {
- //手续费:取小数点2位,截断
- $poundage = bcmul($poundage_ratio / 100, $cash_amount, 4);
- // 四舍五入,保留2位
- $poundage = number_format($poundage, 2, '.', '');
- $cash->actual_num = bcsub($params['price'], $poundage, 2);
- $cash->poundage_num = $poundage;
- $cash->poundage_ratio = $poundage_ratio;
- }
- if (intval(bcmul($cash->actual_num, 100)) < 1) {
- return [
- 'state' => false,
- 'msg' => '提现金额扣除费用后金额不足!'
- ];
- }
- $t = \Yii::$app->db->beginTransaction();
- try {
- switch ($params['type']) {
- case 'balance':
- //提现到个人余额
- $desc = '余额提现' . $cash->num;
- $data = [
- 'message_id' => 0, 'mall_id' => $store['mall_id'], 'user_id' => $store['user_id'],
- 'wallet_type' => 'balance',
- 'is_frozen' => false, 'unfrozen' => false, 'money' => abs($cash->actual_num),
- 'desc' => $desc, 'source_table' => 'user_wallet', 'source_table_id' => $cash->id,
- 'from_type' => UserWalletEnum::WITHDRAWAL,
- 'capital_type' => UserWalletEnum::RECHARGE_STORE_BALANCE,
- ];
- $wallet_service_status = UserWalletService::handle(0, $data);
- if (!$wallet_service_status) {
- throw new Exception('提现失败' . UserWalletService::getStaticError());
- }
- $cash->withdraw_status = 1;
- break;
- default:
- $cash->withdraw_status = 0;
- }
- if (!$cash->save()) {
- throw new Exception($cash->getErrorMessage());
- }
- $store->balance -= $params['price'];
- $store->total_expenses += $params['price'];
- $res = $store->save();
- if ($res == false) throw new Exception($store->getErrorMessage());
- $res_data = [
- 'state' => true,
- 'data' => ['cash_id' => $cash->id],
- 'msg' => ''
- ];
- $t->commit();
- } catch (Exception $e) {
- $t->rollBack();
- \Yii::error($e->getMessage());
- return [
- 'state' => false,
- 'msg' => '提现失败!' . $e->getMessage()
- ];
- }
- return $res_data;
- }
- public static function withdrawByJoinPay($select_bank)
- {
- dd($select_bank);
- }
- public static function withdrawApply($params)
- {
- // $t = Yii::$app->db->beginTransaction();
- // $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_MCH_BALANCE_WALLET, $params['mch_id']);
- $identification = uniqid();
- try {
- // if (LockHelper::lock($lock_key, $identification, 100, 100)) {
- $store = Store::getOne([['id' => $params['store_id']]], false, [], false, 'id,mall_id,user_id,balance');
- if ($params['withdrawal_money'] > $store['balance']) throw new Exception('输入金额大于可提现金额');
- $params['user_id'] = $store['user_id'];
- $cash = new self();
- $cash->mall_id = $params['mall_id'];
- $cash->user_id = $store['user_id'];
- $cash->store_id = $store['id'];
- $cash->num = $params['withdrawal_money'];
- $cash->actual_num = $params['withdrawal_money'];
- $cash->order_no = StringHelper::generateOrderNo('tx');
- $cash->extra = json_encode([]);
- $cash->status = 1;
- $cash->remark = $params['remark'] ?? '';
- $extra = [];
- $return_data = [];
- $withdraw_status = 0;
- switch ($params['withdrawal_type']) {
- case 'balance':
- //提现到个人余额
- $cash->type = 'balance';
- $desc = '余额提现' . $cash->num;
- $data = [
- 'message_id' => 0, 'mall_id' => $store['mall_id'], 'user_id' => $store['user_id'],
- 'wallet_type' => 'balance',
- 'is_frozen' => false, 'unfrozen' => false, 'money' => abs($cash->actual_num),
- 'desc' => $desc, 'source_table' => 'user_wallet', 'source_table_id' => $cash->id,
- 'from_type' => UserWalletEnum::WITHDRAWAL,
- 'capital_type' => UserWalletEnum::RECHARGE_MCH_BALANCE,
- ];
- $wallet_service_status = UserWalletService::handle(0, $data);
- if (!$wallet_service_status) {
- throw new Exception('提现失败' . UserWalletService::getStaticError());
- }
- $withdraw_status = 1;
- break;
- case 'bank':
- case 'joinpay':
- case 'yunfast_pay':
- if (empty($params['select_bank'])) throw new Exception('请选择银行卡');
- $extra = $params['select_bank'];
- break;
- case 'alitopay':
- case 'alipay_offline':
- if (empty($params['name'])) throw new Exception('请输入支付宝真实姓名');
- if (empty($params['mobile'])) throw new Exception('支付宝绑定的手机号');
- // if (empty($params['id_card'])) throw new Exception('请输入支付宝身份证号码');
- // $extra['id_card'] = $params['id_card'];
- $extra['name'] = $params['name'];
- $extra['mobile'] = $params['mobile'];
- break;
- case 'alipay_tax':
- if (empty($params['name'])) throw new Exception('请输入支付宝真实姓名');
- if (empty($params['mobile'])) throw new Exception('支付宝绑定的手机号');
- $extra['name'] = $params['name'];
- $extra['mobile'] = $params['mobile'];
- if (empty($params['id_card'])) throw new Exception('请输入支付宝身份证号码');
- $extra['id_card'] = $params['id_card'];
- $obj = new UserService(['mall_id' => $params['mall_id']]);
- $res = $obj->checkSign($store['user_id']);
- $data['is_sign'] = 0;
- if ($res != false) {
- $data['is_sign'] = 1;
- $data = array_merge($res, $data);
- }
- $return_data['is_sign'] = $data['is_sign'];
- if (!$data['is_sign']) {
- $res = $obj->goToSing($store['user_id'], $params['mobile'], $params['id_card'], $params['name']);
- if (!$res) {
- throw new Exception($obj->error);
- }
- $res['is_sign'] = $data['is_sign'];
- return ['code' => 1, 'data' => $res];
- }
- break;
- case 'wechat':
- if (empty($params['wechat_qrcode'])) throw new Exception('请上传凭证');
- $extra['content'] = $params['content'];
- $extra['wechat_qrcode'] = $params['wechat_qrcode'];
- break;
- case 'auto':
- $userInfo = UserInfo::findOne(['user_id' => $store['user_id'], 'mall_id' => $params['mall_id'],
- 'status' => StatusEnum::ENABLED, 'platform' => ['wechat', 'mp-wx']]);
- if (empty($userInfo)) throw new Exception('该商户不存在微信相关信息,请先到前端用微信公众号或者小程序注册');
- break;
- default:
- throw new Exception('提现方式异常');
- // }
- }
- $cash->extra = json_encode($extra);
- $cash->type = $params['withdrawal_type'];
- if ($params['balance_cash_service_fee'] > 0 && $params['balance_cash_service_fee'] < 100) {
- //手续费:取小数点2位,截断
- $poundage = bcmul($params['balance_cash_service_fee'] / 100, $params['withdrawal_money'], 4);
- // 四舍五入,保留2位
- $poundage = number_format($poundage, 2, '.', '');
- $cash->actual_num = bcsub($params['withdrawal_money'], $poundage, 2);
- $cash->poundage_num = $poundage;
- $cash->poundage_ratio = $params['balance_cash_service_fee'];
- }
- if (intval(bcmul($cash->actual_num, 100)) < 1) {
- throw new Exception('提现金额扣除费用后金额不足');
- }
- $cash->withdraw_status = $withdraw_status;
- $res = $cash->save();
- if ($res == false) throw new Exception($cash->getErrorMessage());
- $store->balance -= $params['withdrawal_money'];
- $res = $store->save();
- if ($res == false) throw new Exception($store->getErrorMessage());
- // $t->commit();
- // LockHelper::uLock($lock_key, $identification);
- return ['code' => 1, 'data' => $return_data];
- } catch (\Exception $e) {
- // $t->rollBack();
- // LockHelper::uLock($lock_key, $identification);
- self::$static_error = $e->getMessage();
- return [];
- }
- }
- /**
- * @name:
- * @msg: 后台审核门店提现申请
- * @param {int} $mall_id
- * @param {array} $params
- * @return {*}
- */
- public static function cashAuditOld(int $mall_id, array $params)
- {
- $log = self::findOne(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'id' => $params['id'], 'withdraw_status' => 0]);
- if (empty($log)) {
- self::$static_error = '提现记录不存在';
- return false;
- }
- if ($params['withdraw_status'] == 1 && $log['type'] == 'fast_join_pay') {
- //汇聚代付
- $extraArr = json_decode($log['extra'], true);
- $extra = json_encode([
- 'bank_account' => $extraArr['bank_card_no'],
- 'name' => $extraArr['payer_name'],
- 'bank_account_type' => $extraArr['bank_account_type'],
- ]);
- $cash = [
- 'actual_num' => $log['actual_num'],
- 'mall_id' => $log['mall_id'],
- 'user_id' => $log['user_id'],
- 'order_no' => $log['order_no'],
- 'extra' => $extra,
- ];
- $data['cash'] = json_decode(json_encode($cash));
- $data['title'] = 'o2o店铺余额提现';
- $data['source'] = '2';
- WithdrawWay::extensionWithdrawPay($data);
- }
- $transaction = \Yii::$app->db->beginTransaction();
- $log->withdraw_status = $params['withdraw_status'];
- $log->remark = $params['remark'];
- $log->updated_at = time();
- $res = $log->save();
- if (!$res) {
- $transaction->rollBack();
- self::$static_error = $log->getErrorMessage();
- return false;
- }
- if (2 == $params['withdraw_status']) {
- // 驳回提现申请,退回已经扣除的余额
- $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_STORE_BALANCE_WALLET, $log->store_id);
- $identification = uniqid();
- if (LockHelper::lock($lock_key, $identification, 100, 100)) {
- // 退回的金额
- $store = Store::findOne(['mall_id' => $mall_id, 'id' => $log->store_id, 'user_id' => $log->user_id]);
- $store->balance = bcadd($store->balance, $log->num, 2);
- $res_store = $store->save();
- LockHelper::uLock($lock_key, $identification);
- if (!$res_store) {
- $transaction->rollBack();
- self::$static_error = $store->getErrorMessage();
- return false;
- }
- $transaction->commit();
- return true;
- } else {
- $transaction->rollBack();
- self::$static_error = '系统繁忙,请稍后再试';
- return false;
- }
- } else {
- $transaction->commit();
- return true;
- }
- }
- public static function cashAudit(int $mall_id, array $params)
- {
- $log = self::findOne(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'id' => $params['id'], 'withdraw_status' => 0]);
- if (empty($log)) {
- self::$static_error = '提现记录不存在';
- return false;
- }
- try {
- $res = false;
- switch ($params['withdraw_status']) {
- case 1:
- $cash = [
- 'actual_num' => $log['actual_num'],
- 'mall_id' => $log['mall_id'],
- 'user_id' => $log['user_id'],
- 'order_no' => $log['order_no'],
- 'id' => $log['id'],
- ];
- switch ($log['type']) {
- case "joinpay":
- //汇聚代付
- $extraArr = json_decode($log['extra'], true);
- $extra = json_encode([
- 'bank_account' => !empty($extraArr['bank_card_no'])?$extraArr['bank_card_no']:$extraArr['bank_account'],
- 'name' => !empty($extraArr['payer_name'])?$extraArr['payer_name']:$extraArr['name'],
- 'bank_account_type' =>$extraArr['bank_account_type'],
- ]);
- $cash['extra'] = $extra;
- $data['cash'] = json_decode(json_encode($cash));
- $data['title'] = '商户余额提现';
- $data['source'] = '3';
- $res = WithdrawWay::extensionWithdrawPay($data);
- break;
- case "alitopay":
- $extraArr = json_decode($log['extra'], true);
- $res = self::withdrawToPay($mall_id, $log['id'], $log['order_no'], $extraArr['name'], $extraArr['mobile'], $log['actual_num']);
- break;
- case "alipay_offline":
- case "bank":
- case "wechat":
- $res = true;
- break;
- case "auto":
- $userInfo = UserInfo::getOne([["user_id" => $log->user_id, "platform" => [User::PLATFORM_WECHAT, User::PLATFORM_MP_WX], "status" => StatusEnum::ENABLED]]);
- try {
- $cash['extra'] = [];
- $payment = new PayService();
- $paymentTransfer = new PaymentTransfer();
- $paymentTransfer->orderNo = PaymentTransfer::generate_order_no("TX");
- $paymentTransfer->user = $userInfo;
- $paymentTransfer->title = "收益提现";
- $paymentTransfer->amount = $log['actual_num'];
- $paymentTransfer->transferType = PayTypeEnum::WECHAT;
- $paymentTransfer->cashInfo = json_decode(json_encode($cash));
- $paymentTransfer->withdrawal_source = 'Store';
- $paymentTransfer->withdrawal_source_id = $log['id'];
- $res = $payment->transfer($paymentTransfer);
- } catch (Exception $e) {
- throw new \Exception($e->getMessage());
- }
- break;
- case 'alipay_tax':
- break;
- }
- if ($res) {
- $log->withdraw_status = $params['withdraw_status'];
- $log->remark = $params['remark'];
- $log->updated_at = time();
- $res = $log->save();
- if (!$res) {
- throw new \Exception($log->getErrorMessage());
- }
- }
- break;
- case 2:
- // 驳回提现申请,退回已经扣除的余额
- $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_STORE_BALANCE_WALLET, $log->store_id);
- $identification = uniqid();
- if (LockHelper::lock($lock_key, $identification, 100, 100)) {
- // 退回的金额
- $store = Store::findOne(['mall_id' => $mall_id, 'id' => $log->store_id, 'user_id' => $log->user_id]);
- $store->balance = bcadd($store->balance, $log->num, 2);
- $store->total_expenses = bcsub($store->total_expenses, $log->num, 2);
- $res_store = $store->save();
- $log->withdraw_status = $params['withdraw_status'];
- $log->remark = $params['remark'];
- $log->updated_at = time();
- $res = $log->save();
- LockHelper::uLock($lock_key, $identification);
- if (!$res_store) {
- throw new \Exception($store->getErrorMessage());
- }
- $res = true;
- } else {
- throw new \Exception('系统繁忙,请稍后再试');
- }
- break;
- }
- return $res;
- }catch (\Exception $e){
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- public static function withdrawToPay($mall_id, $source_id, $order_no, $name, $mobile, $money)
- {
- // 获取设置
- $setting = (new SettingService($mall_id))->getSetting();
- if (empty($setting)) throw new \Exception('未进行代付配置');
- // 加锁
- $uniqid = uniqid();
- $lock_key = 'alitopay_order_lock_' . $mall_id;
- if (!LockHelper::lock($lock_key, $uniqid)) throw new \Exception('操作频繁请稍后重试');
- // 拼接数据入表
- $insert_data = [];
- $time = time();
- // 是否达到最低打款金额
- if ($money < AlitoapyEnum::MIX_WITHDRAW) {
- throw new \Exception("订单{$name},打款金额必须大于1元");
- }
- // 数据
- $data['mall_id'] = $mall_id;
- $data['order_sn'] = $time . rand(1000, 9999);
- $data['type'] = Order::TYPE_WITHDRAWAL;
- $data['money'] = $money;
- $data['name'] = $name;
- $data['account'] = $mobile;
- $data['source_id'] = $source_id;
- $data['source_sn'] = $order_no;
- $data['created_at'] = $data['updated_at'] = $time;
- $insert_data[] = $data;
- // 开启事务
- $db = Yii::$app->db->beginTransaction();
- try {
- // 批量插入
- Order::batchInsert($insert_data);
- // 批量修改打款中
- $db->commit();
- } catch (\Exception $e) {
- $db->rollBack();
- LockHelper::uLock($lock_key, $uniqid);
- throw new \Exception($e->getMessage());
- }
- // 批量进行打款
- $count = self::aliPay($mall_id, $insert_data);
- LockHelper::uLock($lock_key, $uniqid);
- return $count;
- }
- private static function aliPay($mall_id, array $list)
- {
- $aliapy = new AlipayService($mall_id);
- // 创建一个批次号
- $out_batch_no = 'TX' . date('Ymd') . $mall_id . rand(1000, 9999);
- $count = 0;
- $sub_msg = null;
- foreach ($list as $v) {
- // 打款
- $res = $aliapy->transfer(
- $v['money'], $v['name'], $v['account'], $v['order_sn']
- );
- if ($res['code'] == '10000') {
- // 打款成功
- Order::paySuccessBySourceIdAndOrderSn(
- $v['source_id'], $v['order_sn'],$res['order_id']
- );
- $count++;
- } else {
- // 打款失败
- Order::payFialBySourceIdAndOrderSn(
- $v['source_id'], $v['order_sn'], $res['sub_msg']
- );
- $sub_msg =$res['sub_msg'];
- }
- }
- // 设置批次号
- Order::setOutBatchNoByOrderSn($out_batch_no, array_column($list, 'order_sn'));
- if(isset($sub_msg)){
- throw new \Exception($sub_msg);
- }
- return $count;
- }
- /**
- * @name:
- * @msg: 导出字段列表
- * @param {array} $fields
- * @return {*}
- */
- public static function exportFieldList(array $fields = null)
- {
- $field_list = [
- 'nickname' => '会员昵称',
- 'mobile' => '手机号',
- 'type' => '提现方式',
- 'account_username' => '收款账户名',
- 'account_no' => '收款账户',
- 'account_organization' => '收款机构',
- 'num' => '提现金额',
- 'poundage_num' => '手续费',
- 'actual_num' => '实际打款金额',
- 'remark' => '备注',
- 'created_at' => '付款时间',
- ];
- if (empty($fields)) {
- return $field_list;
- } else {
- $new_list = [];
- foreach ($fields as $val) {
- if (!empty($field_list[$val])) {
- $new_list[$val] = $fields[$val];
- }
- }
- return $new_list;
- }
- }
- public static function exportHandle(array $data = null)
- {
- try {
- $download_id = $data['download_id'] ?? 0;
- $download = Download::findOne(['id' => $download_id]);
- $params = json_decode($download->params, true);
- // dd($params);
- $have_select_field_arr = [];
- $all_fields = self::exportFieldList();
- $fields = $params['fields'] ?? [];
- if (!empty($fields)) {
- foreach ($fields as $field) {
- $have_select_field_arr[] = $all_fields[$field];
- }
- } else {
- $have_select_field_arr = $all_fields;
- }
- // dd($have_select_field_arr);
- $csv = new CsvTool();
- $csv->filename = $download->name;
- $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($download->type);
- $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
- $csv->header = $have_select_field_arr;
- $cash_status_map = ['waiting-payment' => 0, 'payment' => 1, 'refund' => 2];
- $list_query = self::find()->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED, 'withdraw_status' => $cash_status_map[$params['curr_tabname']]]);
- if (!empty($params['user_id'])) {
- $wheres[] = ['user_id' => $params['user_id']];
- }
- if (!empty($params['nickname'])) {
- $users = User::find()
- ->select('id,nickname,mobile,avatar_url')
- ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED])
- ->andWhere(['like', 'nickname', $params['nickname']])
- ->asArray()
- ->indexBy('id')
- ->all();
- $wheres[] = ['user_id' => array_column($users, 'id')];
- }
- if (!empty($params['start_time'])) {
- $wheres[] = ['>=', 'created_at', strtotime($params['start_time'])];
- }
- if (!empty($params['end_time'])) {
- $wheres[] = ['<=', 'created_at', strtotime($params['end_time'] . ' 23:59:59')];
- }
- $rows = [];
- $type_map= PaymentLogic::getWithdrawTypeMap($params['mall_id']);
- foreach ($list_query->asArray()->batch(200) as $lists) {
- if (empty($users)) {
- $user_ids = array_column($lists, 'user_id');
- $users = User::find()
- ->select('id,nickname,mobile,avatar_url')
- ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED, 'id' => $user_ids])
- ->asArray()
- ->indexBy('id')
- ->all();
- }
- foreach ($lists as &$list) {
- $user = $users[$list['user_id']] ?? '';
- $list['nickname'] = $user['nickname'] ?? '';
- $list['mobile'] = $user['mobile'] ?? '';
- $list['account_no'] = $list['account_username'] = $list['account_organization'] = '';
- switch ($list['type']) {
- case 'bank':
- case 'joinpay':
- $extra = json_decode($list['extra'], true);
- $list['account_no'] = $extra['bank_card_no'] ?? '';
- $list['account_username'] = $extra['payer_name'] ?? '';
- $list['account_organization'] = $extra['bank_name'] ?? '';
- break;
- case 'alipay':
- $extra = json_decode($list['extra'], true);
- $list['account_no'] = $extra['mobile'] ?? '';
- $list['account_username'] = $extra['name'] ?? '';
- $list['account_organization'] = '';
- break;
- case 'balance':
- $list['account_no'] = $user['mobile'] ?? '';
- $list['account_username'] = $user['nickname'] ?? '';
- $list['account_organization'] = '平台';
- break;
- case 'auto':
- $list['account_no'] = $user['mobile'] ?? '';
- $list['account_username'] = $user['nickname'] ?? '';
- $list['account_organization'] = '';
- break;
- }
- $arr = [];
- foreach ($fields as $field) {
- if (!empty($list[$field])) {
- if ('created_at' == $field) {
- $list[$field] = date('Y-m-d H:i:s', $list[$field]);
- }
- if ('mobile' == $field) {
- $list[$field] = (string)$list[$field];
- }
- if($field=='type'){
- $list[$field] = $type_map[$list[$field]]??'';
- }
- } else {
- $list[$field] = '';
- }
- $arr[] = $list[$field];
- }
- $rows[] = $arr;
- }
- }
- // dd($rows);
- $csv->data = $rows;
- $csv->export();
- $csv->updateDown($download, $params['mall_id']);
- return true;
- } catch (\Exception $e) {
- $download->status = 3;
- $res = $download->save();
- self::setStaticError($e->getMessage());
- return $e->getMessage();
- }
- }
- /**
- * 打款失败,变成待打款状态,让客户自己去驳回
- * @param $withdraw_log
- * @param $msg
- */
- public static function remit_fail($withdraw_log, $msg)
- {
- $res = StoreWithdrawLog::updateAll([
- 'withdraw_status' => 0,
- 'remark' => '打款结果:' . $msg,
- 'updated_at' => time()
- ], ['id' => $withdraw_log->id]);
- }
- public static function fixTotalExpenses(){
- $list = StoreWithdrawLog::lists([
- 'where'=>[
- ['withdraw_status'=>[0,1]]
- ],
- 'select'=>'sum(num) as num,store_id',
- 'group'=>'store_id'
- ]);
- foreach ($list as $item){
- $store = Store::findOne(['id'=>$item['store_id']]);
- if($store){
- $store->total_expenses = $item['num'];
- $store->save();
- }
- }
- }
- }
|