UserWithdrawLog.php 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387
  1. <?php
  2. namespace common\models\user;
  3. use addons\Chanjet\common\global_func\Request;
  4. use addons\Chanjet\common\models\AddonsChanjetRequest;
  5. use addons\DigitalEmployment\common\models\DigitalEmploymentOrder;
  6. use addons\Linggong\common\service\ApiRequestService;
  7. use addons\MerchantAuth\common\models\MerchantAuthLog;
  8. use addons\Redpack\common\enums\RedpackEnum;
  9. use addons\Redpack\common\models\RedpackWallet;
  10. use addons\Redpack\common\models\RedpackWalletLog;
  11. use addons\ScoreGame\common\enums\ScoreGameEnum;
  12. use backend\modules\mall\services\WithdrawalService;
  13. use common\components\export\CsvTool;
  14. use common\enums\AddonsChanjetRequestEnum;
  15. use common\enums\AddonsEnum;
  16. use common\enums\DownloadEnum;
  17. use common\enums\RedisKeyEnum;
  18. use common\enums\PayTypeEnum;
  19. use common\enums\StatusEnum;
  20. use common\enums\UserWalletEnum;
  21. use common\enums\WithdrawEnum;
  22. use common\enums\WithdrawWayEnum;
  23. use common\events\user\UserWalletEvent;
  24. use common\events\user\UserWithdrawEvent;
  25. use common\events\user\UserWithdrawRejectEvent;
  26. use common\events\user\UserWithdrawSuccessfulEvent;
  27. use common\globals\GlobalInvoke;
  28. use common\helpers\LockHelper;
  29. use common\logic\user\ScoreLogic;
  30. use common\logic\wechat\WechatMessageLogic;
  31. use common\models\common\Download;
  32. use common\models\common\PaidSinglePayLog;
  33. use common\models\common\PaymentTransfer;
  34. use common\enums\AssetsType;
  35. use common\models\base\BaseActiveRecord;
  36. use common\models\common\CapitalLog;
  37. use common\models\common\ScoreLog;
  38. use common\models\mall\MallAddons;
  39. use services\common\PayService;
  40. use services\common\UserWalletService;
  41. use Exception;
  42. use Yii;
  43. use yii\helpers\Json;
  44. /**
  45. * This is the model class for table "{{%user_withdraw_log}}".
  46. *
  47. *
  48. * @property int $id
  49. * @property int $mall_id
  50. * @property int $user_id
  51. * @property string $order_no 提现订单号
  52. * @property float $num 提现金额
  53. * @property float $actual_num 实际到账金额
  54. * @property float $poundage_num 手续费扣除金额
  55. * @property float $poundage_ratio 手续费比例
  56. * @property float $exchange_score_num 转积分金额
  57. * @property float $exchange_score_ratio 转积分比例
  58. * @property float $give_score_num 提现赠送积分额度
  59. * @property int $from 提现来源1佣金2余额 4积分
  60. * @property string $type 提现方式 auto--自动打款 wechat--微信打款 alipay--支付宝打款 bank--银行转账 balance--打款到余额
  61. * @property string $extra 额外信息 例如微信账号、支付宝账号等
  62. * @property string $content 用户额外输入信息
  63. * @property int $status 提现状态 0--申请 1--同意 2--已打款 3--驳回 4--失败
  64. * @property string|null $transfer 支付宝打款信息
  65. * @property float|null $direct_withdraws_reward_num 提现直推奖励金额
  66. * @property float|null $indirect_withdraws_reward_num 提现间推奖励金额
  67. * @property float|null $direct_withdraws_reward_ratio 提现直推奖励比例
  68. * @property float|null $indirect_withdraws_reward_ratio 提现间推奖励比例
  69. * @property int $created_at 添加时间戳
  70. * @property int $updated_at 更新时间戳
  71. * @property string $source 来源
  72. * @property string $sign 提现标识
  73. * @property float $exchange_balance_num 转余额金额
  74. * @property float $exchange_balance_ratio 转余额比例
  75. */
  76. class UserWithdrawLog extends BaseActiveRecord
  77. {
  78. const FROM_BALANCE = 2;
  79. const FROM_INCOME = 1;
  80. const FROM_PAYMENT_FOR_GOODS = 3;
  81. const FROM_SCORE = 4;
  82. const FROM_SCORE_GAME = 9; //积分增长赢插件
  83. const FROM_HUIDIAN = 10; //惠点插件
  84. const STATUS_APPLY = 0;
  85. const STATUS_AGREE = 1;
  86. const STATUS_ALREADY_TRANS = 2;
  87. const STATUS_ALREADY_REJECT = 3;
  88. const STATUS_FAIL = 4;
  89. const STATUS_WAIT = 5;
  90. //提现状态
  91. public static $status_msg = [
  92. self::STATUS_APPLY => '申请',
  93. self::STATUS_AGREE => '同意',
  94. self::STATUS_ALREADY_TRANS => '已打款',
  95. self::STATUS_ALREADY_REJECT => '驳回',
  96. self::STATUS_FAIL => '失败',
  97. self::STATUS_WAIT => '打款中'
  98. ];
  99. //打款类型
  100. public static $type_msg = [
  101. 'auto' => '自动打款',
  102. 'wechat' => '微信',
  103. 'alipay' => '支付宝',
  104. 'bank' => '银行转账',
  105. 'balance' => '打款到余额'
  106. ];
  107. public static $from_msg = [
  108. self::FROM_BALANCE => '余额',
  109. self::FROM_INCOME => '佣金',
  110. self::FROM_SCORE => '积分',
  111. self::FROM_SCORE_GAME => '积分增长赢',
  112. self::FROM_HUIDIAN => '惠点'
  113. ];
  114. /**
  115. * @var float|int|mixed|null
  116. */
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public static function tableName()
  121. {
  122. return '{{%user_withdraw_log}}';
  123. }
  124. /**
  125. * {@inheritdoc}
  126. */
  127. public function rules()
  128. {
  129. return [
  130. [['mall_id', 'user_id', 'num', 'actual_num', 'extra', 'content', 'from', 'type'], 'required'],
  131. [['id', 'mall_id', 'user_id', 'from', 'status', 'created_at', 'updated_at'], 'integer'],
  132. [['num', 'actual_num', 'poundage_num', 'direct_withdraws_reward_num', 'indirect_withdraws_reward_num', 'poundage_ratio', 'exchange_score_num', 'exchange_score_ratio', 'give_score_num', 'direct_withdraws_reward_ratio', 'indirect_withdraws_reward_ratio', 'exchange_balance_num', 'exchange_balance_ratio'], 'number'],
  133. [['extra', 'content', 'transfer'], 'string'],
  134. [['order_no','source'], 'string', 'max' => 255],
  135. [['type','sign'], 'string', 'max' => 45],
  136. [['from'], 'in', 'range' => [1, 2, 3, 4, 9, 10]],
  137. ];
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function attributeLabels()
  143. {
  144. return [
  145. 'id' => 'ID',
  146. 'mall_id' => 'Mall ID',
  147. 'user_id' => 'User ID',
  148. 'order_no' => 'Order No',
  149. 'num' => 'Num',
  150. 'actual_num' => 'Actual Num',
  151. 'poundage_num' => 'Poundage Num',
  152. 'poundage_ratio' => 'Poundage Ratio',
  153. 'exchange_score_num' => 'Exchange Score Num',
  154. 'exchange_score_ratio' => 'Exchange Score Ratio',
  155. 'give_score_num' => 'Give Score Num',
  156. 'from' => 'From',
  157. 'type' => 'Type',
  158. 'extra' => 'Extra',
  159. 'content' => 'Content',
  160. 'status' => 'Status',
  161. 'transfer' => 'Transfer',
  162. 'created_at' => 'Created At',
  163. 'updated_at' => 'Updated At',
  164. 'source' => 'source',
  165. ];
  166. }
  167. public static function fieldsList($field = null, $isChanjet = false)
  168. {
  169. $fields = [
  170. 'user_id' => '会员ID',
  171. // 'user_info' => '基本信息',
  172. 'username' => '会员编号',
  173. 'nickname' => '会员昵称',
  174. 'user_mobile' => '手机号码',
  175. 'from' => '提现类型',
  176. // 'type' => '账户信息',
  177. 'alipay_name' => '支付宝姓名',
  178. 'mobile' => '支付宝账号',
  179. 'bank_account_type' => '账户类型',
  180. 'name' => '持卡/开户人',
  181. 'bank_name' => '开户行',
  182. 'bank_account' => '银行卡号',
  183. 'withdraw_type' => '提现方式',
  184. 'idcard' => '身份证',
  185. // 'withdrawal_information' => '提现信息',
  186. 'num' => '提现金额',
  187. 'actual_num' => '实际到账金额',
  188. 'poundage_num' => '手续费',
  189. 'exchange_score_num' => '转积分扣除',
  190. 'status' => '状态',
  191. 'updated_at' => '时间',
  192. 'remark' => '备注',
  193. ];
  194. if ($isChanjet) {
  195. $fields['chanjet_updated_at'] = '最后推送时间';
  196. $fields['chanjet_request_status'] = '推送状态';
  197. }
  198. if ($field === null) return $fields;
  199. $temp = [];
  200. foreach ($field as $val) {
  201. if (isset($fields[$val])) $temp[$val] = $fields[$val];
  202. }
  203. return $temp;
  204. }
  205. /**
  206. * User: wniu
  207. * Date: 2021/10/25
  208. * Time: 6:02 下午
  209. * *
  210. * @param $params
  211. * @param array $extra 额外自定义参数
  212. * @return false|int[]
  213. * @throws Exception
  214. */
  215. public function saveRecord($params, $extra = [])
  216. {
  217. if ($params['price'] <= 0) {
  218. return [
  219. 'state' => false,
  220. 'msg' => '提现金额必须大于0!'
  221. ];
  222. }
  223. $exists = self::find()->where([
  224. 'mall_id' => $params['mall_id'], 'status' => 0, 'user_id' => $params['user_id'], 'from' => $params['from']
  225. ])->asArray()->one();
  226. if ($exists) {
  227. return [
  228. 'state' => false,
  229. 'msg' => '尚有未审核的提现申请!'
  230. ];
  231. }
  232. $user_balance = UserWallet::getOne([['user_id' => $params['user_id'], 'status' => 1]], true, [], false, 'balance,commission,score');
  233. $actual_num = $params['price']; //提现到账金额
  234. /**
  235. * 增加缓存机制防止重新提交表单
  236. */
  237. // $cacheKey = 'cash-submit-' . $params['user_id'];
  238. // $cacheValue = md5($params['price'] . $params['type']);
  239. // if(!$this->formLimitSubmis($cacheKey, $cacheValue)){
  240. // return $this->returnApiResultData(ApiCode::CODE_FAIL, '操作太快啦,请稍候');
  241. // }
  242. $deduct_equal_points = 0;
  243. $payment = [];
  244. if ($params['from'] == self::FROM_BALANCE) {
  245. if ($user_balance['balance'] < $params['price']) {
  246. return [
  247. 'state' => false,
  248. 'msg' => '提现金额超出可提现金额!'
  249. ];
  250. }
  251. $payment = \Yii::$app->services->setting->mall->get($params['mall_id'], 'withdraw_balance');
  252. if (!empty($payment['balance_min_money']) && $params['price'] < $payment['balance_min_money']) {
  253. return [
  254. 'state' => false,
  255. 'msg' => '最少提现金额是' . $payment['balance_min_money'] . '!'
  256. ];
  257. }
  258. if (!$payment || $payment['balance_cash_status'] == 0) {
  259. return [
  260. 'state' => false,
  261. 'msg' => '暂未开启提现功能!'
  262. ];
  263. }
  264. if (!empty($payment['balance_cash_multiple']) && ($multiple = $payment['balance_cash_multiple'])) {
  265. if (bcmod($params['price'], $multiple, 2) != 0) {
  266. return [
  267. 'state' => false,
  268. 'msg' => sprintf('请输入%s的倍数!', $multiple),
  269. ];
  270. }
  271. }
  272. // 限制
  273. if ($this->witdrawLimit($params, $payment) === false) {
  274. return [
  275. 'state' => false,
  276. 'msg' => $this->getError(),
  277. ];
  278. }
  279. $dayMaxMoney = isset($payment['balance_day_max_money']) && $payment['balance_day_max_money'] > 0 ? $payment['balance_day_max_money'] : 100000;
  280. $minMoney = isset($payment['balance_min_money']) && $payment['balance_min_money'] > 0 ? $payment['balance_min_money'] : 0;
  281. $poundage_ratio = isset($payment['balance_cash_service_fee']) && $payment['balance_cash_service_fee'] > 0 ? $payment['balance_cash_service_fee'] : 0;
  282. $exchange_score_ratio = isset($payment['balance_trans_score_rate']) && $payment['balance_trans_score_rate'] > 0 ? $payment['balance_trans_score_rate'] : 0;
  283. $wallet_type = UserWalletService::WALLET_TYPE_BALANCE;
  284. }elseif($params['from'] == self::FROM_SCORE){
  285. $payment = \Yii::$app->services->setting->mall->get($params['mall_id'], 'score');
  286. if (!empty($payment['score_cash_min_money'])) {
  287. //&& $params['price'] < $payment['score_cash_min_money']
  288. $score_cash_radio = $payment['score_cash_radio'];
  289. $score_cash_min_money = bcmul($payment['score_cash_min_money'],$score_cash_radio,2);
  290. if ($params['price'] < $score_cash_min_money) {
  291. return [
  292. 'state' => false,
  293. 'msg' => '最少提现数量是' . $score_cash_min_money . '!'
  294. ];
  295. }
  296. }
  297. if (!$payment || $payment['score_cash_status'] == 0) {
  298. return [
  299. 'state' => false,
  300. 'msg' => '暂未开启提现功能!'
  301. ];
  302. }
  303. $actual_num = ScoreLogic::checkUserCash($params['mall_id'],$params['user_id'],$params['price']);
  304. if(!$actual_num){
  305. return [
  306. 'state' => false,
  307. 'msg' => ScoreLogic::getStaticError()
  308. ];
  309. }
  310. $dayMaxMoney = isset($payment['score_cash_day_max_money']) && $payment['score_cash_day_max_money'] > 0 ? $payment['score_cash_day_max_money'] : 100000;
  311. $minMoney = isset($payment['score_cash_min_money']) && $payment['score_cash_min_money'] > 0 ? $payment['score_cash_min_money'] : 0;
  312. $poundage_ratio = isset($payment['score_cash_service_fee']) && $payment['score_cash_service_fee'] > 0 ? $payment['score_cash_service_fee'] : 0;
  313. $wallet_type = UserWalletService::WALLET_TYPE_SCORE;
  314. } else {
  315. $freeze_commission = UserFreezeCommission::handlePromotionCenter($params['mall_id'], $params['user_id']);
  316. if(!empty($freeze_commission['is_freeze_commission'])){
  317. $user_balance['commission'] -= $freeze_commission['freeze_amount'];
  318. $user_balance['commission'] < 0 && $user_balance['commission'] = 0;
  319. }
  320. if ($user_balance['commission'] < $params['price']) {
  321. return [
  322. 'state' => false,
  323. 'msg' => '提现金额超出可提现金额!'
  324. ];
  325. }
  326. $payment = \Yii::$app->services->setting->mall->get($params['mall_id'], 'withdraw_income');
  327. // 如果是提现到余额则根据配置 "提现到余额总权重控制" 决定是否对余额提现进行每项的限制
  328. $needCheckLevels = $this->getIsNeedCheckSettingMap($params['from'], $params['type'], $payment);
  329. $deduct_equal_points = ($payment['deduct_equal_points'] ?? $deduct_equal_points) && $needCheckLevels[WithdrawEnum::DEDUCT_EQUAL_POINTS];
  330. $score_name = \Yii::$app->services->setting->mall->get($params['mall_id'], 'score.score_name');
  331. //扣除冻结红包
  332. $deduct_equal_frozen_redpack = ($payment['deduct_equal_frozen_redpack'] ?? 0) && $needCheckLevels[WithdrawEnum::DEDUCT_FROZEN_REDPACKET];
  333. $install_redpack = MallAddons::isInstall($params['mall_id'], AddonsEnum::ADDONS_NAME_REDPACK);
  334. if($deduct_equal_frozen_redpack && $install_redpack){
  335. //查询用户红包
  336. $redpack = RedpackWallet::find()->select("frozen_redpack")->where(['user_id' => $params['user_id'], 'status' => StatusEnum::ENABLED])->asArray()->one();
  337. if($redpack['frozen_redpack'] < $params['price']){
  338. $config = Yii::$app->services->setting->addons->get($params['mall_id'], AddonsEnum::ADDONS_NAME_REDPACK, 'basic');
  339. $redpack_name = $config['redpack_name'] ?? '红包';// 自定义红包名称
  340. return [
  341. 'state' => false,
  342. 'msg' => '提现金额超出可扣除冻结' . $redpack_name . '!'
  343. ];
  344. }
  345. }
  346. $withdrawsLimitLogType = WithdrawsLimitLog::getType($params['mall_id'], $params['type'], $payment);
  347. $payment["withdraws_limit_enable"] = $needCheckLevels[WithdrawEnum::LIMIT_STRATEGY] && !empty($payment["withdraws_limit_enable"]);
  348. $withdraws_limit_enable = $payment["withdraws_limit_enable"];
  349. if(!empty($payment["withdraws_limit_enable"])){
  350. $withdraws_limit_money = $withdrawsLimitLogType == WithdrawsLimitLog::COMMON_LIMIT ? (isset($payment["withdraws_limit_money"]) ? $payment["withdraws_limit_money"] : 0) : ($payment["independent_balance_withdraw_max_amount"] ?? 0);
  351. $withdrawsLimitLog = WithdrawsLimitLog::getOne([['user_id' => $params['user_id'], 'status' => StatusEnum::ENABLED,'from'=>1, 'type' => $withdrawsLimitLogType]], true, [], false, 'amount');
  352. if(!empty($withdrawsLimitLog)){
  353. $withdraws_limit_money = $withdrawsLimitLog['amount'];
  354. }
  355. if($params['price'] > $withdraws_limit_money){
  356. return [
  357. 'state' => false,
  358. 'msg' => '提现金额超出可提现额度,复购任意产品可恢复额度',
  359. ];
  360. }
  361. }
  362. if (($user_balance['score'] < $params['price']) && $deduct_equal_points == 1) {
  363. return [
  364. 'state' => false,
  365. 'msg' => '提现金额超出可扣除' . $score_name . '!'
  366. ];
  367. }
  368. // 如果提现到余额根据配置决定要不要限制(如果提现到余额总权重控制 关闭或者开启但是未选择最小提现额度则不需要限制)
  369. if ($needCheckLevels[WithdrawEnum::MIN_WITHDRAW_AMOUNT] && !empty($payment['min_money']) && $params['price'] < $payment['min_money']) {
  370. return [
  371. 'state' => false,
  372. 'msg' => '最少提现金额是' . $payment['min_money'] . '!'
  373. ];
  374. }
  375. if (!$payment || $payment['is_income_cash'] == 0) {
  376. return [
  377. 'state' => false,
  378. 'msg' => '暂未开启提现功能!'
  379. ];
  380. }
  381. if ($needCheckLevels[WithdrawEnum::WITHDRAW_MULTIPLE] && !empty($payment['income_cash_multiple']) && ($multiple = $payment['income_cash_multiple'])) {
  382. if (bcmod($params['price'], $multiple, 2) != 0) {
  383. return [
  384. 'state' => false,
  385. 'msg' => sprintf('请输入%s的倍数!', $multiple),
  386. ];
  387. }
  388. }
  389. // 限制
  390. if ($needCheckLevels[WithdrawEnum::WITHDRAW_RESTRICTION] && $this->witdrawLimit($params, $payment) === false) {
  391. return [
  392. 'state' => false,
  393. 'msg' => $this->getError(),
  394. ];
  395. }
  396. $dayMaxMoney = $needCheckLevels[WithdrawEnum::DAILY_MAX_WITHDRAW] ? (isset($payment['day_max_money']) && $payment['day_max_money'] > 0 ? $payment['day_max_money'] : -1) : -1;
  397. $minMoney = isset($payment['min_money']) && $payment['min_money'] > 0 ? $payment['min_money'] : 0.1;
  398. //$poundage_ratio = isset($payment['cash_service_fee']) && $payment['cash_service_fee'] > 0 ? $payment['cash_service_fee'] : 0;
  399. if ($params['type'] == 'balance') {
  400. $poundage_ratio = isset($payment['cash_income_service_fee']) && $payment['cash_income_service_fee'] > 0 ? $payment['cash_income_service_fee'] : 0;
  401. } else {
  402. $poundage_ratio = isset($payment['cash_service_fee']) && $payment['cash_service_fee'] > 0 ? $payment['cash_service_fee'] : 0;
  403. }
  404. $exchange_score_ratio = $needCheckLevels[WithdrawEnum::CONVERT_TO_POINTS_RATIO] && isset($payment['balance_trans_score_rate']) && $payment['balance_trans_score_rate'] > 0 ? $payment['balance_trans_score_rate'] : 0;
  405. $wallet_type = UserWalletService::WALLET_TYPE_COMMISSION;
  406. // 提现转余额比例
  407. $trans_balance_rate = !empty($payment['trans_balance_rate']) ? $payment['trans_balance_rate'] : 0;
  408. }
  409. $direct_withdraws_reward_rate = isset($payment['direct_withdraws_reward']) && $payment['direct_withdraws_reward'] > 0 ? $payment['direct_withdraws_reward'] : 0;
  410. $indirect_withdraws_reward_rate = isset($payment['indirect_withdraws_reward']) && $payment['indirect_withdraws_reward'] > 0 ? $payment['indirect_withdraws_reward'] : 0;
  411. $direct_withdraws_reward = intval(bcmul($params['price'] * $direct_withdraws_reward_rate / 100, 100)) / 100;
  412. $indirect_withdraws_reward = intval(bcmul($params['price'] * $indirect_withdraws_reward_rate / 100, 100)) / 100;
  413. $check_password_result = self::checkPassword($params['user_id'], $params['transaction_password'], $payment);
  414. if(is_array($check_password_result)){
  415. return $check_password_result;
  416. }
  417. // $balance_config = \Yii::$app->services->setting->mall->get($params['mall_id'], 'pay.balance');
  418. // if ($balance_config) {
  419. // $balance_config = Json::decode((string)$balance_config);
  420. // if ($balance_config['pay_password_status'] == 1) {
  421. // $transactionPassword = $params['transaction_password'];
  422. // $password = User::getOne([['id' => $params['user_id']]], true, '', '', 'transaction_password');
  423. // if (!$params['transaction_password']) {
  424. // return [
  425. // 'state' => false,
  426. // 'msg' => '请输入支付密码!'
  427. // ];
  428. // }
  429. // if (empty($password['transaction_password'])) {
  430. // return [
  431. // 'state' => false,
  432. // 'msg' => '您未设置支付密码!'
  433. // ];
  434. // }
  435. // if (empty($transactionPassword)) {
  436. // return [
  437. // 'state' => false,
  438. // 'msg' => '请输入交易密码!'
  439. // ];
  440. // }
  441. // if (!\Yii::$app->getSecurity()->validatePassword(trim($transactionPassword), $password['transaction_password'])) {
  442. // return [
  443. // 'state' => false,
  444. // 'msg' => '支付密码错误!'
  445. // ];
  446. // }
  447. // }
  448. // }
  449. // if ($minMoney > $params['price']) {
  450. // return [
  451. // 'state' => false,
  452. // 'msg' => '最低提现金额为' . $minMoney
  453. // ];
  454. // }
  455. if ($dayMaxMoney > -1) {
  456. // 根据配置 "提现到余额总权重限制" 决定要不要忽略今日的余额提现
  457. // 空表示对余额不限制,那么今日已提现的则不能累计
  458. if (!$this->inBalanceWithdrawTotalWeightLimitSelectedByType($params['from'], WithdrawEnum::DAILY_MAX_WITHDRAW, $payment)) {
  459. $filterBalanceWhere = ['<>', 'type', 'balance'];
  460. }
  461. $today_cash_price = self::find()->where(['user_id' => $params['user_id'], 'mall_id' => $params['mall_id'], 'from' => $params['from']])->andWhere(['>', 'created_at', strtotime(date('Y-m-d', time()))])->andWhere(['<', 'status', 3])->andWhere($filterBalanceWhere ?? [])->sum('num');
  462. if ($today_cash_price >= $dayMaxMoney) {
  463. return [
  464. 'state' => false,
  465. 'msg' => '今日可提现额度已用完!'
  466. ];
  467. }
  468. if (floatval($params['price']) + floatval($today_cash_price) > floatval($dayMaxMoney)) {
  469. return [
  470. 'state' => false,
  471. 'msg' => '提现金额大于今日剩余可提现额度!'
  472. ];
  473. }
  474. }
  475. if (!$params['type']) {
  476. return [
  477. 'state' => false,
  478. 'msg' => '请选择提现方式!'
  479. ];
  480. }
  481. if ($params['type'] == 'wechat') {
  482. if (!isset($params['wechat_qrcode'])) {
  483. return [
  484. 'state' => false,
  485. 'msg' => '请上传微信收款码!'
  486. ];
  487. }
  488. }
  489. if ($params['type'] == 'alipay') {
  490. if (!$params['mobile']) {
  491. return [
  492. 'state' => false,
  493. 'msg' => '请填写支付宝账号!'
  494. ];
  495. }
  496. if (!$params['name']) {
  497. return [
  498. 'state' => false,
  499. 'msg' => '请填写支付宝姓名!'
  500. ];
  501. }
  502. }
  503. if ($params['type'] == 'paid' || $params['type'] == 'joinpay') { //代付银行卡
  504. if (!$params['name']) {
  505. return [
  506. 'state' => false,
  507. 'msg' => '请填写持卡人!'
  508. ];
  509. }
  510. if (!$params['bank_account']) {
  511. return [
  512. 'state' => false,
  513. 'msg' => '请填写银行卡号!'
  514. ];
  515. }
  516. }
  517. if ($params['type'] == 'alipay_tax') {
  518. if (!$params['mobile']) {
  519. return [
  520. 'state' => false,
  521. 'msg' => '请填写支付宝账号(手机号)'
  522. ];
  523. }
  524. if (!$params['name']) {
  525. return [
  526. 'state' => false,
  527. 'msg' => '请填写支付宝姓名'
  528. ];
  529. }
  530. if (!$params['id_card']) {
  531. return [
  532. 'state' => false,
  533. 'msg' => '请填写身份证信息'
  534. ];
  535. }
  536. $service = new \addons\AvoidTax\common\service\UserService(['mall_id' => $this->mall_id]);
  537. // $res = $service->checkSign($this->user_id);
  538. // 判断当前身份ID是否已经签约 已签约则不签约
  539. if (!$service->idIsSignAndAddAuthOfUid(
  540. $params['id_card'], $params['name'], $this->user_id, $params['mobile']
  541. )) {
  542. // 判断用户是否签约
  543. $res = $service->checkSign($this->user_id);
  544. if ($res === false) {
  545. if ($service->getConfigService()->isXLApiType()) {
  546. $res = $service->goToSing($this->user_id, $params['mobile'], $params['id_card'], $params['name'], $extra['redirect_url'] ?? '');
  547. if (!$res) {
  548. return [
  549. 'state' => false,
  550. 'msg' => $service->error
  551. ];
  552. }
  553. // 跳转url签约
  554. return [
  555. 'state' => true,
  556. 'data' => $res
  557. ];
  558. }
  559. if ($service->getConfigService()->isLYApiType()) {
  560. $res = $service->silentSign(
  561. $this->user_id, $params['name'], $params['mobile'], $params['id_card']
  562. );
  563. if ($res === false) {
  564. return [
  565. 'state' => false,
  566. 'msg' => $service->getError(),
  567. ];
  568. }
  569. }
  570. }
  571. }
  572. }
  573. if ($params['type'] == 'digital') {//数字化用工
  574. if (!$params['mobile']) {
  575. return [
  576. 'state' => false,
  577. 'msg' => '请填写支付宝绑定的手机号!'
  578. ];
  579. }
  580. if($params['bank_account_type'] == 2){
  581. $params['bank_account'] = $params['mobile'];
  582. }
  583. if($params['bank_account_type'] == 3){
  584. $findOpenId = UserInfo::find()->where(['user_id'=>$this->user_id, 'status'=>StatusEnum::ENABLED])->one();
  585. if(empty($findOpenId->openid)){
  586. return [
  587. 'state' => false,
  588. 'msg' => '该账号未绑定微信,无法使用微信提现方式!'
  589. ];
  590. }
  591. }
  592. // 是否签约
  593. $sign = DigitalEmploymentOrder::inquireSign($this->mall_id, $this->user_id);
  594. // 1-签约中 2-签约成功 3-签约失败
  595. if (empty($sign)) {
  596. return [
  597. 'state' => false,
  598. 'msg' => '该用户未进行签约!'
  599. ];
  600. }
  601. if($sign->result->signState == 1){
  602. return [
  603. 'state' => false,
  604. 'msg' => '该用户的签约正在审核中!'
  605. ];
  606. }
  607. if($sign->result->signState == 3){
  608. return [
  609. 'state' => false,
  610. 'msg' => '用户签约失败,请重新签约!'
  611. ];
  612. }
  613. }
  614. // 微信零钱打款
  615. if ($params['type'] == 'auto') {
  616. $payment_conf = Yii::$app->services->setting->mall->get($params['mall_id'], 'pay.wechat');
  617. $payment_conf = json_decode($payment_conf, true);
  618. if(!is_numeric($payment_conf['wechat_auto_pay_limit'])) $payment_conf['wechat_auto_pay_limit'] = 200;
  619. if($params['from'] == self::FROM_SCORE){//积分提现,需除以积分提现比例
  620. $payment = Yii::$app->services->setting->mall->get($params['mall_id'], 'score');
  621. $params['price'] = bcdiv($params['price'],$payment['score_cash_radio'],2);
  622. }
  623. if($params['price'] > $payment_conf['wechat_auto_pay_limit']){
  624. return [
  625. 'state' => false,
  626. 'msg' => '微信自动打款提现最高提现金额不能超过'.$payment_conf['wechat_auto_pay_limit'].'元'
  627. ];
  628. }
  629. }
  630. $cash = new self();
  631. $cash->mall_id = $params['mall_id'];
  632. $cash->user_id = $params['user_id'];
  633. $cash->num = $actual_num;
  634. $cash->source = $params['source']??'';
  635. $cash->actual_num = $actual_num;
  636. $cash->content = Json::encode(['user_content' => $params['content']]);
  637. $cash->from = $params['from'];
  638. $cash->type = $params['type'];
  639. $cash->extra = Json::encode([
  640. 'name' => !empty($params['name']) ? $params['name'] : '',
  641. 'mobile' => !empty($params['mobile']) ? $params['mobile'] : '',
  642. 'bank_name' => $params['bank_name'],
  643. 'bank_account' => (string)$params['bank_account'],
  644. 'bank_account_type' => $params['bank_account_type'],
  645. 'wechat_qrcode' => $params['wechat_qrcode'],
  646. 'id_card' => $params['id_card']?? '',
  647. 'receive_bank_chanel_no' => $params['receive_bank_chanel_no'] ?? '',
  648. 'x-app-platform' => $params['x-app-platform'] ?? '',
  649. 'bank_address' => !empty($params['bank_address']) ? $params['bank_address'] : '',
  650. 'idcard' => !empty($params['idcard']) ? $params['idcard'] : '',
  651. // 'settlementInfoId' => !empty($params['settlementInfoId']) ? $params['settlementInfoId'] : '', //点薪灵工结算单id
  652. ], JSON_UNESCAPED_UNICODE);
  653. $cash->sign = $params['sign'] ?? '';
  654. if ($poundage_ratio < 0 || $poundage_ratio > 100) {
  655. return [
  656. 'state' => false,
  657. 'msg' => '手续费设置不正确!'
  658. ];
  659. }
  660. //手续费
  661. $poundage = 0;
  662. if ($poundage_ratio > 0 && $poundage_ratio < 100) {
  663. //手续费:取小数点2位,截断
  664. $poundage = bcmul($poundage_ratio / 100, $actual_num, 2);
  665. $cash->actual_num = bcsub($actual_num, $poundage, 2);
  666. //只影响余额提现
  667. if ($params['from'] == self::FROM_BALANCE && $payment['received_full']) {
  668. //提现金额需要全额到账,重新计算提现金额(手续费额外从余额扣减)
  669. $new_num = bcadd($actual_num, $poundage, 2);
  670. if ($user_balance['balance'] < $new_num) {
  671. return [
  672. 'state' => false,
  673. 'msg' => '余额不足以扣除手续费!'
  674. ];
  675. }
  676. $params['price'] = $cash->num = $new_num;
  677. $cash->actual_num = $actual_num;
  678. }
  679. $cash->poundage_num = $poundage;
  680. $cash->poundage_ratio = $poundage_ratio;
  681. }
  682. // //点薪灵工发起结算订单
  683. // if ($params['type'] == 'linggong') {
  684. // $res = (new ApiRequestService())->addSettlement($cash);
  685. // if ($res['status'] == false) return $res;
  686. // }
  687. $score_money = 0;
  688. //扣除转积分的费用
  689. if ($exchange_score_ratio > 0 && $exchange_score_ratio < 100) {
  690. // 提现转积分扣除比例=balance_trans_score_rate,提现赠送积分比例=score_withdrawal_giving_ratio
  691. $giving_ratio = 1; //转增比例
  692. $scoreAssets = Yii::$app->services->setting->mall->get($params['mall_id'], 'score');
  693. if (!empty($scoreAssets)) {
  694. if (isset($scoreAssets['score_withdrawal_giving_ratio']) && $scoreAssets['score_withdrawal_giving_ratio'] > 0) $giving_ratio = $scoreAssets['score_withdrawal_giving_ratio'];
  695. }
  696. $score_money = bcmul($exchange_score_ratio / 100, $params['price'], 2); // 提现转积分扣除的手续费 = 转积分扣除的手续费比例 * 提现金额
  697. $exchange_score_num = $score_money * $giving_ratio; // 可得积分 = 提现转积分扣除的手续费 * 提现赠送积分比例
  698. $cash->actual_num = bcsub($cash->actual_num, $score_money, 2);
  699. $cash->exchange_score_num = $score_money;
  700. $cash->exchange_score_ratio = $exchange_score_ratio;
  701. $cash->give_score_num = $exchange_score_num;
  702. }
  703. if (intval(bcmul($cash->actual_num, 100)) < 1) {
  704. return [
  705. 'state' => false,
  706. 'msg' => '提现金额扣除费用后金额不足!'
  707. ];
  708. }
  709. $balance_money = 0;
  710. //扣除转余额的费用
  711. if (isset($trans_balance_rate) && $params['type'] != 'balance' && $trans_balance_rate > 0 && $trans_balance_rate < 100) {
  712. // 提现转积分扣除比例=balance_trans_score_rate,提现赠送积分比例=score_withdrawal_giving_ratio
  713. $balance_money = bcmul($trans_balance_rate / 100, $cash->actual_num, 2); // 提现转余额扣除的手续费 = 转余额扣除的手续费比例 * 剩余可提现金额
  714. $cash->actual_num = bcsub($cash->actual_num, $balance_money, 2);
  715. $cash->exchange_balance_num = $balance_money;
  716. $cash->exchange_balance_ratio = $trans_balance_rate;
  717. if (intval(bcmul($cash->actual_num, 100)) < 1) {
  718. return [
  719. 'state' => false,
  720. 'msg' => '提现金额扣除费用后金额不足!'
  721. ];
  722. }
  723. }
  724. //提现分佣金额
  725. $cash->direct_withdraws_reward_num = $direct_withdraws_reward;
  726. $cash->indirect_withdraws_reward_num = $indirect_withdraws_reward;
  727. $cash->direct_withdraws_reward_ratio = $direct_withdraws_reward_rate;
  728. $cash->indirect_withdraws_reward_ratio = $indirect_withdraws_reward_rate;
  729. $t = \Yii::$app->db->beginTransaction();
  730. try {
  731. $cash->order_no = $this->getCashOrder($params['mall_id']);
  732. //$desc = $cash->from == self::FROM_INCOME ? '佣金提现' : '余额提现';
  733. $desc = self::$from_msg[$cash->from].'提现';
  734. //$desc .= $cash->num;
  735. $desc .= $params['price'];
  736. if ($poundage > 0) {
  737. $desc .= ':手续费¥' . $poundage;
  738. }
  739. if ($score_money > 0) {
  740. $desc .= ' 转积分扣除¥' . $score_money;
  741. }
  742. if ($balance_money > 0) {
  743. $desc .= ' 转余额扣除¥' . $balance_money;
  744. }
  745. if (!$cash->save()) {
  746. throw new Exception($cash->getErrorMessage());
  747. }
  748. $res_data = [
  749. 'state' => true,
  750. 'data' => ['cash_id' => $cash->id],
  751. 'msg' => ''
  752. ];
  753. //提现限额
  754. $payment = \Yii::$app->services->setting->mall->get($cash->mall_id, 'withdraw_income');
  755. if (isset($withdraws_limit_enable)) {
  756. $payment["withdraws_limit_enable"] = $withdraws_limit_enable;
  757. }
  758. if($cash->from == 1 && !empty($payment["withdraws_limit_enable"])){
  759. $withdrawsLimitLogType = $withdrawsLimitLogType ?? 0;
  760. $withdraws_limit_money = $withdrawsLimitLogType == WithdrawsLimitLog::COMMON_LIMIT ? (isset($payment["withdraws_limit_money"]) ? $payment["withdraws_limit_money"] : 0) : ($payment["independent_balance_withdraw_max_amount"] ?? 0);
  761. $withdrawsLimitLog = WithdrawsLimitLog::findOne(['user_id' => $cash->user_id, 'status' => StatusEnum::ENABLED,'from'=>1, 'type' => $withdrawsLimitLogType]);
  762. $log_data = [
  763. 'mall_id' => $cash->mall_id,
  764. 'user_id' => $cash->user_id,
  765. 'amount' => $withdraws_limit_money,
  766. 'from' => 1,
  767. 'type' => $withdrawsLimitLogType
  768. ];
  769. if(empty($withdrawsLimitLog)){
  770. $withdrawsLimitLog = WithdrawsLimitLog::setData($log_data);
  771. if(!$withdrawsLimitLog){
  772. throw new \Exception();
  773. }
  774. }
  775. $withdrawsLimitLog->amount = bcsub($withdrawsLimitLog->amount,$cash->num,2);
  776. if(!$withdrawsLimitLog->save()){
  777. throw new \Exception();
  778. }
  779. $log_data['amount'] = $cash->num;
  780. $log_data['withdraw_log_id'] = $cash->id;
  781. $withdrawsLimitChangeLog = WithdrawsLimitChangeLog::setData($log_data);
  782. if(!$withdrawsLimitChangeLog){
  783. throw new \Exception();
  784. }
  785. }
  786. //扣除冻结红包
  787. if ($params['from'] == self::FROM_INCOME && $deduct_equal_frozen_redpack && $install_redpack) {
  788. $config = Yii::$app->services->setting->addons->get($params['mall_id'], AddonsEnum::ADDONS_NAME_REDPACK, 'basic');
  789. $redpack_name = $config['redpack_name'] ?? '红包';// 自定义红包名称
  790. $wallet = RedpackWallet::setData([
  791. 'mall_id' => $params['mall_id'],
  792. 'user_id' => $params['user_id'],
  793. 'is_frozen' => true,
  794. 'is_deduct' => true,
  795. 'money' => $params['price'] * -1,
  796. 'from_type' => RedpackEnum::FROM_CASH_DEDUCT,
  797. 'desc' => "佣金提现扣除等额冻结".$redpack_name,
  798. 'source_table' => self::tableName(),
  799. 'source_table_id' => $cash->id,
  800. ]);
  801. if(!$wallet) throw new \Exception(RedpackWallet::getStaticError());
  802. }
  803. $t->commit();
  804. $data = [
  805. 'message_id' => 0, 'mall_id' => $params['mall_id'], 'user_id' => $params['user_id'],
  806. 'wallet_type' => $wallet_type,
  807. 'is_frozen' => false, 'unfrozen' => false, 'money' => -abs($params['price']),
  808. 'desc' => $desc, 'source_table' => 'user_wallet', 'source_table_id' => $cash->id,
  809. 'from_type' => UserWalletEnum::WITHDRAWAL,
  810. // 'capital_type' => $params['from'] == self::FROM_BALANCE ? UserWalletEnum::WITHDRAWAL_DECR : UserWalletEnum::RECHARGE_COMMISSION,
  811. 'capital_type' => UserWalletEnum::WITHDRAWAL_DECR,
  812. ];
  813. $wallet_service_status = UserWalletService::handle(0, $data);
  814. if ($params['from'] == self::FROM_INCOME && $deduct_equal_points == 1) {
  815. $score_data = [
  816. 'message_id' => 0, 'mall_id' => $params['mall_id'], 'user_id' => $params['user_id'],
  817. 'wallet_type' => 'score',
  818. 'is_frozen' => false, 'unfrozen' => false, 'money' => -abs($cash->num),
  819. 'desc' => $desc, 'source_table' => 'user_wallet', 'source_table_id' => $cash->id,
  820. 'from_type' => UserWalletEnum::WITHDRAWAL,
  821. 'capital_type' => UserWalletEnum::WITHDRAWAL_FOLLOW_DECR,
  822. ];
  823. UserWalletService::handle(0, $score_data);
  824. }
  825. if (!$wallet_service_status) {
  826. $cash->status = 4;
  827. $cash->save();
  828. return [
  829. 'state' => false,
  830. 'msg' => '提现失败!' . UserWalletService::getStaticError()
  831. ];
  832. }
  833. //佣金提现到余额免审核
  834. if ($cash->type == 'balance' && $cash->from == self::FROM_INCOME && isset($payment['is_examine']) && $payment['is_examine']) {
  835. $this->remit($cash);
  836. // 如果是提现的余额,通知余额变动
  837. $user_wallet_list = ['user_id' => $cash->user_id, 'wallet_type' => UserWalletService::WALLET_TYPE_BALANCE];
  838. $event = new UserWalletEvent($cash->mall_id);
  839. Yii::$app->services->events->dispatch($event, ['mall_id'=>$cash->mall_id, 'user_wallet_list' => $user_wallet_list], $event->listeners);
  840. $event = new UserWithdrawSuccessfulEvent($cash->mall_id);
  841. $data['id'] = $cash->id;
  842. $data['mall_id'] = $cash->mall_id;
  843. Yii::$app->services->events->dispatch($event, $data, $event->listeners);
  844. }
  845. if ($cash->type == 'joinpay') {
  846. //获取汇聚代付配置
  847. $huiju_config = \Yii::$app->services->setting->addons->get($this->mall_id, AddonsEnum::ADDONS_NAME_JOIN_PAY, 'basic');
  848. if (!empty($huiju_config['joinpay_channel_alternative'])) $huiju_config['joinpay_channel_alternative'] = json_decode($huiju_config['joinpay_channel_alternative'], true);
  849. if ($huiju_config['not_to_examine'] == 1 && !empty($huiju_config['joinpay_channel_alternative']) && in_array($cash->from, $huiju_config['joinpay_channel_alternative'])) {
  850. $this->remit($cash);
  851. }
  852. }
  853. //灵工点薪免审核打款
  854. // if ($cash->type == 'linggong') {
  855. // $config = \Yii::$app->services->setting->addons->get($cash->mall_id, AddonsEnum::ADDONS_NAME_LINGGONG, 'basic');
  856. // if (!empty($config) && $config['is_examine'] == 1) {
  857. // $this->remit($cash);
  858. // }
  859. // }
  860. $event = new UserWithdrawEvent($cash->mall_id);
  861. Yii::$app->services->events->dispatch($event, ['mall_id'=>$cash->mall_id, 'id' => $cash['id']], $event->listeners);
  862. } catch (Exception $e) {
  863. $t->rollBack();
  864. \Yii::error($e->getMessage());
  865. return [
  866. 'state' => false,
  867. 'msg' => '提现失败!' . $e->getMessage()
  868. ];
  869. }
  870. return $res_data;
  871. }
  872. public function getCashOrder($mall_id): string
  873. {
  874. $order_no = null;
  875. while (true) {
  876. $order_no = 'TX' . date('YmdHis') . rand(10000, 99999);
  877. $exist = self::find()->where(['mall_id' => $mall_id, 'order_no' => $order_no,])->asArray()->one();
  878. if (!$exist) {
  879. break;
  880. }
  881. }
  882. return $order_no;
  883. }
  884. /**
  885. * User: wniu
  886. * Date: 2021/11/1
  887. * Time: 4:28 下午
  888. * *
  889. * @param $get
  890. * @return array
  891. */
  892. public function searchLogList($get): array
  893. {
  894. $mall_id = $get['mall_id'];
  895. $params['alias'] = 'b';
  896. $params['joinWith'] = ['user'];
  897. $params['where'][] = ['!=', 'b.status', -1];
  898. if ($get['status'] && $get['status'] >= 0) {
  899. $params['where'][] = ['=', 'b.status', $get['status']];
  900. }
  901. if ($get['status'] == 0) {
  902. $params['where'][] = ['=', 'b.status', $get['status']];
  903. }
  904. if (!empty($get['keyword'])) {
  905. $params['where'] = [[
  906. 'or',
  907. ['like', 'nickname', $get['keyword']],
  908. ['like', 'mobile', $get['keyword']]
  909. ]];
  910. }
  911. if (!empty($get['user_id'])) {
  912. $params['where'][] = ['=', 'user_id', $get['user_id']];
  913. }
  914. if (!empty($get['id'])) {
  915. $params['where'][] = ['=', 'b.id', $get['id']];
  916. }
  917. if (!empty($get['withdraw_type'])) {
  918. $params['where'][] = ['=', 'b.type', $get['withdraw_type']];
  919. }
  920. if (!empty($get['withdraw_from'])) {
  921. $params['where'][] = ['=', 'b.from', $get['withdraw_from']];
  922. }
  923. if (!empty($get['start_date']) && !empty($get['end_date'])) {
  924. $get['start_date'] = str_replace('+', ' ', $get['start_date']);
  925. $get['end_date'] = str_replace('+', ' ', $get['end_date']);
  926. $params['where'][] = ['>=', 'b.created_at', strtotime($get['start_date'])];
  927. $params['where'][] = ['<=', 'b.created_at', strtotime($get['end_date'])];
  928. }
  929. $params['where'][] = ['=', 'b.mall_id', $mall_id];
  930. $params['order'] = ['status' => SORT_ASC, 'updated_at' => SORT_DESC];
  931. $params['limit'] = 10;
  932. $isChanjet = !empty($get['is_chanjet_addons']);
  933. // 畅捷通插件相关
  934. if ($isChanjet) {
  935. $params['with'][] = 'addonsChanjetRequest';
  936. }
  937. $list = self::listPage($params, false, false);
  938. $newList = [];
  939. $joinpay_msg = '';
  940. if(MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_HUI_DIAN)){
  941. $huidian_from_msg = \Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_HUI_DIAN, 'basic.custom_name');
  942. }
  943. foreach ($list['list'] as $item) {
  944. $serviceCharge = $item->poundage_num;
  945. $fact_price = $item->actual_num;
  946. $score_money = $item->exchange_score_num;
  947. $extra = $item->extra ? json_decode($item->extra, true) : [];
  948. if (!empty($extra)) $extra['bank_account'] = (string)$extra['bank_account'];
  949. if ($item->type == 'paid' || $item->type == 'joinpay') {
  950. //汇聚代付
  951. $pay_log = PaidSinglePayLog::getOne([['mall_id' => $item->mall_id, 'order_no' => $item->order_no]],false,[],'id desc');
  952. if ($pay_log) {
  953. if ($pay_log->status == PaidSinglePayLog::STATUS_SUCCESS) {
  954. $joinpay_msg = '打款成功';
  955. } else {
  956. $joinpay_msg = $pay_log->error_msg ?: '打款中';
  957. }
  958. }
  959. }
  960. if (isset($item->addonsChanjetRequest)) {
  961. $addonsChanjetRequest = $item->addonsChanjetRequest ?
  962. ['updated_at' => $item->addonsChanjetRequest->updated_at, 'request_status' => $item->addonsChanjetRequest->request_status] :
  963. null;
  964. }
  965. $from_msg = self::$from_msg[$item->from];
  966. if($item->from == self::FROM_SCORE_GAME && MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_SCORE_GAME)){
  967. $wallet_text = ScoreGameEnum::getWalletText();
  968. $from_msg = $from_msg.' - '.$wallet_text[$item->source];
  969. }
  970. if ($item->from == self::FROM_HUIDIAN) {
  971. $from_msg = $huidian_from_msg ?? '惠点';
  972. }
  973. $newItem = [
  974. 'id' => $item->id,
  975. 'from' => $item->from,
  976. 'order_no' => $item->order_no,
  977. 'type' => $item->type,
  978. 'status' => $item->status,
  979. 'extra' => $extra,
  980. 'created_at' => $item->created_at,
  981. 'updated_at' => $item->updated_at,
  982. 'addonsChanjetRequest' => $addonsChanjetRequest ?? null,
  983. 'content' => $item->content ? Json::decode($item->content) : [],
  984. 'user' => [
  985. 'avatar' => isset($item->user->avatar_url) ? $item->user->avatar_url : '',
  986. 'nickname' => isset($item->user->nickname) ? $item->user->nickname : '',
  987. 'id' => isset($item->user->id) ? $item->user->id : '',
  988. 'mobile' => isset($item->user->mobile) ? $item->user->mobile : '',
  989. ],
  990. 'cash' => [
  991. 'price' => round($item->num, 2),
  992. 'service_fee_rate' => $serviceCharge,
  993. 'score_money' => $score_money,
  994. 'fact_price' => $fact_price,
  995. 'exchange_balance_num' => $item->exchange_balance_num
  996. ],
  997. 'joinpay_msg' => $joinpay_msg,
  998. 'from_msg' => $from_msg.'提现'
  999. ];
  1000. $newList[] = $newItem;
  1001. }
  1002. $export_list = self::fieldsList(null, $isChanjet);
  1003. return [
  1004. 'code' => 0,
  1005. 'data' => [
  1006. 'list' => $newList,
  1007. 'export_list' => $export_list,
  1008. 'pagination' => $list['pagination'],
  1009. ]
  1010. ];
  1011. }
  1012. /**
  1013. * @throws Exception
  1014. */
  1015. public function updateLog(): bool
  1016. {
  1017. $where = [['id' => $this->id]];
  1018. $cash = self::getOne($where);
  1019. if (!$cash) {
  1020. throw new \Exception('提现记录不存在');
  1021. }
  1022. if ($cash->status == 2) {
  1023. throw new \Exception('提现已打款');
  1024. }
  1025. if ($cash->status == 3) {
  1026. throw new \Exception('提现已被驳回');
  1027. }
  1028. if ($this->status <= $cash->status) {
  1029. throw new \Exception('状态错误, 请刷新重试');
  1030. }
  1031. $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_USER_CASH, $cash->user_id);
  1032. $identification = uniqid();
  1033. if (!LockHelper::lock($lock_key, $identification, 100, 100)) {
  1034. \Yii::error('cashForm 获取锁(' . $lock_key . ')失败阻塞,提现打款:cash,操作:save,金额:' . $cash->actual_num);
  1035. return false;
  1036. }
  1037. $t = \Yii::$app->db->beginTransaction();
  1038. try {
  1039. switch ($this->status) {// 1=提现申请通过,2=同意提现,3=拒绝提现
  1040. case 1:
  1041. $this->validateCash($cash);
  1042. break;
  1043. case 2:
  1044. $this->remit($cash);
  1045. $flag = true;
  1046. break;
  1047. case 3:
  1048. $this->reject($cash);
  1049. break;
  1050. default:
  1051. throw new \Exception('错误的提现类型');
  1052. }
  1053. $t->commit();
  1054. LockHelper::uLock($lock_key, $identification);
  1055. if (isset($flag)) {
  1056. // 如果是提现的余额,通知余额变动 或 余额提现到第三方
  1057. if ($cash->type === 'balance' || $cash->from == self::FROM_BALANCE) {
  1058. $user_wallet_list = ['user_id' => $cash->user_id, 'wallet_type' => UserWalletService::WALLET_TYPE_BALANCE];
  1059. $event = new UserWalletEvent($cash->mall_id);
  1060. Yii::$app->services->events->dispatch($event, ['mall_id'=>$cash->mall_id, 'user_wallet_list' => $user_wallet_list], $event->listeners);
  1061. }
  1062. $event = new UserWithdrawSuccessfulEvent($cash->mall_id);
  1063. $data['id'] = $cash->id;
  1064. $data['mall_id'] = $cash->mall_id;
  1065. Yii::$app->services->events->dispatch($event, $data, $event->listeners);
  1066. }
  1067. // 执行成功后触发插件操作
  1068. GlobalInvoke::exec(GlobalInvoke::INVOKE_WITHDRAW_OPERATE, $cash->mall_id, $cash->toArray());
  1069. if($this->status==3){
  1070. //用户提现审核不通过事件
  1071. $event = new UserWithdrawRejectEvent($cash->mall_id);
  1072. $data['id'] = $cash->id;
  1073. $data['mall_id'] = $cash->mall_id;
  1074. Yii::$app->services->events->dispatch($event, $data, $event->listeners);
  1075. }
  1076. } catch (\Exception $exception) {
  1077. $t->rollBack();
  1078. LockHelper::uLock($lock_key, $identification);
  1079. \Yii::error("finance cashForm error=" . $exception->getFile() . ";line:" . $exception->getLine() . ";message:" . $exception->getMessage());
  1080. throw new \Exception($exception->getMessage());
  1081. }
  1082. return true;
  1083. }
  1084. /**
  1085. * 申请
  1086. * @param $cash
  1087. * @return bool
  1088. * @throws Exception
  1089. */
  1090. private function validateCash($cash): bool
  1091. {
  1092. if (!$cash->content) {
  1093. $content = [];
  1094. } else {
  1095. $content = Json::decode($cash->content);
  1096. }
  1097. $cash->status = 1;
  1098. $content['validate_content'] = $this->content ?: '审核通过';
  1099. $cash->content = Json::encode($content);
  1100. if (!$cash->save()) {
  1101. throw new \Exception('失败');
  1102. }
  1103. return true;
  1104. }
  1105. /**
  1106. * @Author: 广东七件事 ganxiaohao
  1107. * @Date: 2020-05-30
  1108. * @Time: 11:22
  1109. * @Note:拒绝
  1110. * @param $cash
  1111. * @return void
  1112. * @throws \Exception
  1113. */
  1114. private function reject($cash): void
  1115. {
  1116. if (!$this->content) {
  1117. throw new \Exception('请填写备注');
  1118. }
  1119. if (!$cash->content) {
  1120. $content = [];
  1121. } else {
  1122. $content = Json::decode($cash->content);
  1123. }
  1124. $cash->status = 3;
  1125. $content['reject_content'] = $this->content;
  1126. $cash->content = Json::encode($content);
  1127. if (!$cash->save()) {
  1128. throw new \Exception('失败');
  1129. }
  1130. $from = $cash->from;
  1131. $cash_num = $cash->num;
  1132. if ($from == self::FROM_INCOME) {
  1133. $desc = "佣金申请提现被驳回,驳回原因:" . $this->content ?? '';
  1134. $wallet_type = UserWalletService::WALLET_TYPE_COMMISSION;
  1135. }elseif ($from == self::FROM_SCORE) {
  1136. $desc = "积分申请提现被驳回,驳回原因:" . $this->content ?? '';
  1137. $wallet_type = UserWalletService::WALLET_TYPE_SCORE;
  1138. //原路返回积分数量查询 积分记录表
  1139. $score_log = ScoreLog::find()->where(['user_id' => $cash->user_id, 'from_type' => UserWalletEnum::WITHDRAWAL, 'source_table' => 'user_wallet', 'source_table_id' => $cash->id])->asArray()->one();
  1140. $cash_num = $score_log['change_num'] ?? 0;
  1141. }elseif ($from == self::FROM_SCORE_GAME) {
  1142. //插件提现
  1143. } elseif ($from == self::FROM_HUIDIAN) {
  1144. //惠点插件提现驳回
  1145. $log = \addons\HuiDian\common\models\HuidianLog::getOne([
  1146. ['mall_id' => $cash->mall_id],
  1147. ['user_id' => $cash->user_id],
  1148. ['from_type' => \addons\HuiDian\common\enums\HuiDianEnum::FROEM_TYPE_WITHDRAWS_SUBMIT],
  1149. ['source_table' => self::tableName()],
  1150. ['source_table_id' => $cash->id]
  1151. ]);
  1152. if ($log) {
  1153. $res = \addons\HuiDian\common\models\Huidian::setData([
  1154. 'mall_id' => $log['mall_id'],
  1155. 'user_id' => $log['user_id'],
  1156. 'amount' => $log['change_num'],
  1157. 'desc' => "提现申请被驳回,驳回原因:" . $this->content ?? '',
  1158. 'source_table' => self::tableName(),
  1159. 'source_table_id' => $cash->id,
  1160. 'from_type' => \addons\HuiDian\common\enums\HuiDianEnum::FROEM_TYPE_WITHDRAWS_REJECT,
  1161. 'is_withdraw_reject' => true
  1162. ]);
  1163. if ($res === false) throw new \Exception();
  1164. }
  1165. } else {
  1166. $desc = "余额提现申请被驳回,驳回原因:" . $this->content ?? '';
  1167. $wallet_type = UserWalletService::WALLET_TYPE_BALANCE;
  1168. }
  1169. if($wallet_type){
  1170. $data = [
  1171. 'message_id' => 0,
  1172. 'mall_id' => $cash->mall_id, 'user_id' => $cash->user_id,
  1173. 'wallet_type' => $wallet_type, 'is_frozen' => false,
  1174. 'unfrozen' => false, 'money' => abs($cash_num), 'desc' => $desc,
  1175. 'source_table' => AssetsType::CASH_OUT_REFUND, 'source_table_id' => $cash->id,
  1176. 'from_type' => UserWalletEnum::WITHDRAWAL,
  1177. 'capital_type' => UserWalletEnum::WITHDRAWAL_REFUND,
  1178. 'no_change_field' => ['total_commission']
  1179. ];
  1180. UserWalletService::handle(0, $data);
  1181. }
  1182. if ($from == self::FROM_INCOME) {
  1183. // 处理被扣除积分退回
  1184. CapitalLog::$capitalType = 'score';
  1185. $logs = CapitalLog::lists([
  1186. 'where' => [
  1187. ['mall_id' => $cash->mall_id],
  1188. ['user_id' => $cash->user_id],
  1189. ['from_type' => UserWalletEnum::WITHDRAWAL],
  1190. ['capital_type' => UserWalletEnum::WITHDRAWAL_FOLLOW_DECR],
  1191. ['source_table_id' => $cash->id],
  1192. ],
  1193. 'select' => 'user_id,from_type,change_num'
  1194. ]);
  1195. if ($logs) {
  1196. $log = $logs[0];
  1197. $change_num = abs($log['change_num']);
  1198. $score_name = \Yii::$app->services->setting->mall->get($cash->mall_id, 'score.score_name');
  1199. $desc = "佣金申请提现被驳回,{$change_num}{$score_name}原路退回";
  1200. $data = [
  1201. 'message_id' => 0,
  1202. 'mall_id' => $cash->mall_id, 'user_id' => $cash->user_id,
  1203. 'wallet_type' => 'score', 'is_frozen' => false,
  1204. 'unfrozen' => false, 'money' => $change_num, 'desc' => $desc,
  1205. 'source_table' => AssetsType::CASH_OUT_REFUND, 'source_table_id' => $cash->id,
  1206. 'from_type' => UserWalletEnum::WITHDRAWAL,
  1207. 'capital_type' => UserWalletEnum::WITHDRAWAL_REFUND,
  1208. ];
  1209. UserWalletService::handle(0, $data);
  1210. }
  1211. //返还冻结红包
  1212. $this->reject_redpack($cash);
  1213. //处理被扣除提现额度
  1214. $withdrawsLimitChangeLog = WithdrawsLimitChangeLog::findOne(['withdraw_log_id' => $cash->id, 'status' => StatusEnum::ENABLED,'from'=>1]);
  1215. if(!empty($withdrawsLimitChangeLog)){
  1216. $payment = \Yii::$app->services->setting->mall->get($cash->mall_id, 'withdraw_income');
  1217. $withdrawsLimitLog = WithdrawsLimitLog::findOne(['user_id' => $cash->user_id, 'status' => StatusEnum::ENABLED,'from'=>1, 'type' => $withdrawsLimitChangeLog->type]);
  1218. if(!empty($withdrawsLimitLog)){
  1219. $withdraws_limit_money = $withdrawsLimitChangeLog->type == WithdrawsLimitLog::BALANCE_LIMIT ?
  1220. ($payment["independent_balance_withdraw_max_amount"] ?? 0) :
  1221. (isset($payment["withdraws_limit_money"]) ? $payment["withdraws_limit_money"] : 0);
  1222. $withdrawsLimitLog->amount = bcadd($withdrawsLimitLog->amount,$cash->num,2);
  1223. if($withdrawsLimitLog->amount > $withdraws_limit_money){
  1224. $withdrawsLimitLog->amount = $withdraws_limit_money;
  1225. }
  1226. if(!$withdrawsLimitLog->save()){
  1227. throw new \Exception();
  1228. }
  1229. $withdrawsLimitChangeLog->status = StatusEnum::DISABLED;
  1230. if(!$withdrawsLimitChangeLog->save()){
  1231. throw new \Exception();
  1232. }
  1233. }
  1234. }
  1235. }
  1236. }
  1237. public function getUser(): \yii\db\ActiveQuery
  1238. {
  1239. return $this->hasOne(User::class, ['id' => 'user_id']);
  1240. }
  1241. /**
  1242. * @throws Exception
  1243. */
  1244. private function remit($cash): void
  1245. {
  1246. $res = false;
  1247. if ($cash->type === 'auto') {
  1248. //todo 待测试联调
  1249. /**
  1250. * @var UserInfo $userInfo ;
  1251. */
  1252. $userInfo = UserInfo::getOne([["user_id" => $cash->user_id, "platform" => [User::PLATFORM_WECHAT, User::PLATFORM_MP_WX], "status" => StatusEnum::ENABLED]]);
  1253. if (empty($userInfo)) {
  1254. throw new \Exception('该用户不存在微信相关信息!');
  1255. }
  1256. // $wechatPaySetting = OptionLogic::get(Option::NAME_PAYMENT, \Yii::$app->mall->id, Option::GROUP_APP);
  1257. // if (!$wechatPaySetting) {
  1258. // throw new \Exception('系统未开启微信支付!');
  1259. // }
  1260. // if (!$wechatPaySetting['wechat_status']) {
  1261. // throw new \Exception('系统未开启微信支付!');
  1262. // }
  1263. try {
  1264. $payment = new PayService();
  1265. $paymentTransfer = new PaymentTransfer();
  1266. $paymentTransfer->orderNo = PaymentTransfer::generate_order_no("TR");
  1267. $paymentTransfer->user = $userInfo;
  1268. $paymentTransfer->title = "收益提现";
  1269. $paymentTransfer->amount = $cash->actual_num;
  1270. $paymentTransfer->withdrawal_source = 'UserWithdrawLog';
  1271. $paymentTransfer->withdrawal_source_id = $cash->id;
  1272. $paymentTransfer->transferType = PayTypeEnum::WECHAT;
  1273. // $paymentTransfer->transferType = PaymentTransfer::TRANSFER_TYPE_WECHAT;
  1274. $paymentTransfer->cashInfo = $cash;
  1275. $res = $payment->transfer($paymentTransfer);
  1276. } catch (Exception $e) {
  1277. throw new \Exception($e->getMessage());
  1278. }
  1279. } else if ($cash->type === 'balance') {
  1280. $userInfo = User::getOne([['id' => $cash->user_id, 'status' => StatusEnum::ENABLED]]);
  1281. if (!$userInfo) {
  1282. throw new \Exception('该用户不存在!');
  1283. }
  1284. $desc = "用户收益提现到余额:" . $cash->actual_num . "元";
  1285. $data = [
  1286. 'message_id' => 0,
  1287. 'mall_id' => $cash->mall_id, 'user_id' => $cash->user_id,
  1288. 'wallet_type' => UserWalletService::WALLET_TYPE_BALANCE,
  1289. 'is_frozen' => false, 'unfrozen' => false, 'money' => abs($cash->actual_num), 'desc' => $desc,
  1290. 'source_table' => AssetsType::CASH_OUT, 'source_table_id' => $cash->id,
  1291. 'from_type' => UserWalletEnum::RECHARGE,
  1292. 'capital_type' => UserWalletEnum::RECHARGE_COMMISSION,
  1293. ];
  1294. $res = UserWalletService::handle(0, $data);
  1295. //免审核,免打款
  1296. $withdraw_config = \Yii::$app->services->setting->mall->get($cash->mall_id, 'withdraw_income');
  1297. if (isset($withdraw_config['is_examine']) && $withdraw_config['is_examine']) {
  1298. $cash->content = Json::encode(['validate_content' => '提现免审核,免打款']);
  1299. }
  1300. } elseif ($cash->type === 'paid' || $cash->type === 'joinpay') { //代付
  1301. $res = GlobalInvoke::exec(GlobalInvoke::INVOKE_WITHDRAW_EXTENSION_PAY, $cash->mall_id, ['cash' => $cash]);
  1302. if ($res) {
  1303. // 提交成功
  1304. self::remit_wait($cash, "提交成功");
  1305. return;
  1306. } else {
  1307. // 提交失败
  1308. $msg = '代付打款失败';
  1309. throw new \Exception($msg);
  1310. }
  1311. } else if ($cash->type == 'alipay_offline' || $cash->type == 'wechat' || $cash->type == 'bank') { //线下转账
  1312. $res = true;
  1313. } else if ($cash->type == 'digital') {
  1314. $ids = [
  1315. $cash->id
  1316. ];
  1317. $pay_res = GlobalInvoke::exec(GlobalInvoke::INVOKE_WITHDRAW_AVOIDTAX_PAY,$cash->mall_id,[
  1318. 'ids'=>$ids,
  1319. 'mall_id'=>$cash->mall_id
  1320. ]);
  1321. if($pay_res){
  1322. // 提交成功
  1323. self::remit_wait($cash,"提交成功");
  1324. return;
  1325. }else{
  1326. // 提交失败
  1327. $msg = '代付打款失败';
  1328. throw new \Exception($msg);
  1329. }
  1330. } else if ($cash->type === 'bank_tax') { // 银企直连
  1331. $data['mall_id'] = $cash->mall_id;
  1332. $data['log_id'] = $cash->id;
  1333. $service = new WithdrawalService($data);
  1334. $banktaxToPay = $service->banktaxToPay();
  1335. if ($banktaxToPay === false) {
  1336. $msg = '银企直连打款失败';
  1337. Yii::$app->custom->logs('提现到银企直连失败', ['err' => $service->error, 'cash' => $cash]);
  1338. throw new \Exception($msg);
  1339. }
  1340. Yii::$app->custom->logs('提现到银企直连成功', ['res' => $banktaxToPay, 'cash' => $cash]);
  1341. return;
  1342. } else if ($cash->type === 'linggong') { //点薪灵工
  1343. $data['mall_id'] = $cash->mall_id;
  1344. $data['log_id'] = $cash->id;
  1345. $service = new WithdrawalService($data);
  1346. $linggongToPay = $service->linggongToPay();
  1347. if ($linggongToPay === false) {
  1348. $msg = '点薪灵工打款失败';
  1349. Yii::$app->custom->logs('提现到点薪灵工失败', ['err' => $service->error, 'cash' => $cash]);
  1350. throw new \Exception($msg);
  1351. }
  1352. Yii::$app->custom->logs('提现到点薪灵工成功', ['res' => $linggongToPay, 'cash' => $cash]);
  1353. return;
  1354. }
  1355. if ($res) {
  1356. self::remit_success($cash);
  1357. try {
  1358. $obj = new WechatMessageLogic();
  1359. $obj->withdrawalSuccessSendMessage(['mall_id'=>$cash->mall_id,'user_id'=>$cash->user_id,'money'=>$cash->actual_num]);
  1360. }catch (\Exception $e){
  1361. }
  1362. }else{
  1363. $msg = '打款失败';
  1364. throw new \Exception($msg);
  1365. }
  1366. }
  1367. /**
  1368. * 明确打款成功
  1369. *
  1370. * @param UserWithdrawLog $cash
  1371. * @param string $msg
  1372. * @return void
  1373. */
  1374. public static function remit_success(UserWithdrawLog $cash, $msg = '打款成功')
  1375. {
  1376. // 保存提现信息
  1377. if ($cash->content) {
  1378. $content = Json::decode($cash->content);
  1379. } else {
  1380. $content = [];
  1381. }
  1382. $cash->status = 2;
  1383. $content['remit_at'] = date('Y-m-d H:i:s', time());
  1384. $content['remit_content'] = $msg;
  1385. $cash->content = Json::encode($content);
  1386. if (!$cash->save()) {
  1387. throw new \Exception();
  1388. }
  1389. $user_wallet_model = UserWallet::findOne(['user_id' => $cash->user_id, 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
  1390. if ($cash->from == 1) { //佣金
  1391. $user_wallet_model->commission_withdrawal += $cash->num;
  1392. } else { //余额
  1393. $user_wallet_model->balance_withdrawal += $cash->num;
  1394. }
  1395. if (!$user_wallet_model->save()) {
  1396. throw new \Exception();
  1397. }
  1398. $user = [];
  1399. //获取收益提现配置
  1400. $withdraw_income_config = \Yii::$app->services->setting->mall->get($cash->mall_id, 'withdraw_income');
  1401. if ($withdraw_income_config['level_withdrwas_reward_type'] == 1) { // 全局设置
  1402. if ($cash->direct_withdraws_reward_num > 0 || $cash->indirect_withdraws_reward_num > 0) {
  1403. $user = User::getOne([['id' => $cash->user_id]]);
  1404. }
  1405. } else { // 独立设置
  1406. $user = User::getOne([['id' => $cash->user_id]]);
  1407. }
  1408. // print_r($withdraw_income_config);exit;
  1409. if (!empty($withdraw_income_config['level_withdrwas_reward'])) $withdraw_income_config['level_withdrwas_reward'] = json_decode($withdraw_income_config['level_withdrwas_reward'], true);
  1410. if (!empty($withdraw_income_config['indep_withdrwas_reward'])) $withdraw_income_config['indep_withdrwas_reward'] = json_decode($withdraw_income_config['indep_withdrwas_reward'], true);
  1411. //发放提现直推奖
  1412. $can_reward = 1;
  1413. $parent_id = $user->parent_id;
  1414. if ($cash->from == 1) {
  1415. $parent_user = User::find()->where(['mall_id' => $cash->mall_id, 'id' => $parent_id, 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]])->with(['userLevelTwo'])->asArray()->one();
  1416. if ($withdraw_income_config['level_withdrwas_reward_type'] == 1) {
  1417. //查询上级等级
  1418. if (!empty($withdraw_income_config['level_withdrwas_reward'])) {
  1419. if (!in_array($parent_user['level'], $withdraw_income_config['level_withdrwas_reward'])) $can_reward = 0;
  1420. }
  1421. } else if ($withdraw_income_config['level_withdrwas_reward_type'] == 2) {
  1422. if (!empty($withdraw_income_config['indep_withdrwas_reward'][$parent_user['level']])) {
  1423. $can_reward = 1;
  1424. $cash->direct_withdraws_reward_num = intval(bcmul($cash->num * $withdraw_income_config['indep_withdrwas_reward'][$parent_user['level']]['direct_withdraws_reward'] / 100, 100)) / 100;
  1425. } else {
  1426. $can_reward = 0;
  1427. }
  1428. // print_r($withdraw_income_config['indep_withdrwas_reward']);exit;
  1429. }
  1430. }
  1431. if ($cash->direct_withdraws_reward_num > 0) {
  1432. if (!empty($parent_id) && $can_reward == 1) {
  1433. $desc = "下级用户({$cash->user_id})提现({$cash->order_no}),发放直推奖励";
  1434. $data = [
  1435. 'message_id' => 0,
  1436. 'mall_id' => $cash->mall_id, 'user_id' => $parent_id,
  1437. 'wallet_type' => $cash->from == 1 ? UserWalletService::WALLET_TYPE_COMMISSION : UserWalletService::WALLET_TYPE_BALANCE,
  1438. 'is_frozen' => false, 'unfrozen' => false,
  1439. 'money' => abs($cash->direct_withdraws_reward_num), 'desc' => $desc,
  1440. 'source' => AssetsType::CASH_OUT,
  1441. 'source_id' => $cash->id,
  1442. 'from_type' => UserWalletEnum::REWARD,
  1443. 'capital_type' => UserWalletEnum::DIRECT_REWARD
  1444. ];
  1445. UserWalletService::handle(0, $data);
  1446. }
  1447. }
  1448. //发放提现间推奖
  1449. $can_reward = 1;
  1450. $second_parent_id = $user->second_parent_id;
  1451. if ($cash->from == 1) {
  1452. $second_parent_user = User::find()->where(['mall_id' => $cash->mall_id, 'id' => $second_parent_id, 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]])->asArray()->one();
  1453. if ($withdraw_income_config['level_withdrwas_reward_type'] == 1) {
  1454. //查询上级等级
  1455. if (!empty($withdraw_income_config['level_withdrwas_reward'])) {
  1456. if (!in_array($second_parent_user['level'], $withdraw_income_config['level_withdrwas_reward'])) $can_reward = 0;
  1457. }
  1458. } else if ($withdraw_income_config['level_withdrwas_reward_type'] == 2) {
  1459. if (!empty($withdraw_income_config['indep_withdrwas_reward'][$second_parent_user['level']])) {
  1460. $can_reward = 1;
  1461. $cash->indirect_withdraws_reward_num = intval(bcmul($cash->num * $withdraw_income_config['indep_withdrwas_reward'][$second_parent_user['level']]['indirect_withdraws_reward'] / 100, 100)) / 100;
  1462. } else {
  1463. $can_reward = 0;
  1464. }
  1465. }
  1466. }
  1467. if ($cash->indirect_withdraws_reward_num > 0) {
  1468. if (!empty($second_parent_id) && $can_reward == 1) {
  1469. $desc = "下下级用户({$cash->user_id})提现({$cash->order_no}),发放间推奖励";
  1470. $data = [
  1471. 'message_id' => 0,
  1472. 'mall_id' => $cash->mall_id, 'user_id' => $second_parent_id,
  1473. 'wallet_type' => $cash->from == 1 ? UserWalletService::WALLET_TYPE_COMMISSION : UserWalletService::WALLET_TYPE_BALANCE,
  1474. 'is_frozen' => false, 'unfrozen' => false,
  1475. 'money' => abs($cash->indirect_withdraws_reward_num), 'desc' => $desc,
  1476. 'source' => AssetsType::CASH_OUT, 'source_id' => $cash->id,
  1477. 'from_type' => UserWalletEnum::REWARD,
  1478. 'capital_type' => UserWalletEnum::INDIRECT_REWARD
  1479. ];
  1480. UserWalletService::handle(0, $data);
  1481. }
  1482. }
  1483. //提现余额&佣金转积分
  1484. if ($cash->give_score_num > 0) {
  1485. $data = [
  1486. 'message_id' => 0,
  1487. 'mall_id' => $cash->mall_id,
  1488. 'user_id' => $cash->user_id,
  1489. 'wallet_type' => UserWalletService::WALLET_TYPE_SCORE,
  1490. 'is_frozen' => false,
  1491. 'unfrozen' => false,
  1492. 'money' => abs($cash->give_score_num),
  1493. 'desc' => '提现[' . $cash->order_no . '] 转积分',
  1494. 'source' => AssetsType::RECHARGE,
  1495. 'source_id' => $cash->id,
  1496. 'from_type' => UserWalletEnum::TRANSFER,
  1497. 'capital_type' => $cash->from == 1 ? UserWalletEnum::WITHDRAWAL_COMMISSION_TRANSFER : UserWalletEnum::WITHDRAWAL_BALANCE_TRANSFER
  1498. ];
  1499. UserWalletService::handle(0, $data);
  1500. }
  1501. //提现佣金转余额
  1502. if ($cash->exchange_balance_num > 0) {
  1503. $data = [
  1504. 'message_id' => 0,
  1505. 'mall_id' => $cash->mall_id,
  1506. 'user_id' => $cash->user_id,
  1507. 'wallet_type' => UserWalletService::WALLET_TYPE_BALANCE,
  1508. 'is_frozen' => false,
  1509. 'unfrozen' => false,
  1510. 'money' => abs($cash->exchange_balance_num),
  1511. 'desc' => '提现[' . $cash->order_no . '] 转余额',
  1512. 'source' => AssetsType::RECHARGE,
  1513. 'source_id' => $cash->id,
  1514. 'from_type' => UserWalletEnum::TRANSFER,
  1515. 'capital_type' => UserWalletEnum::WITHDRAWAL_COMMISSION_TRANSFER_BALANCE
  1516. ];
  1517. UserWalletService::handle(0, $data);
  1518. }
  1519. }
  1520. /**
  1521. * 打款失败,变成已同意状态,让客户自己去驳回
  1522. *
  1523. * @param UserWithdrawLog $cash
  1524. * @param string $msg
  1525. * @return void
  1526. */
  1527. public static function remit_fail(UserWithdrawLog $cash, $msg)
  1528. {
  1529. $content = empty($cash->content) ? [] : Json::decode($cash->content);
  1530. $content['remit_content'] = $msg;
  1531. $res = UserWithdrawLog::updateAll([
  1532. 'status' => 1,
  1533. 'content' => Json::encode($content),
  1534. 'updated_at' => time()
  1535. ], ['id' => $cash->id]);
  1536. }
  1537. /**
  1538. * 打款中
  1539. *
  1540. * @param [type] $cash
  1541. * @param [type] $msg
  1542. * @return void
  1543. */
  1544. public static function remit_wait(UserWithdrawLog $cash, $msg)
  1545. {
  1546. $content = empty($cash['content']) ? [] : Json::decode($cash['content']);
  1547. $content['remit_content'] = $msg;
  1548. $res = self::updateAll(['content' => Json::encode($content), 'status' => 5], ['id' => $cash['id']]);
  1549. }
  1550. public static function exportHandle(array $data)
  1551. {
  1552. $download_id = $data['download_id'] ?? 0;
  1553. $download = Download::findOne(['id' => $download_id]);
  1554. if ($download) {
  1555. try {
  1556. $params = json_decode($download->params, true);
  1557. $isChanjetExport = !empty($params['is_chanjet_addons']);
  1558. $filename = $download->name;
  1559. $type = $download->type;
  1560. $user_withdrawlog_model = UserWithdrawLog::find();
  1561. $user_withdrawlog_model->where(['mall_id' => $params['mall_id']]);
  1562. if (!empty($params['keyword'])) {
  1563. $user = User::find()->where([
  1564. 'OR',
  1565. ['like', 'nickname', $params['keyword'] . '%', false],
  1566. ['like', 'mobile', $params['keyword'] . '%', false],
  1567. ])->all();
  1568. $where[] = ['in', 'user_id', array_column($user, 'id')];
  1569. $user_withdrawlog_model->andWhere(['in', 'user_id', array_column($user, 'id')]);
  1570. }
  1571. if (!empty($params['user_id'])) $user_withdrawlog_model->andWhere(['=', 'user_id', $params['user_id']]);
  1572. if (!empty($params['withdraw_type'])) $user_withdrawlog_model->andWhere(['=', 'type', $params['withdraw_type']]);
  1573. if (!empty($params['withdraw_from'])) $user_withdrawlog_model->andWhere(['=', 'from', $params['withdraw_from']]);
  1574. if (!empty($params['start_date'])) $user_withdrawlog_model->andWhere(['>=', 'created_at', strtotime($params['start_date'])]);
  1575. if (!empty($params['end_date'])) $user_withdrawlog_model->andWhere(['<=', 'created_at', strtotime($params['end_date'])]);
  1576. if (isset($params['status'])) {
  1577. $user_withdrawlog_model->andWhere(['=', 'status', $params['status']]);
  1578. } else {
  1579. $user_withdrawlog_model->andWhere(['>=', 'status', StatusEnum::DISABLED]);
  1580. }
  1581. $fields = $params['fields'];
  1582. $fields_arr = self::fieldsList(null, $isChanjetExport);
  1583. $have_select_field_arr = [];
  1584. foreach ($fields as $value) {
  1585. $have_select_field_arr[] = $fields_arr[$value];
  1586. }
  1587. // 获取提现方式
  1588. $userWithdrawType = self::getUserWithdrawType($params['mall_id']);
  1589. $csv = new CsvTool();
  1590. $csv->filename = $filename;
  1591. $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type);
  1592. $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
  1593. $csv->header = $have_select_field_arr;
  1594. $user_withdrawlog_model->with(['user' => function ($query) {
  1595. $query->select('id,nickname,username,avatar_url,mobile');
  1596. }]);
  1597. if ($isChanjetExport) {
  1598. $user_withdrawlog_model->with(['addonsChanjetRequest']);
  1599. }
  1600. $user_withdrawlog_model->orderBy('status asc,created_at desc');
  1601. foreach ($user_withdrawlog_model->batch() as $withdrawlog) {
  1602. $csv->data = array_map(function ($withdrawlog) use ($fields, $userWithdrawType) {
  1603. $row = [];
  1604. $extra = json_decode($withdrawlog['extra'], true) ?: [];
  1605. foreach ($fields as $field) {
  1606. switch (true) {
  1607. case (in_array($field, ['updated_at'])):
  1608. $row[] = !empty($withdrawlog[$field]) ? date('Y-m-d H:i:s', $withdrawlog[$field]) : '';
  1609. break;
  1610. case ($field == 'username'):
  1611. $row[] = $withdrawlog['user']['username'] ?: '';
  1612. break;
  1613. case ($field == 'nickname'):
  1614. $row[] = $withdrawlog['user']['nickname'] ?: '';
  1615. break;
  1616. case ($field == 'user_mobile'):
  1617. $row[] = $withdrawlog['user']['mobile'] ?: '';
  1618. break;
  1619. case ($field == 'from'):
  1620. $row[] = $withdrawlog[$field] == 1 ? '佣金收益提现' : '余额提现';
  1621. break;
  1622. case ($field=='alipay_name'):
  1623. $row[] = $extra['name'] ?: '';
  1624. break;
  1625. case ($field=='mobile'):
  1626. $row[] = empty($extra['mobile']) ? '' : $extra['mobile']."\t";
  1627. break;
  1628. case ($field=='bank_account_type'):
  1629. $row[] = $extra['bank_account_type'] == 1 ? '对私账户' : ($extra['bank_account_type'] == 2 ? '对公账号' : '');
  1630. break;
  1631. case ($field=='name'):
  1632. $row[] = $extra['name'] ?: '';
  1633. break;
  1634. case ($field=='bank_name'):
  1635. $row[] = $extra['bank_name'] ?: '';
  1636. break;
  1637. case ($field=='bank_account'):
  1638. $row[] = empty($extra['bank_account']) ? '' : $extra['bank_account']."\t";
  1639. break;
  1640. case ($field == 'withdraw_type'): // 提现方式
  1641. $row[] = $userWithdrawType[$withdrawlog['type']] ?? '';
  1642. break;
  1643. case ($field=='idcard'):
  1644. $row[] = empty($extra['idcard']) ? '' : $extra['idcard']."\t";
  1645. break;
  1646. case ($field=='wechat_qrcode'):
  1647. $row[] = $extra['wechat_qrcode'] ?: '';
  1648. break;
  1649. case ($field=='status'):
  1650. $str = '';
  1651. switch ($withdrawlog[$field]){
  1652. case 0:
  1653. $str='待审核';
  1654. break;
  1655. case 1:
  1656. $str='待打款';
  1657. break;
  1658. case 2:
  1659. $str='已打款';
  1660. break;
  1661. case 5:
  1662. $str='打款中';
  1663. break;
  1664. case 3:
  1665. $str='已驳回';
  1666. break;
  1667. }
  1668. $row[] = $str;
  1669. break;
  1670. case ($field == 'remark'):
  1671. $withdrawlog['content'] = json_decode($withdrawlog['content'], true);
  1672. $str = '';
  1673. if (!empty($withdrawlog['content']['reject_content'])) $str .= '驳回备注:' . $withdrawlog['content']['reject_content'];
  1674. if (!empty($withdrawlog['content']['validate_content']) && in_array($withdrawlog['status'], [1, 2])) $str .= ';审核备注:' . $withdrawlog['content']['validate_content'];
  1675. if (!empty($withdrawlog['content']['remit_content']) && in_array($withdrawlog['status'], [1, 2])) $str .= ';打款备注:' . $withdrawlog['content']['remit_content'];
  1676. if (!empty($withdrawlog['content']['joinpay_msg'])) $str .= ';汇聚备注:' . $withdrawlog['content']['joinpay_msg'];
  1677. $row[] = $str;
  1678. break;
  1679. case ($field == 'chanjet_updated_at'):
  1680. if (isset($withdrawlog['addonsChanjetRequest']['updated_at'])) {
  1681. $row[] = date('Y-m-d H:i:s', $withdrawlog['addonsChanjetRequest']['updated_at']);
  1682. }else {
  1683. $row[] = '';
  1684. }
  1685. break;
  1686. case ($field == 'chanjet_request_status'):
  1687. if (isset($withdrawlog['addonsChanjetRequest']['request_status'])) {
  1688. $row[] = AddonsChanjetRequestEnum::getMap()[$withdrawlog['addonsChanjetRequest']['request_status']] ?? '';
  1689. }else {
  1690. $row[] = '';
  1691. }
  1692. break;
  1693. default:
  1694. $row[] = !empty($withdrawlog[$field]) ? $withdrawlog[$field] : '';
  1695. }
  1696. }
  1697. return $row;
  1698. }, $withdrawlog);
  1699. $csv->export();
  1700. }
  1701. $csv->updateDown($download, $params['mall_id']);
  1702. return true;
  1703. } catch (\Exception $e) {
  1704. $download->status = 3;
  1705. $res = $download->save();
  1706. self::setStaticError($e->getMessage());
  1707. return $e->getMessage();
  1708. }
  1709. }
  1710. }
  1711. /**
  1712. * 获取用户提现方式
  1713. * @param int $mall_id
  1714. * @return array|string[]
  1715. */
  1716. public static function getUserWithdrawType(int $mall_id)
  1717. {
  1718. $cashTypeBalance = $cashTypeIncome = [];
  1719. $paymentIncome = \Yii::$app->services->setting->mall->get($mall_id, 'withdraw_income');
  1720. if (!empty($paymentIncome['balance_cash_type'])) {
  1721. $decoded = Json::decode($paymentIncome['balance_cash_type']);
  1722. if (is_array($decoded)) {
  1723. $cashTypeIncome = $decoded;
  1724. }
  1725. }
  1726. $paymentBalance = \Yii::$app->services->setting->mall->get($mall_id, 'withdraw_balance');
  1727. if (!empty($paymentBalance['balance_cash_type'])) {
  1728. $decoded = Json::decode($paymentBalance['balance_cash_type']);
  1729. if (is_array($decoded)) {
  1730. $cashTypeBalance = $decoded;
  1731. }
  1732. }
  1733. $cash_type = array_merge($cashTypeIncome, $cashTypeBalance);
  1734. $cash_type_name = [];
  1735. if (!empty($cash_type)) {
  1736. $default_withdraw_way = WithdrawWayEnum::getDefaultWithDrawWayMap(WithdrawWayEnum::WITHDRAW_TYPE_2);
  1737. $extension_withdraw_way = GlobalInvoke::exec(GlobalInvoke::INVOKE_GET_WITHDRAW_EXTENSION_WAY, $mall_id, ['mall_id' => $mall_id]);
  1738. $all_withdraw = array_merge($default_withdraw_way, $extension_withdraw_way);
  1739. foreach ($cash_type as $item) {
  1740. if (isset($all_withdraw[$item])) {
  1741. $value = $all_withdraw[$item];
  1742. $name = is_array($value) ? ($value['name'] ?? '') : $value;
  1743. $cash_type_name[$item] = $name;
  1744. }
  1745. }
  1746. }
  1747. return array_merge($cash_type_name, WithdrawWayEnum::getDefaultWithDrawWayMap(null)) ?? [];
  1748. }
  1749. /**
  1750. * 提现限制
  1751. *
  1752. * @param array $params
  1753. * @return boolean
  1754. */
  1755. protected function witdrawLimit(array $params, array $setting)
  1756. {
  1757. // 开启限制
  1758. if (isset($setting['limit_switch']) && $setting['limit_switch'] == 1) {
  1759. // 周限制
  1760. if ($setting['limit_type'] == 1) {
  1761. // ISO-8601 格式数字表示的星期中的第几天(PHP 5.1.0 新加
  1762. $d = date('N');
  1763. $limit = !empty($setting['week']) ? Json::decode($setting['week']) : [];
  1764. sort($limit);
  1765. $weekStr = [1 => '一', 2 => '二', 3 => '三', 4 => '四', 5 => '五', 6 => '六', 7 => '日'];
  1766. $limitStr = array_map(function ($item) use ($weekStr) {
  1767. return $weekStr[$item] ?? '';
  1768. }, $limit);
  1769. $error = sprintf('当前可提现时间为每周%s', implode(',', array_filter($limitStr)));
  1770. }
  1771. // 月限制
  1772. if ($setting['limit_type'] == 2) {
  1773. // 月份中的第几天,没有前导零
  1774. $d = date('j');
  1775. $limit = !empty($setting['month']) ? Json::decode($setting['month']) : [];
  1776. sort($limit);
  1777. $error = sprintf('当前可提现时间为每月的%s号', implode(',', $limit));
  1778. }
  1779. // 提现限制时间
  1780. if (in_array($d, $limit) === false) {
  1781. $this->error = $error;
  1782. return false;
  1783. }
  1784. // 首次提现
  1785. if (!empty($setting['first_withdraw']) && $first_withdraw = $setting['first_withdraw']) {
  1786. // 是否首次提现
  1787. if (static::isFirstWithdraw($params['from'], $params['user_id'])) {
  1788. // 提现金额不足
  1789. if (!empty($params['price']) && $params['price'] < $first_withdraw) {
  1790. $this->error = sprintf('首次提现最低金额为%s', sprintf('%.2f', $first_withdraw));
  1791. return false;
  1792. }
  1793. }
  1794. }
  1795. }
  1796. return true;
  1797. }
  1798. /**
  1799. * 提现拒绝,红包返回
  1800. * @param $cash
  1801. */
  1802. protected function reject_redpack($cash)
  1803. {
  1804. $mall_id = $cash->mall_id;
  1805. $install_redpack = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_REDPACK);
  1806. if($install_redpack){
  1807. //本次提现是否扣除冻结红包
  1808. $exist = RedpackWalletLog::findOne(['mall_id' => $mall_id,'user_id' => $cash->user_id,'redpack_wallet_type' => 'frozen_redpack','from_type' => RedpackEnum::FROM_CASH_DEDUCT,'source_table_id' => $cash->id]);
  1809. if($exist){
  1810. $config = Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_REDPACK, 'basic');
  1811. $redpack_name = $config['redpack_name'] ?? '红包';// 自定义红包名称
  1812. $wallet = RedpackWallet::setData([
  1813. 'mall_id' => $mall_id,
  1814. 'user_id' => $cash->user_id,
  1815. 'is_frozen' => true,
  1816. 'is_deduct' => true,
  1817. 'money' => $exist['change_num'],
  1818. 'from_type' => RedpackEnum::FROM_CASH_DEDUCT,
  1819. 'desc' => "佣金提现审核失败,返还冻结".$redpack_name,
  1820. 'source_table' => self::tableName(),
  1821. 'source_table_id' => $cash->id,
  1822. ]);
  1823. if(!$wallet) throw new \Exception(RedpackWallet::getStaticError());
  1824. }
  1825. }
  1826. }
  1827. public static function doRepurchaseCheck($payment, $user, $mall_id)
  1828. {
  1829. $is_withdraw_repurchase = isset(\Yii::$app->params['is_withdraw_repurchase']) ? \Yii::$app->params['is_withdraw_repurchase'] : false;
  1830. if (!$is_withdraw_repurchase) return 0;
  1831. if (!$payment['enable_repurchase_limit']) return 0;
  1832. if ($payment['repurchase_reach_money'] <= 0) return 0;
  1833. $level_arr = json_decode($payment['repurchase_user_level_limit'], true);
  1834. if (!in_array($user['level'], $level_arr)) return 0;
  1835. $log = UserWithdrawLog::find()->where([
  1836. 'and', ['mall_id' => $mall_id], ['user_id' => $user['id']], ['from' => 1], ['status' => [1, 2]]
  1837. ])->orderBy('id desc')->limit(1)->one();
  1838. $repurchase_money = 0;
  1839. if ($log) {
  1840. if (date('m', $log['created_at']) == date('m')) {
  1841. $repurchase_money = \common\models\order\Order::find()->where([
  1842. 'and', ['mall_id' => $mall_id], ['user_id' => $user['id']], ['pay_status' => StatusEnum::ENABLED], ['>=', 'pay_time', strtotime(date('Y-m-01', time()))], ['<=', 'pay_time', strtotime(date('Y-m-t', time()))]
  1843. ])->sum('goods_price') ?? 0;
  1844. } else {
  1845. $start_time = $log['created_at'];
  1846. $start_year = date('Y', $start_time);
  1847. $current_year = date('Y', time());
  1848. $start_month = (int)date('m', $start_time);
  1849. $current_month = (int)date('m', time());
  1850. $distance_year = $current_year - $start_year;
  1851. //月份相差多少
  1852. $distance_month = 12 - $start_month + $current_month;
  1853. //相差一年就加12
  1854. $distance = $distance_month + (($distance_year - 1) * 12);
  1855. $payment['repurchase_reach_money'] = bcmul($distance, $payment['repurchase_reach_money'], 2);
  1856. $repurchase_money = \common\models\order\Order::find()->where([
  1857. 'and', ['mall_id' => $mall_id], ['user_id' => $user['id']], ['pay_status' => StatusEnum::ENABLED], ['>', 'pay_time', strtotime(date('Y-m-t 23:59:59', $start_time))], ['<=', 'pay_time', time()]
  1858. ])->sum('goods_price') ?? 0;
  1859. }
  1860. } else {
  1861. $repurchase_money = \common\models\order\Order::find()->where([
  1862. 'and', ['mall_id' => $mall_id], ['user_id' => $user['id']], ['pay_status' => StatusEnum::ENABLED], ['>=', 'pay_time', strtotime(date('Y-m-01', time()))], ['<=', 'pay_time', strtotime(date('Y-m-t 23:59:59', time()))]
  1863. ])->sum('goods_price') ?? 0;
  1864. }
  1865. return $repurchase_money - $payment['repurchase_reach_money'];
  1866. }
  1867. /**
  1868. * 是否首次提现
  1869. *
  1870. * @param integer $from
  1871. * @return boolean
  1872. */
  1873. public static function isFirstWithdraw(int $from, int $user_id)
  1874. {
  1875. $has = static::find()
  1876. ->andWhere([
  1877. 'user_id' => $user_id,
  1878. 'status' => static::STATUS_ALREADY_TRANS,
  1879. 'from' => $from,
  1880. ])
  1881. ->select(['id'])
  1882. ->one();
  1883. return empty($has);
  1884. }
  1885. public static function checkPassword($user_id, $check_transaction_password, $setting = [])
  1886. {
  1887. if ($setting) {
  1888. $enable_password = $setting['enable_password'] ?? 0;
  1889. if ($enable_password == 1) {
  1890. $userinfo = User::getOne([['id' => $user_id]], true, '', '', 'transaction_password');
  1891. if (!$check_transaction_password) {
  1892. return [
  1893. 'state' => false,
  1894. 'msg' => '请输入支付密码!'
  1895. ];
  1896. }
  1897. if (empty($userinfo['transaction_password'])) {
  1898. return [
  1899. 'state' => false,
  1900. 'msg' => '您未设置支付密码!'
  1901. ];
  1902. }
  1903. if (empty($check_transaction_password)) {
  1904. return [
  1905. 'state' => false,
  1906. 'msg' => '请输入交易密码!'
  1907. ];
  1908. }
  1909. if (!\Yii::$app->getSecurity()->validatePassword(trim($check_transaction_password), $userinfo['transaction_password'])) {
  1910. return [
  1911. 'state' => false,
  1912. 'msg' => '支付密码错误!'
  1913. ];
  1914. }
  1915. }
  1916. }
  1917. return true;
  1918. }
  1919. /**
  1920. * 获取数据
  1921. *
  1922. * @param integer $mall_id
  1923. * @return array
  1924. */
  1925. public static function getWithdrawLogStatistic(int $mall_id)
  1926. {
  1927. $audit_commision = static::find()->where(['mall_id' => $mall_id, 'status' => 0])->sum('num');
  1928. $pending_commision = static::find()->where(['mall_id' => $mall_id, 'status' => 1])->sum('num');
  1929. $paid_commision = static::find()->where(['mall_id' => $mall_id, 'status' => 2])->sum('num');
  1930. $rejected_commision = static::find()->where(['mall_id' => $mall_id, 'status' => 3])->sum('num');
  1931. $total_commision = static::find()->where(['mall_id' => $mall_id])->sum('num');
  1932. return [
  1933. $audit_commision ?? '0.00',
  1934. $pending_commision ?? '0.00',
  1935. $paid_commision ?? '0.00',
  1936. $rejected_commision ?? '0.00',
  1937. $total_commision ?? '0.00',
  1938. ];
  1939. }
  1940. /**
  1941. * 畅捷通请求
  1942. *
  1943. * @return \yii\db\ActiveQuery
  1944. */
  1945. public function getAddonsChanjetRequest()
  1946. {
  1947. return $this
  1948. ->hasOne(AddonsChanjetRequest::class, ['table_id' => 'id'])
  1949. ->orderBy('updated_at desc')
  1950. ->select('id, table_id, request_status, updated_at')
  1951. ->where([
  1952. 'table' => self::tableName(),
  1953. 'path' => [Request::PATHS['EXPENSE_VOUCHER_CREATE_EXPENSE_VOUCHER']]
  1954. ])
  1955. ->andWhere(['>', 'request_status', 0]);
  1956. }
  1957. public static function withdrawCheck($params)
  1958. {
  1959. if (!$params['type']) {
  1960. throw new Exception('请选择提现方式');
  1961. }
  1962. switch ($params['type']) {
  1963. case "yunfast_pay":
  1964. if (empty($params['bank_account'])) {
  1965. throw new Exception('请选择银行卡');
  1966. }
  1967. if (empty($params['bank_account_type'])) {
  1968. throw new Exception('请选择账户类型');
  1969. }
  1970. if (empty($params['name'])) {
  1971. throw new Exception('请输入持卡人姓名');
  1972. }
  1973. break;
  1974. case 'alitopay':
  1975. case WithdrawWayEnum::ALIPAY_OFFLINE:
  1976. if (empty($params['mobile'])) {
  1977. throw new Exception('请输入支付宝账号');
  1978. }
  1979. if (empty($params['name'])) {
  1980. throw new Exception('请输入支付宝真实姓名');
  1981. }
  1982. break;
  1983. case 'wechat':
  1984. if (!isset($params['wechat_qrcode'])) {
  1985. throw new Exception('请上传微信收款码');
  1986. }
  1987. break;
  1988. case 'alipay':
  1989. if (!isset($params['mobile'])) {
  1990. throw new Exception('请填写支付宝账号');
  1991. }
  1992. if (!$params['name']) {
  1993. throw new Exception('请填写支付宝姓名');
  1994. }
  1995. break;
  1996. case 'paid':
  1997. case 'joinpay':
  1998. if (!$params['name']) {
  1999. throw new \Exception('请填写持卡人');
  2000. }
  2001. if (!$params['bank_account']) {
  2002. throw new \Exception('请填写银行卡号');
  2003. }
  2004. break;
  2005. case 'alipay_tax':
  2006. if (!$params['mobile']) {
  2007. throw new \Exception('请填写支付宝账号(手机号)');
  2008. }
  2009. if (!$params['name']) {
  2010. throw new \Exception('请填写支付宝姓名');
  2011. }
  2012. if (!$params['id_card']) {
  2013. throw new \Exception('请填写身份证信息');
  2014. }
  2015. $service = new \addons\AvoidTax\common\service\UserService(['mall_id' => $params['mall_id']]);
  2016. // 判断当前身份ID是否已经签约 已签约则不签约
  2017. if (!$service->idIsSignAndAddAuthOfUid(
  2018. $params['id_card'], $params['name'], $params['user_id'], $params['mobile']
  2019. )) {
  2020. // 判断用户是否签约
  2021. $res = $service->checkSign($params['user_id']);
  2022. if ($res === false) {
  2023. if ($service->getConfigService()->isXLApiType()) {
  2024. $res = $service->goToSing($params['user_id'], $params['mobile'], $params['id_card'], $params['name'], $extra['redirect_url'] ?? '');
  2025. if (!$res) {
  2026. throw new \Exception($service->error);
  2027. }
  2028. // 跳转url签约
  2029. return [
  2030. 'state' => true,
  2031. 'data' => $res
  2032. ];
  2033. }
  2034. if ($service->getConfigService()->isLYApiType()) {
  2035. $res = $service->silentSign(
  2036. $params['user_id'], $params['name'], $params['mobile'], $params['id_card']
  2037. );
  2038. if ($res === false) {
  2039. throw new \Exception($service->error);
  2040. }
  2041. }
  2042. }
  2043. }
  2044. break;
  2045. case 'digital':
  2046. if (!$params['mobile']) {
  2047. throw new \Exception('请填写支付宝绑定的手机号!');
  2048. }
  2049. if ($params['bank_account_type'] == 2) {
  2050. $params['bank_account'] = $params['mobile'];
  2051. }
  2052. if ($params['bank_account_type'] == 3) {
  2053. $findOpenId = UserInfo::find()->where(['user_id' => $params['user_id'], 'status' => StatusEnum::ENABLED])->one();
  2054. if (empty($findOpenId->openid)) {
  2055. return [
  2056. 'state' => false,
  2057. 'msg' => '该账号未绑定微信,无法使用微信提现方式!'
  2058. ];
  2059. }
  2060. }
  2061. // 是否签约
  2062. $sign = DigitalEmploymentOrder::inquireSign($params['mall_id'], $params['user_id']);
  2063. // 1-签约中 2-签约成功 3-签约失败
  2064. if (empty($sign)) {
  2065. throw new \Exception('该用户未进行签约!');
  2066. }
  2067. if ($sign->result->signState == 1) {
  2068. throw new \Exception('该用户的签约正在审核中!');
  2069. }
  2070. if ($sign->result->signState == 3) {
  2071. throw new \Exception('用户签约失败,请重新签约!');
  2072. }
  2073. break;
  2074. case 'auto':
  2075. $payment_conf = Yii::$app->services->setting->mall->get($params['mall_id'], 'pay.wechat');
  2076. $payment_conf = json_decode($payment_conf, true);
  2077. if(!is_numeric($payment_conf['wechat_auto_pay_limit'])) $payment_conf['wechat_auto_pay_limit'] = 200;
  2078. if($params['from'] == self::FROM_SCORE){//积分提现,需除以积分提现比例
  2079. $payment = Yii::$app->services->setting->mall->get($params['mall_id'], 'score');
  2080. $params['price'] = bcdiv($params['price'],$payment['score_cash_radio'],2);
  2081. }
  2082. if ($params['price'] > $payment_conf['wechat_auto_pay_limit']) {
  2083. throw new \Exception('微信自动打款提现最高提现金额不能超过'.$payment_conf['wechat_auto_pay_limit'].'元');
  2084. }
  2085. break;
  2086. case 'bank':
  2087. if (empty($params['bank_account']) || empty($params['name'] || empty($params['bank_name']))) {
  2088. throw new \Exception('请选择你要提现的银行');
  2089. }
  2090. break;
  2091. case 'linggong': //点薪灵工
  2092. if (empty($params['name'])) {
  2093. throw new \Exception('请输入真实姓名');
  2094. }
  2095. if (empty($params['mobile'])) {
  2096. throw new \Exception('请输入手机号');
  2097. }
  2098. if (empty($params['bank_account'])) {
  2099. throw new \Exception('请输入银行卡号');
  2100. }
  2101. if (empty($params['idcard'])) {
  2102. throw new \Exception('请输入身份证');
  2103. }
  2104. break;
  2105. }
  2106. if (!empty($params['need_auth'])) {
  2107. $need_auth = GlobalInvoke::exec(
  2108. GlobalInvoke::REAL_AUTH,
  2109. $params['mall_id'],
  2110. ['user_id' => $params['user_id'], 'mall_id' => $params['mall_id'], 'type' => 'cash']
  2111. );
  2112. if ($need_auth === true) {
  2113. // 需要先进行实名认证
  2114. throw new Exception('请先进行实名认证');
  2115. }
  2116. }
  2117. //商家认证
  2118. if (!empty($params['MerchantAuth'])) {
  2119. if (MallAddons::isInstall($params['mall_id'], 'MerchantAuth')) {
  2120. $configs = Yii::$app->services->setting->addons->get($params['mall_id'], 'MerchantAuth', 'basic');
  2121. if (!empty($configs['is_force'])) {
  2122. //强制需要认证
  2123. $res = MerchantAuthLog::getOne([
  2124. ['mall_id' => $params['mall_id']],
  2125. ['user_id' => $params['user_id']],
  2126. ['status' => 1]
  2127. ]);
  2128. if (empty($res)) {
  2129. throw new Exception('未查询到认证资料,请先进行商家认证');
  2130. }
  2131. if (empty($res['progress'])) {
  2132. if ($res['is_poss'] == 0) {
  2133. throw new Exception('商家认证资料已提交,请等待审核');
  2134. } else {
  2135. throw new Exception('请先进行商家认证');
  2136. }
  2137. } elseif ($configs['is_force'] == 2 && $res['progress'] != 2) {
  2138. if ($res['is_poss'] == 0) {
  2139. throw new Exception('商家认证资料已提交,请等待审核');
  2140. } else {
  2141. throw new Exception('请先进行商家认证');
  2142. }
  2143. }
  2144. }
  2145. }
  2146. }
  2147. }
  2148. //汇聚代付-免审核
  2149. public static function joinpay_remit($cash): void
  2150. {
  2151. $res = false;
  2152. if ($cash->type === 'paid' || $cash->type === 'joinpay') { //代付
  2153. // print_r($cash);exit;
  2154. $res = GlobalInvoke::exec(GlobalInvoke::INVOKE_WITHDRAW_EXTENSION_PAY, $cash->mall_id, ['cash' => $cash]);
  2155. // print_r($res);exit;
  2156. if ($res) {
  2157. // 提交成功
  2158. self::remit_wait($cash, "提交成功");
  2159. return;
  2160. } else {
  2161. // 提交失败
  2162. $msg = '代付打款失败';
  2163. throw new \Exception($msg);
  2164. }
  2165. }
  2166. if ($res) {
  2167. self::remit_success($cash);
  2168. try {
  2169. $obj = new WechatMessageLogic();
  2170. $obj->withdrawalSuccessSendMessage(['mall_id'=>$cash->mall_id,'user_id'=>$cash->user_id,'money'=>$cash->actual_num]);
  2171. }catch (\Exception $e){
  2172. }
  2173. }else{
  2174. $msg = '打款失败';
  2175. throw new \Exception($msg);
  2176. }
  2177. }
  2178. /**
  2179. * 根据提现到余额总权重控制配置决定要不要验证具体的项
  2180. *
  2181. * @param int $from
  2182. * @param string $type
  2183. * @param array $setting
  2184. *
  2185. * @return array
  2186. */
  2187. protected function getIsNeedCheckSettingMap(int $from, string $type, array $setting): array
  2188. {
  2189. $isNeedCheckMap = [];
  2190. $isOpen = !empty($setting['balance_withdraw_total_weight_limit_switch']);
  2191. if ($isOpen) {
  2192. $balanceWithdrawTotalWeightLimitSelected = json_decode($setting['balance_withdraw_total_weight_limit_selected'] ?? '', true);
  2193. !is_array($balanceWithdrawTotalWeightLimitSelected) && $balanceWithdrawTotalWeightLimitSelected = [];
  2194. } else {
  2195. $balanceWithdrawTotalWeightLimitSelected = array_column(WithdrawEnum::BALANCE_WITHDRAW_TOTAL_WEIGHT_LIMIT_OPTION, 'value');
  2196. }
  2197. foreach (WithdrawEnum::BALANCE_WITHDRAW_TOTAL_WEIGHT_LIMIT_OPTION as $item) {
  2198. if ($type !== 'balance' || $from !== self::FROM_INCOME || !$isOpen) {
  2199. $isNeedCheckMap[$item['value']] = true;
  2200. continue;
  2201. }
  2202. $isNeedCheckMap[$item['value']] = in_array($item['value'], $balanceWithdrawTotalWeightLimitSelected);
  2203. }
  2204. return $isNeedCheckMap;
  2205. }
  2206. /**
  2207. * 返回是否在 "提现到余额总权重限制" 的配置中根据type
  2208. *
  2209. * @param int $from
  2210. * @param string $type
  2211. * @param array $setting
  2212. *
  2213. * @return bool
  2214. */
  2215. public function inBalanceWithdrawTotalWeightLimitSelectedByType(int $from, string $type, array $setting)
  2216. {
  2217. if ($from !== self::FROM_INCOME) {
  2218. return true;
  2219. }
  2220. if (empty($setting['balance_withdraw_total_weight_limit_switch'])) {
  2221. return true;
  2222. }
  2223. $balanceWithdrawTotalWeightLimitSelected = json_decode($setting['balance_withdraw_total_weight_limit_selected'] ?? '', true);
  2224. if (!$balanceWithdrawTotalWeightLimitSelected || !is_array($balanceWithdrawTotalWeightLimitSelected)) {
  2225. return false;
  2226. }
  2227. return in_array($type, $balanceWithdrawTotalWeightLimitSelected);
  2228. }
  2229. }