UserRechargeServices.php 20 KB

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