StoreWithdrawLog.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. <?php
  2. namespace addons\Store\common\models;
  3. use addons\Alitopay\common\enums\AlitoapyEnum;
  4. use addons\Alitopay\common\services\AlipayService;
  5. use addons\Alitopay\common\services\SettingService;
  6. use addons\AvoidTax\common\service\UserService;
  7. use addons\JoinPay\common\global_func\withdraw_way\WithdrawWay;
  8. use addons\JoinPay\common\models\JoinPayUserBankcard;
  9. use common\components\export\CsvTool;
  10. use common\enums\DownloadEnum;
  11. use common\enums\PayTypeEnum;
  12. use common\enums\RedisKeyEnum;
  13. use common\enums\StatusEnum;
  14. use addons\Store\common\enums\StoreEnum;
  15. use common\enums\UserWalletEnum;
  16. use common\helpers\LockHelper;
  17. use common\helpers\StringHelper;
  18. use common\logic\common\PaymentLogic;
  19. use common\models\base\BaseActiveRecord;
  20. use common\models\common\Download;
  21. use common\models\common\PaymentTransfer;
  22. use common\models\common\UserBankCard;
  23. use common\models\user\User;
  24. use common\models\user\UserInfo;
  25. use services\common\PayService;
  26. use services\common\UserWalletService;
  27. use Yii;
  28. use yii\db\Exception;
  29. use yii\helpers\Json;
  30. /**
  31. * This is the model class for table "qimall_addons_store_withdraw_log".
  32. *
  33. * @property int $id
  34. * @property int $mall_id 商城id
  35. * @property int $store_id 门店id
  36. * @property int $user_id 会员id
  37. * @property string $order_no 提现订单号
  38. * @property float $num 提现金额
  39. * @property float $actual_num 实际到账金额
  40. * @property float $poundage_num 手续费扣除金额
  41. * @property float $poundage_ratio 手续费比例
  42. * @property string $type 提现方式 bank--银行转账 balance--打款到余额
  43. * @property string $extra 额外信息
  44. * @property int $withdraw_status 提现状态 0--待打款 --已打款 2--驳回 3--提现失败
  45. * @property int $status 状态[0禁用 1启用 -1删除]
  46. * @property string $remark 备注
  47. * @property int|null $created_at 添加时间戳
  48. * @property int|null $updated_at 更新时间戳
  49. */
  50. class StoreWithdrawLog extends BaseActiveRecord
  51. {
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public static function tableName()
  56. {
  57. return '{{%addons_store_withdraw_log}}';
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function rules()
  63. {
  64. return [
  65. [['mall_id', 'store_id', 'user_id', 'withdraw_status', 'status', 'created_at', 'updated_at'], 'integer'],
  66. [['num', 'actual_num', 'poundage_num', 'poundage_ratio'], 'number'],
  67. [['extra'], 'string'],
  68. [['order_no', 'remark'], 'string', 'max' => 255],
  69. [['type'], 'string', 'max' => 45],
  70. ];
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function attributeLabels()
  76. {
  77. return [
  78. 'id' => 'ID',
  79. 'mall_id' => '商城id',
  80. 'store_id' => '门店id',
  81. 'user_id' => '会员id',
  82. 'order_no' => '提现订单号',
  83. 'num' => '提现金额',
  84. 'actual_num' => '实际到账金额',
  85. 'poundage_num' => '手续费扣除金额',
  86. 'poundage_ratio' => '手续费比例',
  87. 'type' => '提现方式 bank--银行转账 balance--打款到余额',
  88. 'extra' => '额外信息',
  89. 'content' => '用户额外输入信息',
  90. 'withdraw_status' => '提现状态 0--待打款 --已打款 2--驳回 ',
  91. 'status' => '态 0--申请 1--同意 2--已打款 3--驳回 4--失败',
  92. 'remark' => '备注',
  93. 'created_at' => '添加时间戳',
  94. 'updated_at' => '更新时间戳',
  95. ];
  96. }
  97. /**
  98. * User: wniu
  99. * Date: 2021/10/25
  100. * Time: 6:02 下午
  101. * *
  102. * @param $params
  103. * @return false|int[]
  104. * @throws Exception
  105. */
  106. public function saveRecord($params)
  107. {
  108. if(!empty($params['type'])){
  109. switch ($params['type']){
  110. case "joinpay":
  111. case "bank":
  112. if(empty($params['bank_account'])||empty($params['bank_name'])||empty($params['name'])){
  113. return [
  114. 'state' => false,
  115. 'msg' => '请选择银行卡!'
  116. ];
  117. }
  118. break;
  119. case "wechat":
  120. if(empty($params['wechat_qrcode'])){
  121. return [
  122. 'state' => false,
  123. 'msg' => '请上传收款码!'
  124. ];
  125. }
  126. break;
  127. case "alipay_tax":
  128. if(empty($params['id_card'])){
  129. return [
  130. 'state' => false,
  131. 'msg' => '请填写支付宝身份证号码!'
  132. ];
  133. }
  134. if(empty($params['mobile'])){
  135. return [
  136. 'state' => false,
  137. 'msg' => '请填写支付宝账号!'
  138. ];
  139. }
  140. if(empty($params['name'])){
  141. return [
  142. 'state' => false,
  143. 'msg' => '请填写支付宝真实姓名!'
  144. ];
  145. }
  146. break;
  147. case "alipay_offline":
  148. case "alitopay":
  149. if(empty($params['name'])){
  150. return [
  151. 'state' => false,
  152. 'msg' => '请填写支付宝真实姓名!'
  153. ];
  154. }
  155. if(empty($params['mobile'])){
  156. return [
  157. 'state' => false,
  158. 'msg' => '请填写支付宝账号!'
  159. ];
  160. }
  161. break;
  162. }
  163. }
  164. if ($params['price'] <= 0) {
  165. return [
  166. 'state' => false,
  167. 'msg' => '提现金额必须大于0!'
  168. ];
  169. }
  170. $exists = self::find()->where([
  171. 'mall_id' => $params['mall_id'], 'withdraw_status' => 0, 'user_id' => $params['user_id']
  172. ])->asArray()->one();// mycat不支持exists()用法
  173. if ($exists) {
  174. return [
  175. 'state' => false,
  176. 'msg' => '尚有未审核的提现申请!'
  177. ];
  178. }
  179. $store = Store::getOne([['id' => $params['store_id']]], false, [], false, 'id,mall_id,user_id,balance,total_expenses');
  180. //手续费设置
  181. $poundage_ratio = 0;
  182. //需要提现手续费金额
  183. $cash_amount = $params['price'];
  184. if ($params['type'] != 'balance') {
  185. $finance = \Yii::$app->services->setting->addons->get($params['mall_id'], StoreEnum::ADDONS_NAME, 'finance');
  186. $storeSetting = StoreSettings::findOne(['store_id' => $this->store_id]);
  187. // 走的独立设置
  188. if (!empty($storeSetting->is_enable_withdraw_setting)) {
  189. $finance['balance_cash_service_fee_limit'] = $storeSetting->balance_cash_service_fee_limit;
  190. $finance['balance_cash_service_fee_month'] = $storeSetting->balance_cash_service_fee_month;
  191. $finance['balance_cash_service_fee_diff'] = $storeSetting->balance_cash_service_fee_diff;
  192. $finance['balance_cash_service_fee'] = $storeSetting->balance_cash_service_fee;
  193. }
  194. if (!empty($finance['balance_cash_service_fee_limit'])) {
  195. $month_start = strtotime(date('Y-m-01 00:00:00'));
  196. $month_end = time();
  197. $cash_total = self::find()
  198. ->where(['mall_id' => $params['mall_id'], 'withdraw_status' => [0, 1], 'user_id' => $params['user_id'], 'status' => StatusEnum::ENABLED])
  199. ->andWhere(['>=', 'created_at', $month_start])
  200. ->andWhere(['!=', 'type', 'balance'])
  201. ->andWhere(['<', 'created_at', $month_end])
  202. ->sum('num') ?? 0;
  203. if ($params['price'] + $cash_total > $finance['balance_cash_service_fee_month']) {
  204. $poundage_ratio = $finance['balance_cash_service_fee_diff'] ?? 0;
  205. $cash_amount = bcsub(bcadd($params['price'], $cash_total, 2), $finance['balance_cash_service_fee_month'], 2);
  206. if ($cash_amount > $params['price']) {
  207. $cash_amount = $params['price'];
  208. }
  209. }
  210. } else {
  211. if (isset($finance['balance_cash_service_fee'])) {
  212. $poundage_ratio = $finance['balance_cash_service_fee'] ?? 0;
  213. } else {
  214. $poundage_ratio = \Yii::$app->services->setting->mall->get($params['mall_id'], 'withdraw_balance.balance_cash_service_fee');
  215. }
  216. }
  217. }
  218. if ($store['balance'] < $params['price']) {
  219. return [
  220. 'state' => false,
  221. 'msg' => '提现金额超出可提现金额!'
  222. ];
  223. }
  224. if (!$params['type']) {
  225. return [
  226. 'state' => false,
  227. 'msg' => '请选择提现方式!'
  228. ];
  229. }
  230. if ($params['type'] == 'wechat') {
  231. if (!isset($params['wechat_qrcode'])) {
  232. return [
  233. 'state' => false,
  234. 'msg' => '请上传微信收款码!'
  235. ];
  236. }
  237. }
  238. if ($params['type'] == 'alipay') {
  239. if (!$params['mobile']) {
  240. return [
  241. 'state' => false,
  242. 'msg' => '请填写支付宝账号!'
  243. ];
  244. }
  245. if (!$params['name']) {
  246. return [
  247. 'state' => false,
  248. 'msg' => '请填写支付宝姓名!'
  249. ];
  250. }
  251. }
  252. if ($params['type'] == 'paid') {//代付银行卡
  253. if (!$params['name']) {
  254. return [
  255. 'state' => false,
  256. 'msg' => '请填写持卡人!'
  257. ];
  258. }
  259. if (!$params['bank_account']) {
  260. return [
  261. 'state' => false,
  262. 'msg' => '请填写银行卡号!'
  263. ];
  264. }
  265. }
  266. if ($params['type'] == 'alipay_tax') {
  267. if (!$params['mobile']) {
  268. return [
  269. 'state' => false,
  270. 'msg' => '请填写支付宝账号(手机号)'
  271. ];
  272. }
  273. if (!$params['name']) {
  274. return [
  275. 'state' => false,
  276. 'msg' => '请填写支付宝姓名'
  277. ];
  278. }
  279. if (!$params['id_card']) {
  280. return [
  281. 'state' => false,
  282. 'msg' => '请填写身份证信息'
  283. ];
  284. }
  285. $service = new \addons\AvoidTax\common\service\UserService(['mall_id' => $params['mall_id']]);
  286. $res = $service->checkSign($params['user_id']);
  287. if ($res === false) {
  288. $res = $service->goToSing($params['user_id'], $params['mobile'], $params['id_card'], $params['name']);
  289. if (!$res) {
  290. return [
  291. 'state' => false,
  292. 'msg' => $service->error
  293. ];
  294. }
  295. // 跳转url签约
  296. return [
  297. 'state' => true,
  298. 'data' => $res
  299. ];
  300. }
  301. }
  302. $cash = new StoreWithdrawLog();
  303. $cash->mall_id = $params['mall_id'];
  304. $cash->user_id = $store['user_id'];
  305. $cash->store_id = $store['id'];
  306. $cash->num = $params['price'];
  307. $cash->actual_num = $params['price'];
  308. $cash->order_no = StringHelper::generateOrderNo('tx');
  309. $cash->status = StatusEnum::ENABLED;
  310. $cash->remark = $params['remark'] ?? '';
  311. $cash->content = Json::encode(['user_content' => $params['content']]);
  312. $cash->type = $params['type'];
  313. $cash->extra = Json::encode([
  314. 'name' => $params['name'],
  315. 'mobile' => $params['mobile'],
  316. 'bank_name' => $params['bank_name'],
  317. 'bank_account' => (string)$params['bank_account'],
  318. 'bank_account_type' => $params['bank_account_type'],
  319. 'wechat_qrcode' => $params['wechat_qrcode'],
  320. 'id_card' => $params['id_card'] ?? '',
  321. 'receive_bank_chanel_no' => $params['receive_bank_chanel_no'] ?? ''
  322. ], JSON_UNESCAPED_UNICODE);
  323. if ($poundage_ratio < 0 || $poundage_ratio > 100) {
  324. return [
  325. 'state' => false,
  326. 'msg' => '手续费设置不正确!'
  327. ];
  328. }
  329. //手续费
  330. $poundage = 0;
  331. if ($poundage_ratio > 0 && $poundage_ratio < 100) {
  332. //手续费:取小数点2位,截断
  333. $poundage = bcmul($poundage_ratio / 100, $cash_amount, 4);
  334. // 四舍五入,保留2位
  335. $poundage = number_format($poundage, 2, '.', '');
  336. $cash->actual_num = bcsub($params['price'], $poundage, 2);
  337. $cash->poundage_num = $poundage;
  338. $cash->poundage_ratio = $poundage_ratio;
  339. }
  340. if (intval(bcmul($cash->actual_num, 100)) < 1) {
  341. return [
  342. 'state' => false,
  343. 'msg' => '提现金额扣除费用后金额不足!'
  344. ];
  345. }
  346. $t = \Yii::$app->db->beginTransaction();
  347. try {
  348. switch ($params['type']) {
  349. case 'balance':
  350. //提现到个人余额
  351. $desc = '余额提现' . $cash->num;
  352. $data = [
  353. 'message_id' => 0, 'mall_id' => $store['mall_id'], 'user_id' => $store['user_id'],
  354. 'wallet_type' => 'balance',
  355. 'is_frozen' => false, 'unfrozen' => false, 'money' => abs($cash->actual_num),
  356. 'desc' => $desc, 'source_table' => 'user_wallet', 'source_table_id' => $cash->id,
  357. 'from_type' => UserWalletEnum::WITHDRAWAL,
  358. 'capital_type' => UserWalletEnum::RECHARGE_STORE_BALANCE,
  359. ];
  360. $wallet_service_status = UserWalletService::handle(0, $data);
  361. if (!$wallet_service_status) {
  362. throw new Exception('提现失败' . UserWalletService::getStaticError());
  363. }
  364. $cash->withdraw_status = 1;
  365. break;
  366. default:
  367. $cash->withdraw_status = 0;
  368. }
  369. if (!$cash->save()) {
  370. throw new Exception($cash->getErrorMessage());
  371. }
  372. $store->balance -= $params['price'];
  373. $store->total_expenses += $params['price'];
  374. $res = $store->save();
  375. if ($res == false) throw new Exception($store->getErrorMessage());
  376. $res_data = [
  377. 'state' => true,
  378. 'data' => ['cash_id' => $cash->id],
  379. 'msg' => ''
  380. ];
  381. $t->commit();
  382. } catch (Exception $e) {
  383. $t->rollBack();
  384. \Yii::error($e->getMessage());
  385. return [
  386. 'state' => false,
  387. 'msg' => '提现失败!' . $e->getMessage()
  388. ];
  389. }
  390. return $res_data;
  391. }
  392. public static function withdrawByJoinPay($select_bank)
  393. {
  394. dd($select_bank);
  395. }
  396. public static function withdrawApply($params)
  397. {
  398. // $t = Yii::$app->db->beginTransaction();
  399. // $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_MCH_BALANCE_WALLET, $params['mch_id']);
  400. $identification = uniqid();
  401. try {
  402. // if (LockHelper::lock($lock_key, $identification, 100, 100)) {
  403. $store = Store::getOne([['id' => $params['store_id']]], false, [], false, 'id,mall_id,user_id,balance');
  404. if ($params['withdrawal_money'] > $store['balance']) throw new Exception('输入金额大于可提现金额');
  405. $params['user_id'] = $store['user_id'];
  406. $cash = new self();
  407. $cash->mall_id = $params['mall_id'];
  408. $cash->user_id = $store['user_id'];
  409. $cash->store_id = $store['id'];
  410. $cash->num = $params['withdrawal_money'];
  411. $cash->actual_num = $params['withdrawal_money'];
  412. $cash->order_no = StringHelper::generateOrderNo('tx');
  413. $cash->extra = json_encode([]);
  414. $cash->status = 1;
  415. $cash->remark = $params['remark'] ?? '';
  416. $extra = [];
  417. $return_data = [];
  418. $withdraw_status = 0;
  419. switch ($params['withdrawal_type']) {
  420. case 'balance':
  421. //提现到个人余额
  422. $cash->type = 'balance';
  423. $desc = '余额提现' . $cash->num;
  424. $data = [
  425. 'message_id' => 0, 'mall_id' => $store['mall_id'], 'user_id' => $store['user_id'],
  426. 'wallet_type' => 'balance',
  427. 'is_frozen' => false, 'unfrozen' => false, 'money' => abs($cash->actual_num),
  428. 'desc' => $desc, 'source_table' => 'user_wallet', 'source_table_id' => $cash->id,
  429. 'from_type' => UserWalletEnum::WITHDRAWAL,
  430. 'capital_type' => UserWalletEnum::RECHARGE_MCH_BALANCE,
  431. ];
  432. $wallet_service_status = UserWalletService::handle(0, $data);
  433. if (!$wallet_service_status) {
  434. throw new Exception('提现失败' . UserWalletService::getStaticError());
  435. }
  436. $withdraw_status = 1;
  437. break;
  438. case 'bank':
  439. case 'joinpay':
  440. case 'yunfast_pay':
  441. if (empty($params['select_bank'])) throw new Exception('请选择银行卡');
  442. $extra = $params['select_bank'];
  443. break;
  444. case 'alitopay':
  445. case 'alipay_offline':
  446. if (empty($params['name'])) throw new Exception('请输入支付宝真实姓名');
  447. if (empty($params['mobile'])) throw new Exception('支付宝绑定的手机号');
  448. // if (empty($params['id_card'])) throw new Exception('请输入支付宝身份证号码');
  449. // $extra['id_card'] = $params['id_card'];
  450. $extra['name'] = $params['name'];
  451. $extra['mobile'] = $params['mobile'];
  452. break;
  453. case 'alipay_tax':
  454. if (empty($params['name'])) throw new Exception('请输入支付宝真实姓名');
  455. if (empty($params['mobile'])) throw new Exception('支付宝绑定的手机号');
  456. $extra['name'] = $params['name'];
  457. $extra['mobile'] = $params['mobile'];
  458. if (empty($params['id_card'])) throw new Exception('请输入支付宝身份证号码');
  459. $extra['id_card'] = $params['id_card'];
  460. $obj = new UserService(['mall_id' => $params['mall_id']]);
  461. $res = $obj->checkSign($store['user_id']);
  462. $data['is_sign'] = 0;
  463. if ($res != false) {
  464. $data['is_sign'] = 1;
  465. $data = array_merge($res, $data);
  466. }
  467. $return_data['is_sign'] = $data['is_sign'];
  468. if (!$data['is_sign']) {
  469. $res = $obj->goToSing($store['user_id'], $params['mobile'], $params['id_card'], $params['name']);
  470. if (!$res) {
  471. throw new Exception($obj->error);
  472. }
  473. $res['is_sign'] = $data['is_sign'];
  474. return ['code' => 1, 'data' => $res];
  475. }
  476. break;
  477. case 'wechat':
  478. if (empty($params['wechat_qrcode'])) throw new Exception('请上传凭证');
  479. $extra['content'] = $params['content'];
  480. $extra['wechat_qrcode'] = $params['wechat_qrcode'];
  481. break;
  482. case 'auto':
  483. $userInfo = UserInfo::findOne(['user_id' => $store['user_id'], 'mall_id' => $params['mall_id'],
  484. 'status' => StatusEnum::ENABLED, 'platform' => ['wechat', 'mp-wx']]);
  485. if (empty($userInfo)) throw new Exception('该商户不存在微信相关信息,请先到前端用微信公众号或者小程序注册');
  486. break;
  487. default:
  488. throw new Exception('提现方式异常');
  489. // }
  490. }
  491. $cash->extra = json_encode($extra);
  492. $cash->type = $params['withdrawal_type'];
  493. if ($params['balance_cash_service_fee'] > 0 && $params['balance_cash_service_fee'] < 100) {
  494. //手续费:取小数点2位,截断
  495. $poundage = bcmul($params['balance_cash_service_fee'] / 100, $params['withdrawal_money'], 4);
  496. // 四舍五入,保留2位
  497. $poundage = number_format($poundage, 2, '.', '');
  498. $cash->actual_num = bcsub($params['withdrawal_money'], $poundage, 2);
  499. $cash->poundage_num = $poundage;
  500. $cash->poundage_ratio = $params['balance_cash_service_fee'];
  501. }
  502. if (intval(bcmul($cash->actual_num, 100)) < 1) {
  503. throw new Exception('提现金额扣除费用后金额不足');
  504. }
  505. $cash->withdraw_status = $withdraw_status;
  506. $res = $cash->save();
  507. if ($res == false) throw new Exception($cash->getErrorMessage());
  508. $store->balance -= $params['withdrawal_money'];
  509. $res = $store->save();
  510. if ($res == false) throw new Exception($store->getErrorMessage());
  511. // $t->commit();
  512. // LockHelper::uLock($lock_key, $identification);
  513. return ['code' => 1, 'data' => $return_data];
  514. } catch (\Exception $e) {
  515. // $t->rollBack();
  516. // LockHelper::uLock($lock_key, $identification);
  517. self::$static_error = $e->getMessage();
  518. return [];
  519. }
  520. }
  521. /**
  522. * @name:
  523. * @msg: 后台审核门店提现申请
  524. * @param {int} $mall_id
  525. * @param {array} $params
  526. * @return {*}
  527. */
  528. public static function cashAuditOld(int $mall_id, array $params)
  529. {
  530. $log = self::findOne(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'id' => $params['id'], 'withdraw_status' => 0]);
  531. if (empty($log)) {
  532. self::$static_error = '提现记录不存在';
  533. return false;
  534. }
  535. if ($params['withdraw_status'] == 1 && $log['type'] == 'fast_join_pay') {
  536. //汇聚代付
  537. $extraArr = json_decode($log['extra'], true);
  538. $extra = json_encode([
  539. 'bank_account' => $extraArr['bank_card_no'],
  540. 'name' => $extraArr['payer_name'],
  541. 'bank_account_type' => $extraArr['bank_account_type'],
  542. ]);
  543. $cash = [
  544. 'actual_num' => $log['actual_num'],
  545. 'mall_id' => $log['mall_id'],
  546. 'user_id' => $log['user_id'],
  547. 'order_no' => $log['order_no'],
  548. 'extra' => $extra,
  549. ];
  550. $data['cash'] = json_decode(json_encode($cash));
  551. $data['title'] = 'o2o店铺余额提现';
  552. $data['source'] = '2';
  553. WithdrawWay::extensionWithdrawPay($data);
  554. }
  555. $transaction = \Yii::$app->db->beginTransaction();
  556. $log->withdraw_status = $params['withdraw_status'];
  557. $log->remark = $params['remark'];
  558. $log->updated_at = time();
  559. $res = $log->save();
  560. if (!$res) {
  561. $transaction->rollBack();
  562. self::$static_error = $log->getErrorMessage();
  563. return false;
  564. }
  565. if (2 == $params['withdraw_status']) {
  566. // 驳回提现申请,退回已经扣除的余额
  567. $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_STORE_BALANCE_WALLET, $log->store_id);
  568. $identification = uniqid();
  569. if (LockHelper::lock($lock_key, $identification, 100, 100)) {
  570. // 退回的金额
  571. $store = Store::findOne(['mall_id' => $mall_id, 'id' => $log->store_id, 'user_id' => $log->user_id]);
  572. $store->balance = bcadd($store->balance, $log->num, 2);
  573. $res_store = $store->save();
  574. LockHelper::uLock($lock_key, $identification);
  575. if (!$res_store) {
  576. $transaction->rollBack();
  577. self::$static_error = $store->getErrorMessage();
  578. return false;
  579. }
  580. $transaction->commit();
  581. return true;
  582. } else {
  583. $transaction->rollBack();
  584. self::$static_error = '系统繁忙,请稍后再试';
  585. return false;
  586. }
  587. } else {
  588. $transaction->commit();
  589. return true;
  590. }
  591. }
  592. public static function cashAudit(int $mall_id, array $params)
  593. {
  594. $log = self::findOne(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'id' => $params['id'], 'withdraw_status' => 0]);
  595. if (empty($log)) {
  596. self::$static_error = '提现记录不存在';
  597. return false;
  598. }
  599. try {
  600. $res = false;
  601. switch ($params['withdraw_status']) {
  602. case 1:
  603. $cash = [
  604. 'actual_num' => $log['actual_num'],
  605. 'mall_id' => $log['mall_id'],
  606. 'user_id' => $log['user_id'],
  607. 'order_no' => $log['order_no'],
  608. 'id' => $log['id'],
  609. ];
  610. switch ($log['type']) {
  611. case "joinpay":
  612. //汇聚代付
  613. $extraArr = json_decode($log['extra'], true);
  614. $extra = json_encode([
  615. 'bank_account' => !empty($extraArr['bank_card_no'])?$extraArr['bank_card_no']:$extraArr['bank_account'],
  616. 'name' => !empty($extraArr['payer_name'])?$extraArr['payer_name']:$extraArr['name'],
  617. 'bank_account_type' =>$extraArr['bank_account_type'],
  618. ]);
  619. $cash['extra'] = $extra;
  620. $data['cash'] = json_decode(json_encode($cash));
  621. $data['title'] = '商户余额提现';
  622. $data['source'] = '3';
  623. $res = WithdrawWay::extensionWithdrawPay($data);
  624. break;
  625. case "alitopay":
  626. $extraArr = json_decode($log['extra'], true);
  627. $res = self::withdrawToPay($mall_id, $log['id'], $log['order_no'], $extraArr['name'], $extraArr['mobile'], $log['actual_num']);
  628. break;
  629. case "alipay_offline":
  630. case "bank":
  631. case "wechat":
  632. $res = true;
  633. break;
  634. case "auto":
  635. $userInfo = UserInfo::getOne([["user_id" => $log->user_id, "platform" => [User::PLATFORM_WECHAT, User::PLATFORM_MP_WX], "status" => StatusEnum::ENABLED]]);
  636. try {
  637. $cash['extra'] = [];
  638. $payment = new PayService();
  639. $paymentTransfer = new PaymentTransfer();
  640. $paymentTransfer->orderNo = PaymentTransfer::generate_order_no("TX");
  641. $paymentTransfer->user = $userInfo;
  642. $paymentTransfer->title = "收益提现";
  643. $paymentTransfer->amount = $log['actual_num'];
  644. $paymentTransfer->transferType = PayTypeEnum::WECHAT;
  645. $paymentTransfer->cashInfo = json_decode(json_encode($cash));
  646. $paymentTransfer->withdrawal_source = 'Store';
  647. $paymentTransfer->withdrawal_source_id = $log['id'];
  648. $res = $payment->transfer($paymentTransfer);
  649. } catch (Exception $e) {
  650. throw new \Exception($e->getMessage());
  651. }
  652. break;
  653. case 'alipay_tax':
  654. break;
  655. }
  656. if ($res) {
  657. $log->withdraw_status = $params['withdraw_status'];
  658. $log->remark = $params['remark'];
  659. $log->updated_at = time();
  660. $res = $log->save();
  661. if (!$res) {
  662. throw new \Exception($log->getErrorMessage());
  663. }
  664. }
  665. break;
  666. case 2:
  667. // 驳回提现申请,退回已经扣除的余额
  668. $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_STORE_BALANCE_WALLET, $log->store_id);
  669. $identification = uniqid();
  670. if (LockHelper::lock($lock_key, $identification, 100, 100)) {
  671. // 退回的金额
  672. $store = Store::findOne(['mall_id' => $mall_id, 'id' => $log->store_id, 'user_id' => $log->user_id]);
  673. $store->balance = bcadd($store->balance, $log->num, 2);
  674. $store->total_expenses = bcsub($store->total_expenses, $log->num, 2);
  675. $res_store = $store->save();
  676. $log->withdraw_status = $params['withdraw_status'];
  677. $log->remark = $params['remark'];
  678. $log->updated_at = time();
  679. $res = $log->save();
  680. LockHelper::uLock($lock_key, $identification);
  681. if (!$res_store) {
  682. throw new \Exception($store->getErrorMessage());
  683. }
  684. $res = true;
  685. } else {
  686. throw new \Exception('系统繁忙,请稍后再试');
  687. }
  688. break;
  689. }
  690. return $res;
  691. }catch (\Exception $e){
  692. self::$static_error = $e->getMessage();
  693. return false;
  694. }
  695. }
  696. public static function withdrawToPay($mall_id, $source_id, $order_no, $name, $mobile, $money)
  697. {
  698. // 获取设置
  699. $setting = (new SettingService($mall_id))->getSetting();
  700. if (empty($setting)) throw new \Exception('未进行代付配置');
  701. // 加锁
  702. $uniqid = uniqid();
  703. $lock_key = 'alitopay_order_lock_' . $mall_id;
  704. if (!LockHelper::lock($lock_key, $uniqid)) throw new \Exception('操作频繁请稍后重试');
  705. // 拼接数据入表
  706. $insert_data = [];
  707. $time = time();
  708. // 是否达到最低打款金额
  709. if ($money < AlitoapyEnum::MIX_WITHDRAW) {
  710. throw new \Exception("订单{$name},打款金额必须大于1元");
  711. }
  712. // 数据
  713. $data['mall_id'] = $mall_id;
  714. $data['order_sn'] = $time . rand(1000, 9999);
  715. $data['type'] = Order::TYPE_WITHDRAWAL;
  716. $data['money'] = $money;
  717. $data['name'] = $name;
  718. $data['account'] = $mobile;
  719. $data['source_id'] = $source_id;
  720. $data['source_sn'] = $order_no;
  721. $data['created_at'] = $data['updated_at'] = $time;
  722. $insert_data[] = $data;
  723. // 开启事务
  724. $db = Yii::$app->db->beginTransaction();
  725. try {
  726. // 批量插入
  727. Order::batchInsert($insert_data);
  728. // 批量修改打款中
  729. $db->commit();
  730. } catch (\Exception $e) {
  731. $db->rollBack();
  732. LockHelper::uLock($lock_key, $uniqid);
  733. throw new \Exception($e->getMessage());
  734. }
  735. // 批量进行打款
  736. $count = self::aliPay($mall_id, $insert_data);
  737. LockHelper::uLock($lock_key, $uniqid);
  738. return $count;
  739. }
  740. private static function aliPay($mall_id, array $list)
  741. {
  742. $aliapy = new AlipayService($mall_id);
  743. // 创建一个批次号
  744. $out_batch_no = 'TX' . date('Ymd') . $mall_id . rand(1000, 9999);
  745. $count = 0;
  746. $sub_msg = null;
  747. foreach ($list as $v) {
  748. // 打款
  749. $res = $aliapy->transfer(
  750. $v['money'], $v['name'], $v['account'], $v['order_sn']
  751. );
  752. if ($res['code'] == '10000') {
  753. // 打款成功
  754. Order::paySuccessBySourceIdAndOrderSn(
  755. $v['source_id'], $v['order_sn'],$res['order_id']
  756. );
  757. $count++;
  758. } else {
  759. // 打款失败
  760. Order::payFialBySourceIdAndOrderSn(
  761. $v['source_id'], $v['order_sn'], $res['sub_msg']
  762. );
  763. $sub_msg =$res['sub_msg'];
  764. }
  765. }
  766. // 设置批次号
  767. Order::setOutBatchNoByOrderSn($out_batch_no, array_column($list, 'order_sn'));
  768. if(isset($sub_msg)){
  769. throw new \Exception($sub_msg);
  770. }
  771. return $count;
  772. }
  773. /**
  774. * @name:
  775. * @msg: 导出字段列表
  776. * @param {array} $fields
  777. * @return {*}
  778. */
  779. public static function exportFieldList(array $fields = null)
  780. {
  781. $field_list = [
  782. 'nickname' => '会员昵称',
  783. 'mobile' => '手机号',
  784. 'type' => '提现方式',
  785. 'account_username' => '收款账户名',
  786. 'account_no' => '收款账户',
  787. 'account_organization' => '收款机构',
  788. 'num' => '提现金额',
  789. 'poundage_num' => '手续费',
  790. 'actual_num' => '实际打款金额',
  791. 'remark' => '备注',
  792. 'created_at' => '付款时间',
  793. ];
  794. if (empty($fields)) {
  795. return $field_list;
  796. } else {
  797. $new_list = [];
  798. foreach ($fields as $val) {
  799. if (!empty($field_list[$val])) {
  800. $new_list[$val] = $fields[$val];
  801. }
  802. }
  803. return $new_list;
  804. }
  805. }
  806. public static function exportHandle(array $data = null)
  807. {
  808. try {
  809. $download_id = $data['download_id'] ?? 0;
  810. $download = Download::findOne(['id' => $download_id]);
  811. $params = json_decode($download->params, true);
  812. // dd($params);
  813. $have_select_field_arr = [];
  814. $all_fields = self::exportFieldList();
  815. $fields = $params['fields'] ?? [];
  816. if (!empty($fields)) {
  817. foreach ($fields as $field) {
  818. $have_select_field_arr[] = $all_fields[$field];
  819. }
  820. } else {
  821. $have_select_field_arr = $all_fields;
  822. }
  823. // dd($have_select_field_arr);
  824. $csv = new CsvTool();
  825. $csv->filename = $download->name;
  826. $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($download->type);
  827. $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
  828. $csv->header = $have_select_field_arr;
  829. $cash_status_map = ['waiting-payment' => 0, 'payment' => 1, 'refund' => 2];
  830. $list_query = self::find()->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED, 'withdraw_status' => $cash_status_map[$params['curr_tabname']]]);
  831. if (!empty($params['user_id'])) {
  832. $wheres[] = ['user_id' => $params['user_id']];
  833. }
  834. if (!empty($params['nickname'])) {
  835. $users = User::find()
  836. ->select('id,nickname,mobile,avatar_url')
  837. ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED])
  838. ->andWhere(['like', 'nickname', $params['nickname']])
  839. ->asArray()
  840. ->indexBy('id')
  841. ->all();
  842. $wheres[] = ['user_id' => array_column($users, 'id')];
  843. }
  844. if (!empty($params['start_time'])) {
  845. $wheres[] = ['>=', 'created_at', strtotime($params['start_time'])];
  846. }
  847. if (!empty($params['end_time'])) {
  848. $wheres[] = ['<=', 'created_at', strtotime($params['end_time'] . ' 23:59:59')];
  849. }
  850. $rows = [];
  851. $type_map= PaymentLogic::getWithdrawTypeMap($params['mall_id']);
  852. foreach ($list_query->asArray()->batch(200) as $lists) {
  853. if (empty($users)) {
  854. $user_ids = array_column($lists, 'user_id');
  855. $users = User::find()
  856. ->select('id,nickname,mobile,avatar_url')
  857. ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED, 'id' => $user_ids])
  858. ->asArray()
  859. ->indexBy('id')
  860. ->all();
  861. }
  862. foreach ($lists as &$list) {
  863. $user = $users[$list['user_id']] ?? '';
  864. $list['nickname'] = $user['nickname'] ?? '';
  865. $list['mobile'] = $user['mobile'] ?? '';
  866. $list['account_no'] = $list['account_username'] = $list['account_organization'] = '';
  867. switch ($list['type']) {
  868. case 'bank':
  869. case 'joinpay':
  870. $extra = json_decode($list['extra'], true);
  871. $list['account_no'] = $extra['bank_card_no'] ?? '';
  872. $list['account_username'] = $extra['payer_name'] ?? '';
  873. $list['account_organization'] = $extra['bank_name'] ?? '';
  874. break;
  875. case 'alipay':
  876. $extra = json_decode($list['extra'], true);
  877. $list['account_no'] = $extra['mobile'] ?? '';
  878. $list['account_username'] = $extra['name'] ?? '';
  879. $list['account_organization'] = '';
  880. break;
  881. case 'balance':
  882. $list['account_no'] = $user['mobile'] ?? '';
  883. $list['account_username'] = $user['nickname'] ?? '';
  884. $list['account_organization'] = '平台';
  885. break;
  886. case 'auto':
  887. $list['account_no'] = $user['mobile'] ?? '';
  888. $list['account_username'] = $user['nickname'] ?? '';
  889. $list['account_organization'] = '';
  890. break;
  891. }
  892. $arr = [];
  893. foreach ($fields as $field) {
  894. if (!empty($list[$field])) {
  895. if ('created_at' == $field) {
  896. $list[$field] = date('Y-m-d H:i:s', $list[$field]);
  897. }
  898. if ('mobile' == $field) {
  899. $list[$field] = (string)$list[$field];
  900. }
  901. if($field=='type'){
  902. $list[$field] = $type_map[$list[$field]]??'';
  903. }
  904. } else {
  905. $list[$field] = '';
  906. }
  907. $arr[] = $list[$field];
  908. }
  909. $rows[] = $arr;
  910. }
  911. }
  912. // dd($rows);
  913. $csv->data = $rows;
  914. $csv->export();
  915. $csv->updateDown($download, $params['mall_id']);
  916. return true;
  917. } catch (\Exception $e) {
  918. $download->status = 3;
  919. $res = $download->save();
  920. self::setStaticError($e->getMessage());
  921. return $e->getMessage();
  922. }
  923. }
  924. /**
  925. * 打款失败,变成待打款状态,让客户自己去驳回
  926. * @param $withdraw_log
  927. * @param $msg
  928. */
  929. public static function remit_fail($withdraw_log, $msg)
  930. {
  931. $res = StoreWithdrawLog::updateAll([
  932. 'withdraw_status' => 0,
  933. 'remark' => '打款结果:' . $msg,
  934. 'updated_at' => time()
  935. ], ['id' => $withdraw_log->id]);
  936. }
  937. public static function fixTotalExpenses(){
  938. $list = StoreWithdrawLog::lists([
  939. 'where'=>[
  940. ['withdraw_status'=>[0,1]]
  941. ],
  942. 'select'=>'sum(num) as num,store_id',
  943. 'group'=>'store_id'
  944. ]);
  945. foreach ($list as $item){
  946. $store = Store::findOne(['id'=>$item['store_id']]);
  947. if($store){
  948. $store->total_expenses = $item['num'];
  949. $store->save();
  950. }
  951. }
  952. }
  953. }