UserRechargeServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. return true;
  284. }
  285. /**
  286. * 删除
  287. * @param int $id
  288. * @return bool
  289. */
  290. public function delRecharge(int $id)
  291. {
  292. $rechargInfo = $this->getRecharge($id);
  293. if (!$rechargInfo) throw new AdminException(100026);
  294. if ($rechargInfo->paid) {
  295. throw new AdminException(400679);
  296. }
  297. if ($this->dao->delete($id))
  298. return true;
  299. else
  300. throw new AdminException(100008);
  301. }
  302. /**
  303. * 生成充值订单号
  304. * @return bool|string
  305. */
  306. public function getOrderId()
  307. {
  308. return 'wx' . date('YmdHis', time()) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  309. }
  310. /**
  311. * 导入佣金到余额
  312. * @param int $uid
  313. * @param $price
  314. * @return bool
  315. * @throws \think\db\exception\DataNotFoundException
  316. * @throws \think\db\exception\DbException
  317. * @throws \think\db\exception\ModelNotFoundException
  318. */
  319. public function importNowMoney(int $uid, $price)
  320. {
  321. /** @var UserServices $userServices */
  322. $userServices = app()->make(UserServices::class);
  323. $user = $userServices->getUserInfo($uid);
  324. if (!$user) {
  325. throw new ApiException(100100);
  326. }
  327. /** @var UserBrokerageServices $frozenPrices */
  328. $frozenPrices = app()->make(UserBrokerageServices::class);
  329. $broken_commission = $frozenPrices->getUserFrozenPrice($uid);
  330. $commissionCount = bcsub((string)$user['brokerage_price'], (string)$broken_commission, 2);
  331. if ($price > $commissionCount) {
  332. throw new ApiException(400680);
  333. }
  334. $edit_data = [];
  335. $edit_data['now_money'] = bcadd((string)$user['now_money'], (string)$price, 2);
  336. $edit_data['brokerage_price'] = $user['brokerage_price'] > $price ? bcsub((string)$user['brokerage_price'], (string)$price, 2) : 0;
  337. if (!$userServices->update($uid, $edit_data, 'uid')) {
  338. throw new ApiException(100007);
  339. }
  340. //写入充值记录
  341. $rechargeInfo = [
  342. 'uid' => $uid,
  343. 'order_id' => app()->make(StoreOrderCreateServices::class)->getNewOrderId('cz'),
  344. 'recharge_type' => 'balance',
  345. 'price' => $price,
  346. 'give_price' => 0,
  347. 'paid' => 1,
  348. 'pay_time' => time(),
  349. 'add_time' => time()
  350. ];
  351. if (!$re = $this->dao->save($rechargeInfo)) {
  352. throw new ApiException(400681);
  353. }
  354. //余额记录
  355. /** @var UserMoneyServices $userMoneyServices */
  356. $userMoneyServices = app()->make(UserMoneyServices::class);
  357. $userMoneyServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['now_money'], $re['id']);
  358. //写入提现记录
  359. $extractInfo = [
  360. 'uid' => $uid,
  361. 'real_name' => $user['nickname'],
  362. 'extract_type' => 'balance',
  363. 'extract_price' => $price,
  364. 'balance' => $user['brokerage_price'],
  365. 'add_time' => time(),
  366. 'status' => 1
  367. ];
  368. /** @var UserExtractServices $userExtract */
  369. $userExtract = app()->make(UserExtractServices::class);
  370. $userExtract->save($extractInfo);
  371. //佣金提现记录
  372. /** @var UserBrokerageServices $userBrokerageServices */
  373. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  374. $userBrokerageServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['brokerage_price'], $re['id']);
  375. return true;
  376. }
  377. /**
  378. * 申请充值
  379. * @param int $uid
  380. * @param $price
  381. * @param $recharId
  382. * @param $type
  383. * @param $from
  384. * @param bool $renten
  385. * @return mixed
  386. * @throws \think\db\exception\DataNotFoundException
  387. * @throws \think\db\exception\DbException
  388. * @throws \think\db\exception\ModelNotFoundException
  389. */
  390. public function recharge(int $uid, $price, $recharId, $type, $from, bool $renten = false)
  391. {
  392. /** @var UserServices $userServices */
  393. $userServices = app()->make(UserServices::class);
  394. $user = $userServices->getUserInfo($uid);
  395. if (!$user) {
  396. throw new ApiException(400214);
  397. }
  398. switch ((int)$type) {
  399. case 0: //支付充值余额
  400. $paid_price = 0;
  401. if ($recharId) {
  402. /** @var SystemGroupDataServices $systemGroupData */
  403. $systemGroupData = app()->make(SystemGroupDataServices::class);
  404. $data = $systemGroupData->getDateValue($recharId);
  405. if ($data === false) {
  406. throw new ApiException(400682);
  407. } else {
  408. $paid_price = $data['give_money'] ?? 0;
  409. $price = $data['price'] ?? 0;
  410. }
  411. }
  412. $recharge_data = [];
  413. $recharge_data['order_id'] = app()->make(StoreOrderCreateServices::class)->getNewOrderId('cz');
  414. $recharge_data['uid'] = $uid;
  415. $recharge_data['price'] = $price;
  416. $recharge_data['recharge_type'] = $from;
  417. $recharge_data['paid'] = 0;
  418. $recharge_data['add_time'] = time();
  419. $recharge_data['give_price'] = $paid_price;
  420. $recharge_data['channel_type'] = $user['user_type'];
  421. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  422. throw new ApiException(400683);
  423. }
  424. try {
  425. /** @var RechargeServices $recharge */
  426. $recharge = app()->make(RechargeServices::class);
  427. $order_info = $recharge->recharge($rechargeOrder);
  428. } catch (\Exception $e) {
  429. throw new ApiException($e->getMessage());
  430. }
  431. if ($renten) {
  432. return $order_info;
  433. }
  434. return ['msg' => '', 'type' => $from, 'data' => $order_info];
  435. case 1: //佣金转入余额
  436. $this->importNowMoney($uid, $price);
  437. return ['msg' => '转入余额成功', 'type' => $from, 'data' => []];
  438. default:
  439. throw new ApiException(100100);
  440. }
  441. }
  442. /**
  443. * 用户充值成功后
  444. * @param $orderId
  445. * @param array $other
  446. * @return bool
  447. * @throws \think\db\exception\DataNotFoundException
  448. * @throws \think\db\exception\DbException
  449. * @throws \think\db\exception\ModelNotFoundException
  450. */
  451. public function rechargeSuccess($orderId, array $other = [])
  452. {
  453. $order = $this->dao->getOne(['order_id' => $orderId, 'paid' => 0]);
  454. if (!$order) {
  455. throw new ApiException(410173);
  456. }
  457. /** @var UserServices $userServices */
  458. $userServices = app()->make(UserServices::class);
  459. $user = $userServices->getUserInfo((int)$order['uid']);
  460. if (!$user) {
  461. throw new ApiException(410032);
  462. }
  463. $price = bcadd((string)$order['price'], (string)$order['give_price'], 2);
  464. if (!$this->dao->update($order['id'], ['paid' => 1, 'recharge_type' => $other['pay_type'], 'pay_time' => time(), 'trade_no' => $other['trade_no'] ?? ''], 'id')) {
  465. throw new ApiException(410286);
  466. }
  467. $now_money = bcadd((string)$user['now_money'], (string)$price, 2);
  468. /** @var UserMoneyServices $userMoneyServices */
  469. $userMoneyServices = app()->make(UserMoneyServices::class);
  470. $userMoneyServices->income('user_recharge', $user['uid'], ['number' => $price, 'price' => $order['price'], 'give_price' => $order['give_price']], $now_money, $order['id']);
  471. if (!$userServices->update((int)$order['uid'], ['now_money' => $now_money], 'uid')) {
  472. throw new ApiException(410287);
  473. }
  474. /** @var CapitalFlowServices $capitalFlowServices */
  475. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  476. $order['nickname'] = $user['nickname'];
  477. $order['phone'] = $user['phone'];
  478. $capitalFlowServices->setFlow($order, 'recharge');
  479. //提醒推送
  480. event('NoticeListener', [['order' => $order, 'now_money' => $now_money], 'recharge_success']);
  481. //自定义消息-订单拒绝退款
  482. $order['now_money'] = $now_money;
  483. $order['time'] = date('Y-m-d H:i:s');
  484. event('CustomNoticeListener', [$order['uid'], $order, 'recharge_success']);
  485. $order['pay_type'] = $other['pay_type'];
  486. // 小程序订单服务
  487. event('OrderShipping', ['recharge', $order, 3, '', '']);
  488. return true;
  489. }
  490. /**
  491. * 根据查询用户充值金额
  492. * @param array $where
  493. * @param string $rechargeSumField
  494. * @param string $selectType
  495. * @param string $group
  496. * @return float|int
  497. */
  498. public function getRechargeMoneyByWhere(array $where, string $rechargeSumField, string $selectType, string $group = "")
  499. {
  500. switch ($selectType) {
  501. case "sum" :
  502. return $this->dao->getWhereSumField($where, $rechargeSumField);
  503. case "group" :
  504. return $this->dao->getGroupField($where, $rechargeSumField, $group);
  505. }
  506. }
  507. }