UserRechargeServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\services\user;
  13. use app\dao\user\UserRechargeDao;
  14. use app\services\BaseServices;
  15. use app\services\order\StoreOrderCreateServices;
  16. use app\services\pay\PayServices;
  17. use app\services\pay\RechargeServices;
  18. use app\services\statistic\CapitalFlowServices;
  19. use app\services\system\config\SystemGroupDataServices;
  20. use app\services\wechat\WechatUserServices;
  21. use crmeb\exceptions\AdminException;
  22. use crmeb\exceptions\ApiException;
  23. use crmeb\services\FormBuilder as Form;
  24. use crmeb\services\pay\Pay;
  25. use think\facade\Route as Url;
  26. /**
  27. *
  28. * Class UserRechargeServices
  29. * @package app\services\user
  30. * @method be($map, string $field = '') 查询一条数据是否存在
  31. * @method getDistinctCount(array $where, $field, ?bool $search = true)
  32. * @method getTrendData($time, $type, $timeType)
  33. */
  34. class UserRechargeServices extends BaseServices
  35. {
  36. /**
  37. * UserRechargeServices constructor.
  38. * @param UserRechargeDao $dao
  39. */
  40. public function __construct(UserRechargeDao $dao)
  41. {
  42. $this->dao = $dao;
  43. }
  44. /**
  45. * 获取单条数据
  46. * @param int $id
  47. * @param array $field
  48. */
  49. public function getRecharge(int $id, array $field = [])
  50. {
  51. return $this->dao->get($id, $field);
  52. }
  53. /**
  54. * 获取统计数据
  55. * @param array $where
  56. * @param string $field
  57. * @return float
  58. */
  59. public function getRechargeSum(array $where, string $field = '')
  60. {
  61. $whereData = [];
  62. if (isset($where['data'])) {
  63. $whereData['time'] = $where['data'];
  64. }
  65. if (isset($where['paid']) && $where['paid'] != '') {
  66. $whereData['paid'] = $where['paid'];
  67. }
  68. if (isset($where['nickname']) && $where['nickname']) {
  69. $whereData['like'] = $where['nickname'];
  70. }
  71. if (isset($where['recharge_type']) && $where['recharge_type']) {
  72. $whereData['recharge_type'] = $where['recharge_type'];
  73. }
  74. return $this->dao->getWhereSumField($whereData, $field);
  75. }
  76. /**
  77. * 获取充值列表
  78. * @param array $where
  79. * @param string $field
  80. * @return array
  81. */
  82. public function getRechargeList(array $where, string $field = '*', $is_page = true)
  83. {
  84. $whereData = [];
  85. if (isset($where['data'])) {
  86. $whereData['time'] = $where['data'];
  87. }
  88. if (isset($where['paid']) && $where['paid'] != '') {
  89. $whereData['paid'] = $where['paid'];
  90. }
  91. if (isset($where['nickname']) && $where['nickname']) {
  92. $whereData['like'] = $where['nickname'];
  93. }
  94. [$page, $limit] = $this->getPageValue($is_page);
  95. $list = $this->dao->getList($whereData, $field, $page, $limit);
  96. $count = $this->dao->count($whereData);
  97. foreach ($list as &$item) {
  98. switch ($item['recharge_type']) {
  99. case PayServices::WEIXIN_PAY:
  100. $item['_recharge_type'] = '微信充值';
  101. break;
  102. case 'system':
  103. $item['_recharge_type'] = '系统充值';
  104. break;
  105. case PayServices::ALIAPY_PAY:
  106. $item['_recharge_type'] = '支付宝充值';
  107. break;
  108. default:
  109. $item['_recharge_type'] = '其他充值';
  110. break;
  111. }
  112. $item['_pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '暂无';
  113. $item['_add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '暂无';
  114. $item['paid_type'] = $item['paid'] ? '已支付' : '未支付';
  115. $item['avatar'] = strpos($item['avatar'] ?? '', 'http') === false ? (sys_config('site_url') . $item['avatar']) : $item['avatar'];
  116. unset($item['user']);
  117. }
  118. return compact('list', 'count');
  119. }
  120. /**
  121. * 获取用户充值数据
  122. * @return array
  123. */
  124. public function user_recharge(array $where)
  125. {
  126. $data = [];
  127. $data['sumPrice'] = $this->getRechargeSum($where, 'price');
  128. $data['sumRefundPrice'] = $this->getRechargeSum($where, 'refund_price');
  129. $where['recharge_type'] = 'alipay';
  130. $data['sumAlipayPrice'] = $this->getRechargeSum($where, 'price');
  131. $where['recharge_type'] = 'weixin';
  132. $data['sumWeixinPrice'] = $this->getRechargeSum($where, 'price');
  133. return [
  134. [
  135. 'name' => '充值总金额',
  136. 'field' => '元',
  137. 'count' => $data['sumPrice'],
  138. 'className' => 'iconjiaoyijine',
  139. 'col' => 6,
  140. ],
  141. [
  142. 'name' => '充值退款金额',
  143. 'field' => '元',
  144. 'count' => $data['sumRefundPrice'],
  145. 'className' => 'iconshangpintuikuanjine',
  146. 'col' => 6,
  147. ],
  148. [
  149. 'name' => '支付宝充值金额',
  150. 'field' => '元',
  151. 'count' => $data['sumAlipayPrice'],
  152. 'className' => 'iconzhifubao',
  153. 'col' => 6,
  154. ],
  155. [
  156. 'name' => '微信充值金额',
  157. 'field' => '元',
  158. 'count' => $data['sumWeixinPrice'],
  159. 'className' => 'iconweixinzhifu',
  160. 'col' => 6,
  161. ],
  162. ];
  163. }
  164. /**
  165. * 退款表单
  166. * @param int $id
  167. * @return array
  168. * @throws \FormBuilder\Exception\FormBuilderException
  169. * @author 吴汐
  170. * @email 442384644@qq.com
  171. * @date 2023/03/24
  172. */
  173. public function refund_edit(int $id)
  174. {
  175. $UserRecharge = $this->getRecharge($id);
  176. if (!$UserRecharge) {
  177. throw new AdminException(100026);
  178. }
  179. if ($UserRecharge['paid'] != 1) {
  180. throw new AdminException(400677);
  181. }
  182. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  183. throw new AdminException(400147);
  184. }
  185. if ($UserRecharge['recharge_type'] == 'balance') {
  186. throw new AdminException(400678);
  187. }
  188. $f = array();
  189. $f[] = Form::input('order_id', '退款单号', $UserRecharge->getData('order_id'))->disabled(true);
  190. $f[] = Form::radio('refund_price', '状态', 1)->options([['label' => '本金(扣赠送余额)', 'value' => 1], ['label' => '仅本金', 'value' => 0]]);
  191. return create_form('编辑', $f, Url::buildUrl('/finance/recharge/' . $id), 'PUT');
  192. }
  193. /**
  194. * 退款操作
  195. * @param int $id
  196. * @param string $refund_price
  197. * @return mixed
  198. * @throws \think\db\exception\DataNotFoundException
  199. * @throws \think\db\exception\DbException
  200. * @throws \think\db\exception\ModelNotFoundException
  201. */
  202. public function refund_update(int $id, string $refund_price)
  203. {
  204. $UserRecharge = $this->getRecharge($id);
  205. if (!$UserRecharge) {
  206. throw new AdminException(100026);
  207. }
  208. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  209. throw new AdminException(400147);
  210. }
  211. if ($UserRecharge['recharge_type'] == 'balance') {
  212. throw new AdminException(400678);
  213. }
  214. $data['refund_price'] = $UserRecharge['price'];
  215. $refund_data['pay_price'] = $UserRecharge['price'];
  216. $refund_data['refund_price'] = $UserRecharge['price'];
  217. if ($refund_price == 1) {
  218. $number = bcadd($UserRecharge['price'], $UserRecharge['give_price'], 2);
  219. } else {
  220. $number = $UserRecharge['price'];
  221. }
  222. try {
  223. $recharge_type = $UserRecharge['recharge_type'];
  224. if ($recharge_type == 'weixin') {
  225. $refund_data['wechat'] = true;
  226. } else {
  227. $refund_data['trade_no'] = $UserRecharge['trade_no'];
  228. $refund_data['order_id'] = $UserRecharge['order_id'];
  229. /** @var WechatUserServices $wechatUserServices */
  230. $wechatUserServices = app()->make(WechatUserServices::class);
  231. $refund_data['open_id'] = $wechatUserServices->uidToOpenid((int)$UserRecharge['uid'], 'routine') ?? '';
  232. $refund_data['pay_new_weixin_open'] = sys_config('pay_new_weixin_open');
  233. /** @var StoreOrderCreateServices $storeOrderCreateServices */
  234. $storeOrderCreateServices = app()->make(StoreOrderCreateServices::class);
  235. $refund_data['refund_no'] = $storeOrderCreateServices->getNewOrderId('tk');
  236. }
  237. if ($recharge_type == 'allinpay') {
  238. $drivers = 'allin_pay';
  239. $trade_no = $UserRecharge['trade_no'];
  240. } elseif (sys_config('pay_wechat_type')) {
  241. $drivers = 'v3_wechat_pay';
  242. $trade_no = $UserRecharge['trade_no'];
  243. } else {
  244. $drivers = 'wechat_pay';
  245. $trade_no = $UserRecharge['order_id'];
  246. }
  247. /** @var Pay $pay */
  248. $pay = app()->make(Pay::class, [$drivers]);
  249. $pay->refund($trade_no, $refund_data);
  250. } catch (\Exception $e) {
  251. throw new AdminException($e->getMessage());
  252. }
  253. if (!$this->dao->update($id, $data)) {
  254. throw new AdminException(100007);
  255. }
  256. //修改用户余额
  257. /** @var UserServices $userServices */
  258. $userServices = app()->make(UserServices::class);
  259. $userInfo = $userServices->getUserInfo($UserRecharge['uid']);
  260. if ($userInfo['now_money'] > $number) {
  261. $now_money = bcsub((string)$userInfo['now_money'], $number, 2);
  262. } else {
  263. $number = $userInfo['now_money'];
  264. $now_money = 0;
  265. }
  266. $userServices->update((int)$UserRecharge['uid'], ['now_money' => $now_money], 'uid');
  267. //写入资金流水
  268. /** @var CapitalFlowServices $capitalFlowServices */
  269. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  270. $UserRecharge['nickname'] = $userInfo['nickname'];
  271. $UserRecharge['phone'] = $userInfo['phone'];
  272. $capitalFlowServices->setFlow($UserRecharge, 'refund_recharge');
  273. //保存余额记录
  274. /** @var UserMoneyServices $userMoneyServices */
  275. $userMoneyServices = app()->make(UserMoneyServices::class);
  276. $userMoneyServices->income('user_recharge_refund', $UserRecharge['uid'], $number, $now_money, $id);
  277. //提醒推送
  278. event('NoticeListener', [['user_type' => strtolower($userInfo['user_type']), 'data' => $data, 'UserRecharge' => $UserRecharge, 'now_money' => $refund_price], 'recharge_order_refund_status']);
  279. //自定义通知-充值退款
  280. $UserRecharge['now_money'] = $now_money;
  281. $UserRecharge['time'] = date('Y-m-d H:i:s');
  282. event('NoticeListener', [$UserRecharge['uid'], $UserRecharge, 'recharge_refund']);
  283. //自定义事件-后台充值退款
  284. event('CustomEventListener', ['admin_recharge_refund', [
  285. 'uid' => $UserRecharge['uid'],
  286. 'refund_price' => $UserRecharge['price'],
  287. 'now_money' => $now_money,
  288. 'nickname' => $UserRecharge['price'],
  289. 'phone' => $UserRecharge['phone'],
  290. 'refund_time' => date('Y-m-d H:i:s')
  291. ]]);
  292. return true;
  293. }
  294. /**
  295. * 删除
  296. * @param int $id
  297. * @return bool
  298. */
  299. public function delRecharge(int $id)
  300. {
  301. $rechargInfo = $this->getRecharge($id);
  302. if (!$rechargInfo) throw new AdminException(100026);
  303. if ($rechargInfo->paid) {
  304. throw new AdminException(400679);
  305. }
  306. if ($this->dao->delete($id))
  307. return true;
  308. else
  309. throw new AdminException(100008);
  310. }
  311. /**
  312. * 生成充值订单号
  313. * @return bool|string
  314. */
  315. public function getOrderId()
  316. {
  317. return 'wx' . date('YmdHis', time()) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  318. }
  319. /**
  320. * 导入佣金到余额
  321. * @param int $uid
  322. * @param $price
  323. * @return bool
  324. * @throws \think\db\exception\DataNotFoundException
  325. * @throws \think\db\exception\DbException
  326. * @throws \think\db\exception\ModelNotFoundException
  327. */
  328. public function importNowMoney(int $uid, $price)
  329. {
  330. /** @var UserServices $userServices */
  331. $userServices = app()->make(UserServices::class);
  332. $user = $userServices->getUserInfo($uid);
  333. if (!$user) {
  334. throw new ApiException(100100);
  335. }
  336. /** @var UserBrokerageServices $frozenPrices */
  337. $frozenPrices = app()->make(UserBrokerageServices::class);
  338. $broken_commission = $frozenPrices->getUserFrozenPrice($uid);
  339. $commissionCount = bcsub((string)$user['brokerage_price'], (string)$broken_commission, 2);
  340. if ($price > $commissionCount) {
  341. throw new ApiException(400680);
  342. }
  343. $edit_data = [];
  344. $edit_data['now_money'] = bcadd((string)$user['now_money'], (string)$price, 2);
  345. $edit_data['brokerage_price'] = $user['brokerage_price'] > $price ? bcsub((string)$user['brokerage_price'], (string)$price, 2) : 0;
  346. if (!$userServices->update($uid, $edit_data, 'uid')) {
  347. throw new ApiException(100007);
  348. }
  349. //写入充值记录
  350. $rechargeInfo = [
  351. 'uid' => $uid,
  352. 'order_id' => app()->make(StoreOrderCreateServices::class)->getNewOrderId('cz'),
  353. 'recharge_type' => 'balance',
  354. 'price' => $price,
  355. 'give_price' => 0,
  356. 'paid' => 1,
  357. 'pay_time' => time(),
  358. 'add_time' => time()
  359. ];
  360. if (!$re = $this->dao->save($rechargeInfo)) {
  361. throw new ApiException(400681);
  362. }
  363. //余额记录
  364. /** @var UserMoneyServices $userMoneyServices */
  365. $userMoneyServices = app()->make(UserMoneyServices::class);
  366. $userMoneyServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['now_money'], $re['id']);
  367. //写入提现记录
  368. $extractInfo = [
  369. 'uid' => $uid,
  370. 'real_name' => $user['nickname'],
  371. 'extract_type' => 'balance',
  372. 'extract_price' => $price,
  373. 'balance' => $user['brokerage_price'],
  374. 'add_time' => time(),
  375. 'status' => 1
  376. ];
  377. /** @var UserExtractServices $userExtract */
  378. $userExtract = app()->make(UserExtractServices::class);
  379. $userExtract->save($extractInfo);
  380. //佣金提现记录
  381. /** @var UserBrokerageServices $userBrokerageServices */
  382. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  383. $userBrokerageServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['brokerage_price'], $re['id']);
  384. return true;
  385. }
  386. /**
  387. * 申请充值
  388. * @param int $uid
  389. * @param $price
  390. * @param $recharId
  391. * @param $type
  392. * @param $from
  393. * @param bool $renten
  394. * @return mixed
  395. * @throws \think\db\exception\DataNotFoundException
  396. * @throws \think\db\exception\DbException
  397. * @throws \think\db\exception\ModelNotFoundException
  398. */
  399. public function recharge(int $uid, $price, $recharId, $type, $from, bool $renten = false)
  400. {
  401. /** @var UserServices $userServices */
  402. $userServices = app()->make(UserServices::class);
  403. $user = $userServices->getUserInfo($uid);
  404. if (!$user) {
  405. throw new ApiException(400214);
  406. }
  407. switch ((int)$type) {
  408. case 0: //支付充值余额
  409. $paid_price = 0;
  410. if ($recharId) {
  411. /** @var SystemGroupDataServices $systemGroupData */
  412. $systemGroupData = app()->make(SystemGroupDataServices::class);
  413. $data = $systemGroupData->getDateValue($recharId);
  414. if ($data === false) {
  415. throw new ApiException(400682);
  416. } else {
  417. $paid_price = $data['give_money'] ?? 0;
  418. $price = $data['price'] ?? 0;
  419. }
  420. }
  421. $recharge_data = [];
  422. $recharge_data['order_id'] = app()->make(StoreOrderCreateServices::class)->getNewOrderId('cz');
  423. $recharge_data['uid'] = $uid;
  424. $recharge_data['price'] = $price;
  425. $recharge_data['recharge_type'] = $from;
  426. $recharge_data['paid'] = 0;
  427. $recharge_data['add_time'] = time();
  428. $recharge_data['give_price'] = $paid_price;
  429. $recharge_data['channel_type'] = $user['user_type'];
  430. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  431. throw new ApiException(400683);
  432. }
  433. try {
  434. /** @var RechargeServices $recharge */
  435. $recharge = app()->make(RechargeServices::class);
  436. $order_info = $recharge->recharge($rechargeOrder);
  437. } catch (\Exception $e) {
  438. throw new ApiException($e->getMessage());
  439. }
  440. if ($renten) {
  441. return $order_info;
  442. }
  443. return ['msg' => '', 'type' => $from, 'data' => $order_info];
  444. case 1: //佣金转入余额
  445. $this->importNowMoney($uid, $price);
  446. return ['msg' => '转入余额成功', 'type' => $from, 'data' => []];
  447. default:
  448. throw new ApiException(100100);
  449. }
  450. }
  451. /**
  452. * 用户充值成功后
  453. * @param $orderId
  454. * @param array $other
  455. * @return bool
  456. * @throws \think\db\exception\DataNotFoundException
  457. * @throws \think\db\exception\DbException
  458. * @throws \think\db\exception\ModelNotFoundException
  459. */
  460. public function rechargeSuccess($orderId, array $other = [])
  461. {
  462. $order = $this->dao->getOne(['order_id' => $orderId, 'paid' => 0]);
  463. if (!$order) {
  464. throw new ApiException(410173);
  465. }
  466. /** @var UserServices $userServices */
  467. $userServices = app()->make(UserServices::class);
  468. $user = $userServices->getUserInfo((int)$order['uid']);
  469. if (!$user) {
  470. throw new ApiException(410032);
  471. }
  472. $price = bcadd((string)$order['price'], (string)$order['give_price'], 2);
  473. if (!$this->dao->update($order['id'], ['paid' => 1, 'recharge_type' => $other['pay_type'], 'pay_time' => time(), 'trade_no' => $other['trade_no'] ?? ''], 'id')) {
  474. throw new ApiException(410286);
  475. }
  476. $now_money = bcadd((string)$user['now_money'], (string)$price, 2);
  477. /** @var UserMoneyServices $userMoneyServices */
  478. $userMoneyServices = app()->make(UserMoneyServices::class);
  479. $userMoneyServices->income('user_recharge', $user['uid'], ['number' => $price, 'price' => $order['price'], 'give_price' => $order['give_price']], $now_money, $order['id']);
  480. if (!$userServices->update((int)$order['uid'], ['now_money' => $now_money], 'uid')) {
  481. throw new ApiException(410287);
  482. }
  483. /** @var CapitalFlowServices $capitalFlowServices */
  484. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  485. $order['nickname'] = $user['nickname'];
  486. $order['phone'] = $user['phone'];
  487. $capitalFlowServices->setFlow($order, 'recharge');
  488. //提醒推送
  489. event('NoticeListener', [['order' => $order, 'now_money' => $now_money], 'recharge_success']);
  490. //自定义消息-订单拒绝退款
  491. $order['now_money'] = $now_money;
  492. $order['time'] = date('Y-m-d H:i:s');
  493. event('CustomNoticeListener', [$order['uid'], $order, 'recharge_success']);
  494. $order['pay_type'] = $other['pay_type'];
  495. // 小程序订单服务
  496. event('OrderShippingListener', ['recharge', $order, 3, '', '']);
  497. //自定义事件-用户充值
  498. event('CustomEventListener', ['user_recharge', [
  499. 'uid' => $order['uid'],
  500. 'id' => (int)$order['id'],
  501. 'order_id' => $orderId,
  502. 'nickname' => $order['nickname'],
  503. 'phone' => $order['phone'],
  504. 'price' => $order['price'],
  505. 'give_price' => $order['give_price'],
  506. 'now_money' => $order['now_money'],
  507. 'recharge_time' => date('Y-m-d H:i:s'),
  508. ]]);
  509. return true;
  510. }
  511. /**
  512. * 根据查询用户充值金额
  513. * @param array $where
  514. * @param string $rechargeSumField
  515. * @param string $selectType
  516. * @param string $group
  517. * @return float|int
  518. */
  519. public function getRechargeMoneyByWhere(array $where, string $rechargeSumField, string $selectType, string $group = "")
  520. {
  521. switch ($selectType) {
  522. case "sum" :
  523. return $this->dao->getWhereSumField($where, $rechargeSumField);
  524. case "group" :
  525. return $this->dao->getGroupField($where, $rechargeSumField, $group);
  526. }
  527. }
  528. }