Wallet.php 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace addons\shopro\service;
  3. use think\exception\HttpResponseException;
  4. use app\admin\model\shopro\user\User as UserModel;
  5. use app\admin\model\shopro\user\WalletLog;
  6. use addons\shopro\library\Operator;
  7. use app\common\model\MoneyLog;
  8. use app\common\model\ScoreLog;
  9. class Wallet
  10. {
  11. /**
  12. * @name 变更会员资金
  13. * @param int|object $user 会员对象或会员ID
  14. * @param string $type 变更类型:money=余额,commission=佣金,score=积分
  15. * @param float|string $amount 变更数量
  16. * @param array $ext 扩展字段
  17. * @param string $memo 备注
  18. * @return boolean
  19. */
  20. public static function change($user, $type, $amount, $event, $ext = [], $memo = '')
  21. {
  22. // 判断用户
  23. if (is_numeric($user)) {
  24. $user = UserModel::getById($user);
  25. }
  26. if (!$user) {
  27. error_stop('未找到用户');
  28. }
  29. // 判断金额
  30. if ($amount == 0) {
  31. error_stop('请输入正确的金额');
  32. }
  33. if (!in_array($type, ['money', 'score', 'commission'])) {
  34. error_stop('参数错误');
  35. }
  36. $before = $user->$type;
  37. $after = bcadd((string)$user->$type, (string)$amount, 2);
  38. // 只有后台扣除用户余额、扣除用户积分、佣金退回,钱包才可以是负值
  39. if ($after < 0 && !in_array($event, ['admin_recharge', 'reward_back'])) {
  40. $walletTypeText = WalletLog::TYPE_MAP[$type];
  41. error_stop("可用{$walletTypeText}不足");
  42. }
  43. try {
  44. // 更新会员余额信息
  45. $user->setInc($type, $amount);
  46. // 获取操作人
  47. $oper = Operator::get();
  48. // 写入日志
  49. $walletLog = WalletLog::create([
  50. 'user_id' => $user->id,
  51. 'amount' => $amount,
  52. 'type' => $type,
  53. 'before' => $before,
  54. 'after' => $after,
  55. 'event' => $event,
  56. 'memo' => $memo,
  57. 'ext' => $ext,
  58. 'oper_type' => $oper['type'],
  59. 'oper_id' => $oper['id']
  60. ]);
  61. // 钱包和积分记录存到 fastadmin 钱包积分记录表
  62. /*if (in_array($type, ['money', 'score'])) {
  63. $eventMap = (new WalletLog)->getEventMap();
  64. $memo = $memo ?: $eventMap[$type][$event] ?? '';
  65. if ($type === 'money') {
  66. MoneyLog::create(['user_id' => $user->id, 'money' => $amount, 'before' => $before, 'after' => $after, 'memo' => $memo]);
  67. } else if ($type === 'score') {
  68. ScoreLog::create(['user_id' => $user->id, 'score' => $amount, 'before' => $before, 'after' => $after, 'memo' => $memo]);
  69. }
  70. }*/
  71. // 账户变动事件
  72. $data = ['walletLog' => $walletLog, 'type' => $type];
  73. \think\Hook::listen('user_wallet_change', $data);
  74. } catch (HttpResponseException $e) {
  75. $data = $e->getResponse()->getData();
  76. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  77. error_stop($message);
  78. } catch (\Exception $e) {
  79. error_stop('您提交的数据不正确');
  80. }
  81. return true;
  82. }
  83. }