MemberService.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Api;
  12. use App\Helpers\Jwt;
  13. use App\Models\AccountLogModel;
  14. use App\Models\BalanceLogModel;
  15. use App\Models\LiveModel;
  16. use App\Models\MemberBankModel;
  17. use App\Models\MemberModel;
  18. use App\Models\MerchantModel;
  19. use App\Models\VideoModel;
  20. use App\Services\BaseService;
  21. use App\Services\CityService;
  22. use App\Services\ConfigService;
  23. use App\Services\EmailService;
  24. use App\Services\RedisService;
  25. use App\Services\SmsService;
  26. use App\Services\ToolService;
  27. use App\Services\UdunpayService;
  28. use App\Services\WalletService;
  29. use Illuminate\Support\Facades\DB;
  30. use phpQrcode\QRcode;
  31. /**
  32. * 会员管理-服务类
  33. * @author laravel开发员
  34. * @since 2020/11/11
  35. * Class MemberService
  36. * @package App\Services\Api
  37. */
  38. class MemberService extends BaseService
  39. {
  40. // 静态对象
  41. protected static $instance = null;
  42. /**
  43. * 构造函数
  44. * @author laravel开发员
  45. * @since 2020/11/11
  46. * MemberService constructor.
  47. */
  48. public function __construct()
  49. {
  50. $this->model = new MemberModel();
  51. }
  52. /**
  53. * 静态入口
  54. * @return MemberService|static|null
  55. */
  56. public static function make()
  57. {
  58. if (!self::$instance) {
  59. self::$instance = new static();
  60. }
  61. return self::$instance;
  62. }
  63. /**
  64. * 获取资料详情
  65. * @param $where
  66. * @param array $field
  67. */
  68. public function getInfo($where, $type = 'detail', array $field = [], $userId=0)
  69. {
  70. $defaultField = ['id', 'username','email', 'realname', 'mobile','gender','member_level', 'nickname', 'code','supper_point', 'parent_id','province_id','city_id','signature','power_num','trade_state','trc_url','recharge_trc_url', 'point_id', 'balance','trx','usdt','wait_score', 'score','pay_password','realname','idcard_check', 'member_level', 'status', 'avatar'];
  71. $withs = ['merchant','acceptor','parent','point','level'];
  72. if ($type == 'team') {
  73. $defaultField = ['id', 'username','email','member_level', 'nickname', 'code', 'balance', 'score','point_id','power_num','parent_id', 'status', 'avatar'];
  74. }else if($type == 'share'){
  75. $withs = ['parent','level'];
  76. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url', 'score', 'status', 'avatar'];
  77. }else if($type == 'check'){
  78. $withs = ['parent','level'];
  79. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url','wait_score', 'score', 'status', 'avatar'];
  80. }else if ($type == 'info'){
  81. $withs = ['parent','level'];
  82. }
  83. $field = $field ? $field : $defaultField;
  84. if (is_array($where)) {
  85. $info = $this->model->with($withs)->where('mark',1)->where($where)->select($field)->first();
  86. } else {
  87. $info = $this->model->with($withs)->where('mark',1)->where(['id' => (int)$where])->select($field)->first();
  88. }
  89. $info = $info ? $info->toArray() : [];
  90. if ($info && !in_array($type, ['auth', 'check','login'])) {
  91. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  92. $info['balance'] = moneyFormat($info['balance'], 2);
  93. $info['usdt'] = moneyFormat($info['usdt'], 2);
  94. $info['score'] = moneyFormat($info['score'], 2);
  95. // 二维码
  96. if (in_array($type, ['detail'])) {
  97. if (isset($info['wxpay_qrcode'])) {
  98. $info['wxpay_qrcode'] = $info['wxpay_qrcode'] ? get_image_url($info['wxpay_qrcode']) : '';
  99. }
  100. if (isset($info['alipay_qrcode'])) {
  101. $info['alipay_qrcode'] = $info['alipay_qrcode'] ? get_image_url($info['alipay_qrcode']) : '';
  102. }
  103. $info['parent'] = $info['parent']? $info['parent'] : ['id'=>0,'nickname' => '无', 'code' => '无'];
  104. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  105. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  106. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  107. if($userId != $info['id']){
  108. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  109. }else{
  110. $info['is_follow'] = 1;
  111. }
  112. }
  113. else if ($type == 'info') {
  114. $liveOpenLevel = ConfigService::make()->getConfigByCode('live_open_level',0);
  115. $liveOpenLevel = $liveOpenLevel>0? $liveOpenLevel : 0;
  116. $info['live_open'] = $info['member_level']>=$liveOpenLevel? 1 : 0;
  117. }
  118. else if ($type == 'recharge') {
  119. $wallet = WalletService::make()->getWallet(1);
  120. $info['recharge_trc_url'] = isset($wallet['address'])? $wallet['address'] : '';
  121. $info['xd_price'] = ConfigService::make()->getConfigByCode('xd_price',100);
  122. if($info['recharge_trc_url']){
  123. $qrcode = $this->makeQrcode($info['recharge_trc_url']);
  124. $info['trc_qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  125. }else{
  126. $info['trc_qrcode'] = '';
  127. }
  128. }
  129. else if ($type == 'team' || $type == 'share') {
  130. $inviteUrl = get_web_url('/#/pages/register/index?code=' . $info['code']);
  131. $qrcode = $this->makeQrcode($inviteUrl);
  132. $info['qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  133. $info['invite_url'] = $inviteUrl;
  134. $info['qrcode_base64'] = $qrcode?getImageContent($qrcode):'';
  135. $info['team_count1'] = $this->getUserCountByType($info['id'], 1, 0); // 直推人数
  136. $info['team_count2'] = $this->getUserCountByType($info['id'], 3, 0); // 滑落人数
  137. $info['team_count'] = $this->getUserCountByType($info['id'], 2, 0); // 团队人数
  138. }else {
  139. // 默认地址
  140. $info['addressData'] = MemberAddressService::make()->getBindInfo($info['id']);
  141. }
  142. }
  143. return $info;
  144. }
  145. /**
  146. * 获取主页信息
  147. * @param $where
  148. * @param array $field
  149. */
  150. public function getHomeInfo($id, $userId=0)
  151. {
  152. $field = ['id', 'username','email', 'realname', 'mobile','gender', 'nickname', 'code','supper_point', 'parent_id','province_id','city_id','signature','power_num','trade_state', 'point_id', 'balance','trx','usdt','wait_score', 'score','realname', 'member_level', 'status', 'avatar'];
  153. $info = $this->model->where('mark',1)->where(['id' => $id])->select($field)->first();
  154. $info = $info ? $info->toArray() : [];
  155. if ($info) {
  156. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  157. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  158. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  159. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  160. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  161. $info['is_fans'] = (int)MemberCollectService::make()->checkCollect($info['id'], $userId,1); // 是否我的粉丝
  162. $info['live_id'] = (int)LiveModel::where(['user_id'=> $info['id'],'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id'); // 是否正在直播
  163. }
  164. return $info;
  165. }
  166. /**
  167. * 获取用户缓存信息
  168. * @param $where
  169. * @param array $field
  170. * @param int $expired
  171. * @return array|mixed
  172. */
  173. public function getCacheInfo($where, $field = [], $expired = 0)
  174. {
  175. $cacheKey = "caches:member:info:cache_" . md5(json_encode($where, 256) . json_encode($field, 256) . $expired);
  176. $info = RedisService::get($cacheKey);
  177. if ($info) {
  178. return $info;
  179. }
  180. $defaultField = ['id', 'username', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'balance','usdt', 'score', 'member_level', 'status', 'avatar'];
  181. $field = $field ? $field : $defaultField;
  182. $info = $this->model->where($where)->where('mark', 1)->select($field)->first();
  183. $info = $info ? $info->toArray() : [];
  184. if ($info) {
  185. if (isset($info['avatar'])) {
  186. $info['avatar'] = $info['avatar']? $info['avatar'] : '/images/member/logo.png';
  187. $info['avatar_preview'] = $info['avatar']? get_image_url($info['avatar']) : '';
  188. }
  189. RedisService::set($cacheKey, $info, $expired ? $expired : rand(3, 5));
  190. }
  191. return $info;
  192. }
  193. /**
  194. * 生成普通参数二维码
  195. * @param $str 参数
  196. * @param bool $refresh 是否重新生成
  197. * @return bool
  198. */
  199. public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
  200. {
  201. $basePath = base_path() . '/public';
  202. $qrFile = '/images/qrcode/';
  203. if (!is_dir($basePath . '/uploads' . $qrFile)) {
  204. @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
  205. }
  206. $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
  207. $qrFile = $qrFile . "C_{$key}.png";
  208. $cacheKey = "caches:qrcodes:member_" . $key;
  209. if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
  210. return $qrFile;
  211. }
  212. QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
  213. if (!file_exists($basePath . '/uploads' . $qrFile)) {
  214. return false;
  215. }
  216. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  217. return $qrFile;
  218. }
  219. /**
  220. * 获取团队用户数量
  221. * @param $userId 当前用户ID
  222. * @param int $type 层级:1-直推,2-团队
  223. * @param int $isPoint 节点:1-滑落推荐,0-直接推荐
  224. * @return array|mixed
  225. */
  226. public function getUserCountByType($userId, $type = 1, $isPoint=0)
  227. {
  228. $cacheKey = "caches:teams:count_{$userId}_{$type}_{$isPoint}";
  229. $data = RedisService::get($cacheKey);
  230. if ($data) {
  231. return $data;
  232. }
  233. $where = ['status' => 1, 'mark' => 1];
  234. $data = $this->model->where($where)
  235. ->where(function ($query) use ($type, $isPoint, $userId) {
  236. if($isPoint){
  237. if ($type == 1) { // 滑落推荐
  238. $query->where('point_id', $userId);
  239. } else if($type == 2){ // 滑落团队人数
  240. $query->whereRaw('FIND_IN_SET(?,points)', $userId);
  241. }
  242. }else{
  243. if ($type == 1) { // 直推人数
  244. $query->where('parent_id', $userId);
  245. } else if($type == 2){ // 团队人数
  246. $query->whereRaw("FIND_IN_SET({$userId},parents)");
  247. } else if($type == 3){ // 滑落人数
  248. $query->where('parent_id', $userId)->where('point_id','!=', $userId);
  249. }
  250. }
  251. })->count('id');
  252. if ($data) {
  253. RedisService::set($cacheKey, $data, rand(3, 5));
  254. }
  255. return $data;
  256. }
  257. /**
  258. * 分销用户列表
  259. * @param $userId
  260. * @param $params
  261. * @param int $pageSize
  262. * @return array
  263. */
  264. public function getTeamList($userId, $params, $pageSize=15)
  265. {
  266. $page = request()->post('page',1);
  267. $cacheKey = "caches:teams:list_{$userId}_{$page}";
  268. $datas = RedisService::get($cacheKey);
  269. if ($datas) {
  270. return [
  271. 'pageSize' => $pageSize,
  272. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  273. 'list' => isset($datas['data']) ? $datas['data'] : []
  274. ];
  275. }
  276. $where = ['status' => 1, 'mark' => 1];
  277. $field = ['id','avatar', 'nickname', 'username', 'email', 'balance', 'parent_id','power_num','point_id','create_time', 'status'];
  278. $datas = $this->model->with(['level'])->where($where)
  279. ->where(function ($query) use ($userId) {
  280. $query->where('parent_id', $userId);
  281. })
  282. ->where(function($query) use($params){
  283. $kw = isset($params['kw'])? trim($params['kw']) : '';
  284. if($kw){
  285. $query->where('id','=', "%{$kw}%")->orWhere('email','like',"%{$kw}%")->orWhere('username','like',"%{$kw}%");
  286. }
  287. })
  288. ->select($field)
  289. ->orderBy('create_time', 'desc')
  290. ->orderBy('id', 'desc')
  291. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  292. $datas = $datas ? $datas->toArray() : [];
  293. if ($datas) {
  294. foreach ($datas['data'] as &$item) {
  295. $item['avatar'] = $item['avatar']? $item['avatar'] : '/images/member/logo.png';
  296. $item['avatar'] = get_image_url($item['avatar']);
  297. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'y-m-d H:i') : '';
  298. $item['is_online'] = RedisService::get("auths:info:".$item['id'])? 1: 0;
  299. }
  300. unset($item);
  301. RedisService::set($cacheKey, $datas, rand(5, 10));
  302. }
  303. return [
  304. 'pageSize' => $pageSize,
  305. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  306. 'list' => isset($datas['data']) ? $datas['data'] : []
  307. ];
  308. }
  309. /**
  310. * 手机号是否已注册
  311. * @param $mobile
  312. * @return mixed
  313. */
  314. public function checkPhoneExists($mobile)
  315. {
  316. return parent::checkExists('mobile', $mobile); // TODO: Change the autogenerated stub
  317. }
  318. /**
  319. * 账号注册
  320. * @param $params
  321. * @return array|false
  322. */
  323. public function register($params)
  324. {
  325. // 授权
  326. $email = isset($params['email']) ? trim($params['email']) : '';
  327. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  328. $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
  329. $code = isset($params['code']) ? trim($params['code']) : '';
  330. $scene = isset($params['scene']) ? $params['scene'] : '';
  331. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  332. $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : '';
  333. if (empty($params) || empty($email) || $code <= 0) {
  334. $this->error = 2014;
  335. return false;
  336. }
  337. // 验证码
  338. if (!EmailService::make()->check($email, $code, $scene)) {
  339. $this->error = EmailService::make()->getError();
  340. return false;
  341. }
  342. // 验证是否注册
  343. if($this->model->where(['email'=> $email,'mark'=>1])->value('id')){
  344. $this->error = 2009;
  345. return false;
  346. }
  347. // 推荐人
  348. $parentId = 0;
  349. $pointId = 0;
  350. $parents = '';
  351. $points = '';
  352. if ($inviteCode) {
  353. $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1])
  354. ->select(['id', 'parents', 'parent_id'])
  355. ->first();
  356. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  357. $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
  358. // 挂靠节点
  359. if($parentId>0){
  360. $pointId = $this->getPointParentId($parentId);
  361. if($pointId){
  362. $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
  363. $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
  364. }
  365. }
  366. }
  367. // 注册
  368. $id = $this->model->max('id') + 1;
  369. $system = isset($params['system'])? $params['system'] : [];
  370. $ip = get_client_ip();
  371. $ipData = ToolService::make()->getIpAddress($ip,'');
  372. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  373. $city = isset($ipData['city'])? $ipData['city'] : '';
  374. $emailName = explode('@', $email)[0];
  375. // 钱包
  376. $data = [
  377. 'parent_id' => $parentId,
  378. 'point_id' => $pointId,
  379. 'points' => $points,
  380. 'openid' => '',
  381. 'avatar' => '',
  382. 'nickname' => $nickname ? $nickname : '用户'.substr($emailName,-8,8),
  383. 'username' => $email,
  384. 'password' => get_password('xl123456'),
  385. 'code' => strtoupper(get_random_code(9, 'X', "{$id}")),
  386. 'email' => $email,
  387. 'mobile' => $mobile,
  388. 'recharge_trc_url' => UdunpayService::make()->createAddress(195),
  389. 'parents' => $parents,
  390. 'province_id' => CityService::make()->getFieldByName($province),
  391. 'city_id' => CityService::make()->getFieldByName($city),
  392. 'app_uuid' => isset($system['uuid']) ? $system['uuid'] : '',
  393. 'device' => $appSources == 'android' ? 2 : 1,
  394. 'status' => 1,
  395. 'balance' => 0,
  396. 'score' => 0,
  397. 'mark' => 1,
  398. 'login_ip' => $ip,
  399. 'create_time' => time(),
  400. ];
  401. $userId = $this->model->insertGetId($data);
  402. $this->error = 2008;
  403. return [
  404. 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"),
  405. 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'point_id'=> $pointId, 'username' => $data['username']],
  406. ];
  407. }
  408. /**
  409. * 邮箱登录
  410. * @param $params
  411. * @return array|false
  412. */
  413. public function loginByEmail($params)
  414. {
  415. // 授权
  416. $email = isset($params['email']) ? $params['email'] : '';
  417. $code = isset($params['code']) ? $params['code'] : '';
  418. $scene = isset($params['scene']) ? $params['scene'] : '';
  419. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  420. if (empty($params) || empty($email) || empty($scene) || $code <= 0) {
  421. $this->error = 2014;
  422. return false;
  423. }
  424. // 验证码
  425. if (!EmailService::make()->check($email, $code, $scene)) {
  426. $this->error = EmailService::make()->getError();
  427. return false;
  428. }
  429. // 验证是否注册,没有则注册
  430. $data = $this->model->where(['email' => $email, 'mark' => 1])->select(['id', 'username','point_id', 'parent_id', 'code', 'status'])->first();
  431. $data = $data ? $data->toArray() : [];
  432. $userId = isset($data['id']) ? $data['id'] : 0;
  433. $status = isset($data['status']) ? $data['status'] : 0;
  434. if(empty($data) || $userId<=0){
  435. $this->error = 2001;
  436. return false;
  437. }
  438. if ($status != 1) {
  439. $this->error = 2015;
  440. return false;
  441. }
  442. // 获取登录授权token
  443. $jwt = new Jwt('jwt_dys_app');
  444. $token = $jwt->getToken($userId);
  445. // 结果返回
  446. $result = [
  447. 'access_token' => $token,
  448. 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
  449. ];
  450. // 用户信息
  451. $ip = get_client_ip();
  452. $updateData = [
  453. 'login_time' => time(),
  454. 'login_ip' => $ip,
  455. ];
  456. if(!RedisService::get("caches:member:updateArea:{$userId}")){
  457. $ipData = ToolService::make()->getIpAddress($ip,'');
  458. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  459. $city = isset($ipData['city'])? $ipData['city'] : '';
  460. $updateData['province_id'] = CityService::make()->getFieldByName($province);
  461. $updateData['city_id'] = CityService::make()->getFieldByName($city);
  462. }
  463. $this->model->where(['id'=> $userId])->update($updateData);
  464. $this->error = 2004;
  465. $data['token'] = $token;
  466. RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
  467. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  468. return $result;
  469. }
  470. /**
  471. * 手机号登录
  472. * @param $params
  473. * @return array|false
  474. */
  475. public function loginByMobile($params)
  476. {
  477. // 授权
  478. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  479. $code = isset($params['sms_code']) ? $params['sms_code'] : '';
  480. $smsType = isset($params['sms_type']) ? $params['sms_type'] : '';
  481. $nickname = isset($params['nickname']) ? $params['nickname'] : '';
  482. $openid = isset($params['openid']) ? $params['openid'] : '';
  483. $avatar = isset($params['avatar']) ? $params['avatar'] : '';
  484. $regType = isset($params['type']) ? $params['type'] : 'app';
  485. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  486. $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : '';
  487. if (empty($params) || empty($mobile) || $code <= 0) {
  488. $this->error = 2014;
  489. return false;
  490. }
  491. // 验证码
  492. if (!SmsService::make()->check($mobile, $code, $smsType?$smsType:'login')) {
  493. $this->error = SmsService::make()->getError();
  494. return false;
  495. }
  496. // 推荐人
  497. $parentId = 0;
  498. $parents = '';
  499. if ($inviteCode) {
  500. $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1])
  501. ->select(['id', 'parents', 'parent_id'])
  502. ->first();
  503. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  504. $parents = isset($inviteInfo['parents']) ? $inviteInfo['parents'] . $parentId . ',' : ($parentId ? $parentId . ',' : '');
  505. }
  506. // 验证是否注册,没有则注册
  507. $data = $this->model->with(['merchant','mechanic'])->where(['mobile' => $mobile, 'mark' => 1])->select(['id', 'openid', 'username', 'parent_id', 'code', 'push_cid', 'status'])->first();
  508. $data = $data ? $data->toArray() : [];
  509. $userId = isset($data['id']) ? $data['id'] : 0;
  510. $status = isset($data['status']) ? $data['status'] : 0;
  511. if ($userId && $status != 1) {
  512. $this->error = 2015;
  513. return false;
  514. }
  515. // 是否是商家或技师,有订单提醒
  516. $noticeUser = ['id'=> 0,'uid'=>$userId,'type'=>1];
  517. $merchant = isset($data['merchant'])? $data['merchant'] : [];
  518. $merchantStatus = isset($merchant['status'])? $merchant['status'] : 0;
  519. $mechanic = isset($data['mechanic'])? $data['mechanic'] : [];
  520. $mechanicStatus = isset($mechanic['status'])? $mechanic['status'] : 0;
  521. if($merchantStatus==2){
  522. $uid = isset($merchant['id'])? $merchant['id'] : 0;
  523. if($uid>0){
  524. $noticeUser = ['id'=>$uid,'type'=>2,'uid'=> $userId];
  525. }
  526. }else if($mechanicStatus == 2){
  527. $uid = isset($mechanic['id'])? $mechanic['id'] : 0;
  528. if($uid>0){
  529. $noticeUser = ['id'=>$uid,'type'=>3,'uid'=>$userId];
  530. }
  531. }
  532. $pushCid = isset($params['push_cid']) ? $params['push_cid'] : '';
  533. if (!$userId) {
  534. $id = $this->model->max('id') + 1;
  535. $data = [
  536. 'parent_id' => $parentId,
  537. 'openid' => $openid,
  538. 'avatar' => $avatar,
  539. 'nickname' => $nickname ? $nickname : get_random_code(4, '用户u').substr($mobile,-4,4),
  540. 'username' => get_username($id),
  541. 'password' => get_password('123456'),
  542. 'code' => strtoupper(get_random_code(8, 'D', "{$id}")),
  543. 'mobile' => $mobile,
  544. 'parents' => $parents,
  545. 'push_cid' => isset($params['push_cid']) ? $params['push_cid'] : '',
  546. 'app_uuid' => isset($params['uuid']) ? $params['uuid'] : '',
  547. 'device' => $appSources == 'android' ? 2 : 1,
  548. 'status' => 1,
  549. 'balance' => 0,
  550. 'score' => 0,
  551. 'mark' => 1,
  552. 'login_time' => time(),
  553. 'login_ip' => get_client_ip(),
  554. 'create_time' => time(),
  555. ];
  556. $userId = $this->model->insertGetId($data);
  557. } elseif ($regType != 'h5') {
  558. // 登录更新
  559. $updateData = [
  560. 'app_uuid' => isset($params['uuid']) ? $params['uuid'] : '',
  561. 'login_count' => DB::raw("login_count+1"),
  562. 'login_time' => time(),
  563. 'login_ip' => get_client_ip(),
  564. 'update_time' => time(),
  565. ];
  566. if ($pushCid) {
  567. $updateData['push_cid'] = $pushCid;
  568. }
  569. $this->model->where(['id' => $userId])->update($updateData);
  570. }
  571. // H5 邀请注册,无需登录
  572. if ($regType == 'h5') {
  573. $this->error = $status ? 2023 : 2022;
  574. return [
  575. 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"),
  576. 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'username' => $data['username']],
  577. ];
  578. }
  579. // 获取登录授权token
  580. $jwt = new Jwt('jwt_dys_app');
  581. $token = $jwt->getToken($userId);
  582. // 结果返回
  583. $result = [
  584. 'access_token' => $token,
  585. 'info' => ['uid' => $userId,'notice_user'=>$noticeUser, 'openid' => $data['openid'], 'username' => $data['username']],
  586. ];
  587. // 用户信息
  588. $this->error = 2004;
  589. $data['token'] = $token;
  590. unset($data['password']);
  591. // 实现初始化账单明细表
  592. AccountLogModel::where('id','<=',1)->value('id');
  593. RedisService::clear( "caches:map:{$userId}");
  594. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  595. return $result;
  596. }
  597. /**
  598. * 修改头像/商家logo/技师头像
  599. * @param $userId
  600. * @param $avatar
  601. * @return mixed
  602. */
  603. public function saveAvatar($userId, $avatar)
  604. {
  605. $type = request()->post('type', 1);
  606. if($type == 1){
  607. $oldAvatar = $this->model->where(['id' => $userId])->value('avatar');
  608. if ($this->model->where(['id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) {
  609. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  610. @unlink(ATTACHMENT_PATH . $oldAvatar);
  611. }
  612. return true;
  613. }
  614. }else if($type == 2){
  615. $oldAvatar = MerchantModel::where(['user_id' => $userId])->value('logo');
  616. if (MerchantModel::where(['user_id' => $userId])->update(['logo' => $avatar, 'update_time' => time()])) {
  617. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  618. @unlink(ATTACHMENT_PATH . $oldAvatar);
  619. }
  620. return true;
  621. }
  622. }else if($type == 3){
  623. $oldAvatar = MechanicModel::where(['user_id' => $userId])->value('avatar');
  624. if (MechanicModel::where(['user_id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) {
  625. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  626. @unlink(ATTACHMENT_PATH . $oldAvatar);
  627. }
  628. return true;
  629. }
  630. }
  631. return false;
  632. }
  633. /**
  634. * 修改账号
  635. * @param $userId
  636. * @param $params
  637. * @return bool
  638. */
  639. public function modify($userId, $params)
  640. {
  641. $email = isset($params['email']) ? $params['email'] : '';
  642. $password = isset($params['password']) ? $params['password'] : '';
  643. $payPassword = isset($params['pay_password']) ? $params['pay_password'] : '';
  644. // 用户验证
  645. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id', 'status'])->first();
  646. if (!$info) {
  647. $this->error = 2001;
  648. return false;
  649. }
  650. // 使用状态校验
  651. if ($info['status'] != 1) {
  652. $this->error = 2009;
  653. return false;
  654. }
  655. // 密码校验
  656. $data = ['update_time' => time()];
  657. if (isset($params['password']) && $password) {
  658. $password = get_password($password);
  659. $data['password'] = $password;
  660. if ($password != $info['password']) {
  661. $this->error = 2002;
  662. return false;
  663. }
  664. }
  665. // 邮箱验证
  666. if (isset($params['email']) && $email) {
  667. // 修改邮箱
  668. $newEmail = isset($params['new_email'])? trim($params['new_email']) : '';
  669. if(isset($params['new_email']) && $newEmail){
  670. $data['email'] = $email;
  671. $data['username'] = $email;
  672. $checkInfo = $this->model->where(['username' => $newEmail, 'mark' => 1])->select(['id', 'status'])->first();
  673. if ($checkInfo && $checkInfo['id'] != $userId) {
  674. $this->error = 2005;
  675. return false;
  676. }
  677. }
  678. // 邮箱验证码
  679. $code = isset($params['code'])? trim($params['code']) : '';
  680. $scene = isset($params['scene'])? trim($params['scene']) : '';
  681. if (!EmailService::make()->check($email, $code, $scene)) {
  682. $this->error = EmailService::make()->getError();
  683. return false;
  684. }
  685. }
  686. // 修改数据
  687. $nickname = isset($params['nickname']) ? $params['nickname'] : '';
  688. if (isset($params['nickname']) && $nickname) {
  689. $data['nickname'] = $nickname;
  690. }
  691. $gender = isset($params['gender']) ? intval($params['gender']) : 3;
  692. if (isset($params['gender']) && $gender) {
  693. $data['gender'] = $gender;
  694. }
  695. $intro = isset($params['intro']) ? $params['intro'] : '';
  696. if (isset($params['intro']) && $intro) {
  697. $data['intro'] = $intro;
  698. }
  699. if (isset($params['pay_password']) && $payPassword) {
  700. $payPassword = get_password($payPassword);
  701. $data['pay_password'] = $payPassword;
  702. }
  703. $this->model->where(['id' => $userId])->update($data);
  704. $this->error = 1008;
  705. return true;
  706. }
  707. /**
  708. * 身份认证
  709. * @param $userId
  710. * @param $params
  711. * @return bool
  712. */
  713. public function auth($userId, $params)
  714. {
  715. // 用户验证
  716. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','username', 'status'])->first();
  717. if (!$info) {
  718. $this->error = 2001;
  719. return false;
  720. }
  721. // 使用状态校验
  722. if ($info['status'] != 1) {
  723. $this->error = 2009;
  724. return false;
  725. }
  726. // 密码校验
  727. $data = ['update_time' => time(),'idcard_check'=>1];
  728. if (isset($params['realname']) && $params['realname']) {
  729. $data['realname'] = trim($params['realname']);
  730. }
  731. $idcard = isset($params['idcard']) && $params['idcard'];
  732. if ($idcard) {
  733. $data['idcard'] = trim($params['idcard']);
  734. }
  735. if (isset($params['idcard_front_img'][0]) && $params['idcard_front_img'][0]) {
  736. $data['idcard_front_img'] = get_image_path($params['idcard_front_img'][0]['url']);
  737. }
  738. if (isset($params['idcard_back_img'][0]) && $params['idcard_back_img'][0]) {
  739. $data['idcard_back_img'] = get_image_path($params['idcard_back_img'][0]['url']);
  740. }
  741. $this->model->where(['id' => $userId])->update($data);
  742. // 发送消息
  743. $params = [
  744. 'title'=> "身份认证提交成功",
  745. 'body' => "您的身份认证信息已提交成功,请耐心等候审核",
  746. 'type' => 1, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  747. 'content' => [
  748. 'account' => ['name' => '账号', 'text' => $info['username']],
  749. 'pay_time' => ['name' => '申请时间', 'text' => date('Y-m-d H:i:s')],
  750. 'status' => ['name' => '状态', 'text' => '待审核'],
  751. ],
  752. 'click_type' => 'payload',
  753. 'url' => '/pages/my/profile/auth',
  754. ];
  755. PushService::make()->pushMessageByUser($userId, $params, 0);
  756. $this->error = 2036;
  757. return true;
  758. }
  759. /**
  760. * 转账
  761. * @param $userId
  762. * @param $params
  763. * @return bool
  764. */
  765. public function transfer($userId, $params)
  766. {
  767. $toUserId = isset($params['to_user_id'])? intval($params['to_user_id']) : 0;
  768. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  769. $money = isset($params['money'])? floatval($params['money']) : 0;
  770. if(empty($toUserId) || $money<=0){
  771. $this->error = 2420;
  772. return false;
  773. }
  774. $cacheKey = "caches:members:transfer:{$userId}";
  775. if(RedisService::get($cacheKey)){
  776. $this->error = 1034;
  777. return false;
  778. }
  779. // 验证账户
  780. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  781. ->select(['id','nickname','username','usdt','pay_password','balance','status'])
  782. ->first();
  783. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  784. $usdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  785. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  786. $nickname = isset($userInfo['nickname'])? $userInfo['nickname'] : '';
  787. if(empty($userInfo) || $status != 1){
  788. $this->error = 2024;
  789. return false;
  790. }
  791. // 余额支付支付密码验证
  792. if(empty($userPayPassword)){
  793. $this->error = 1040;
  794. return false;
  795. }
  796. $payPassword = get_password($payPassword);
  797. if($payPassword != $userPayPassword){
  798. $this->error = 2038;
  799. return false;
  800. }
  801. // 验证账户
  802. $accountInfo = $this->model->where(['id'=> $toUserId,'mark'=>1])
  803. ->select(['id','nickname','usdt','username','balance','status'])
  804. ->first();
  805. $status = isset($accountInfo['status'])? $accountInfo['status'] : 0;
  806. $accountUsdt = isset($accountInfo['usdt'])? $accountInfo['usdt'] : 0;
  807. $toNickname = isset($accountInfo['nickname'])? $accountInfo['nickname'] : '';
  808. if(empty($accountInfo) || $status != 1){
  809. $this->error = 2421;
  810. return false;
  811. }
  812. if($money > $usdt){
  813. $this->error = 2422;
  814. return false;
  815. }
  816. // 用户余额转账到用户
  817. DB::beginTransaction();
  818. RedisService::set($cacheKey, $params, rand(2,5));
  819. $updateData = ['usdt'=> DB::raw("usdt - {$money}"),'update_time'=> time()];
  820. if(!$this->model->where(['id'=> $userId,'mark'=>1])->update($updateData)){
  821. DB::rollBack();
  822. $this->error = 2028;
  823. RedisService::clear($cacheKey);
  824. return false;
  825. }
  826. // 明细
  827. $orderNo = get_order_num('TR');
  828. $log = [
  829. 'user_id' => $userId,
  830. 'source_id' => $toUserId,
  831. 'source_order_no' => $orderNo,
  832. 'type' => 6,
  833. 'coin_type' => 1,
  834. 'user_type'=> 1,
  835. 'money' => -$money,
  836. 'actual_money' => -$money,
  837. 'balance' => $usdt,
  838. 'create_time' => time(),
  839. 'update_time' => time(),
  840. 'remark' => "USDT转账",
  841. 'status' => 1,
  842. 'mark' => 1,
  843. ];
  844. if(!AccountLogModel::insertGetId($log)){
  845. DB::rollBack();
  846. $this->error = 2423;
  847. RedisService::clear($cacheKey);
  848. return false;
  849. }
  850. // 到账
  851. $fee = ConfigService::make()->getConfigByCode('transfer_fee_rate',5);
  852. $fee = $fee>0 && $fee<100? moneyFormat($fee/100, 2) : 0;
  853. $feeUsdt = round($money * $fee,2);
  854. $realUsdt = moneyFormat($money - $feeUsdt,2);
  855. $updateData = ['usdt'=> DB::raw("usdt + {$realUsdt}"),'update_time'=> time()];
  856. if(!$this->model->where(['id'=> $toUserId,'mark'=>1])->update($updateData)){
  857. DB::rollBack();
  858. $this->error = 2424;
  859. RedisService::clear($cacheKey);
  860. return false;
  861. }
  862. // 明细
  863. $log = [
  864. 'user_id' => $toUserId,
  865. 'source_id' => $userId,
  866. 'source_order_no' => $orderNo,
  867. 'type' => 6,
  868. 'coin_type' => 1,
  869. 'user_type'=> 1,
  870. 'money' => $realUsdt,
  871. 'actual_money' => $realUsdt,
  872. 'balance' => $accountUsdt,
  873. 'create_time' => time(),
  874. 'update_time' => time(),
  875. 'remark' => "USDT转账",
  876. 'status' => 1,
  877. 'mark' => 1,
  878. ];
  879. if(!AccountLogModel::insertGetId($log)){
  880. DB::rollBack();
  881. $this->error = 2029;
  882. RedisService::clear($cacheKey);
  883. return false;
  884. }
  885. // 平台明细
  886. $log = [
  887. 'user_id' => 0,
  888. 'source_id' => $userId,
  889. 'source_order_no' => $orderNo,
  890. 'type' => 6,
  891. 'coin_type' => 1,
  892. 'user_type'=> 4,
  893. 'money' => $feeUsdt,
  894. 'actual_money' => $feeUsdt,
  895. 'balance' => 0,
  896. 'create_time' => time(),
  897. 'update_time' => time(),
  898. 'remark' => "USDT转账",
  899. 'status' => 1,
  900. 'mark' => 1,
  901. ];
  902. if(!AccountLogModel::insertGetId($log)){
  903. DB::rollBack();
  904. $this->error = 2029;
  905. RedisService::clear($cacheKey);
  906. return false;
  907. }
  908. // 平台
  909. FinanceService::make()->saveLog(0, $feeUsdt,1);
  910. // 消息
  911. $dateTime = date('Y-m-d H:i:s');
  912. MessageService::make()->pushMessage($userId,'USDT转账成功',"您在{$dateTime}(UTC+8)成功支付{$money}USDT转账给用户【{$toUserId}】{$toNickname}",3);
  913. $dateTime = date('Y-m-d H:i:s');
  914. MessageService::make()->pushMessage($toUserId,'USDT转账成功',"您在{$dateTime}(UTC+8)收到用户【{$userId}】{$nickname}的{$realUsdt}USDT转账",3);
  915. DB::commit();
  916. RedisService::clear($cacheKey);
  917. $this->error = 2425;
  918. return true;
  919. }
  920. /**
  921. * 余额充值
  922. * @param $userId
  923. * @param $params
  924. * @return array|false
  925. */
  926. public function recharge($userId, $params)
  927. {
  928. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  929. $usdt = isset($params['usdt'])? moneyFormat($params['usdt'], 2) : 0;
  930. $coinType = isset($params['coin_type']) && $params['coin_type']? intval($params['coin_type']) : 2;
  931. $payType = 10;
  932. if($usdt<=0){
  933. $this->error = 2031;
  934. return false;
  935. }
  936. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  937. ->select(['id','nickname','usdt','pay_password','balance','status'])
  938. ->first();
  939. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  940. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  941. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  942. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  943. if(empty($userInfo) || $status != 1){
  944. $this->error = 2024;
  945. return false;
  946. }
  947. if($userPayPassword != get_password($payPassword)){
  948. $this->error = 2038;
  949. return false;
  950. }
  951. // 充值订单
  952. $orderNo = get_order_num('DR');
  953. $money = $usdt;
  954. // 星豆
  955. DB::beginTransaction();
  956. if($coinType == 2){
  957. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  958. $xdPrice = $xdPrice>0 && $xdPrice <=10000? $xdPrice : 100;
  959. $money = round($xdPrice * $usdt,2);
  960. if($usdt > $userUsdt){
  961. $this->error = 2035;
  962. return false;
  963. }
  964. // 扣除usdt余额
  965. $updateData = ['usdt'=>DB::raw("usdt - {$usdt}"),'balance'=>DB::raw("balance + {$money}"),'update_time'=>time()];
  966. if(!$this->model->where(['id'=> $userId])->update($updateData)){
  967. $this->error = 2036;
  968. DB::rollBack();
  969. return false;
  970. }
  971. }
  972. $data = [
  973. 'order_no'=> $orderNo,
  974. 'user_id'=> $userId,
  975. 'type'=> 1,
  976. 'user_type'=> 1,
  977. 'coin_type'=> 2,
  978. 'money'=> $usdt,
  979. 'actual_money'=> $money,
  980. 'pay_type'=> $payType,
  981. 'pay_status'=> 20,
  982. 'pay_at'=> date('Y-m-d H:i:s'),
  983. 'create_time'=> time(),
  984. 'update_time'=> time(),
  985. 'status'=> 2,
  986. 'mark'=> 1,
  987. ];
  988. if(!$orderId = BalanceLogModel::insertGetId($data)){
  989. $this->error = 2033;
  990. DB::rollBack();
  991. return false;
  992. }
  993. // 扣除USDT
  994. $log = [
  995. 'user_id'=> $userId,
  996. 'source_order_no'=> $data['order_no'],
  997. 'user_type'=> 1,
  998. 'type'=> 5,
  999. 'coin_type'=> 1,
  1000. 'money'=> -$usdt,
  1001. 'actual_money'=> -$usdt,
  1002. 'balance'=> $userUsdt,
  1003. 'date'=> date('Y-m-d'),
  1004. 'create_time'=> time(),
  1005. 'remark'=> '星豆余额充值扣除',
  1006. 'status'=>1,
  1007. 'mark'=>1
  1008. ];
  1009. if(!AccountLogModel::insertGetId($log)){
  1010. $this->error = 2029;
  1011. DB::rollBack();
  1012. return false;
  1013. }
  1014. // 增加星豆余额
  1015. $log = [
  1016. 'user_id'=> $userId,
  1017. 'source_order_no'=> $data['order_no'],
  1018. 'user_type'=> 1,
  1019. 'type'=> 5,
  1020. 'coin_type'=> 2,
  1021. 'money'=> $usdt,
  1022. 'actual_money'=> $money,
  1023. 'balance'=> $balance,
  1024. 'date'=> date('Y-m-d'),
  1025. 'create_time'=> time(),
  1026. 'remark'=> '星豆余额充值',
  1027. 'status'=>1,
  1028. 'mark'=>1
  1029. ];
  1030. if(!AccountLogModel::insertGetId($log)){
  1031. $this->error = 2029;
  1032. DB::rollBack();
  1033. return false;
  1034. }
  1035. // 消息
  1036. $dateTime = date('Y-m-d H:i:s');
  1037. MessageService::make()->pushMessage($userId,'星豆余额充值成功',"您在{$dateTime}(UTC+8)成功支付{$usdt}USDT充值{$money}星豆",3);
  1038. DB::commit();
  1039. // 充值星豆任务
  1040. TaskService::make()->updateTask($userId,9, 0);
  1041. $this->error = 2037;
  1042. return ['order_id'=> $orderId,'balance'=> moneyFormat($balance + $money,2),'usdt'=> moneyFormat($userUsdt-$usdt, 2)];
  1043. }
  1044. /**
  1045. * 余额提现
  1046. * @param $userId
  1047. * @param $params
  1048. * @return array|false
  1049. */
  1050. public function withdraw($userId, $params)
  1051. {
  1052. $money = isset($params['money'])? floatval($params['money']) : 0;
  1053. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1054. $userType = isset($params['user_type']) && $params['user_type']? intval($params['user_type']) : 1;
  1055. if($money<=0){
  1056. $this->error = 2401;
  1057. return false;
  1058. }
  1059. if(!in_array($userType,[1,2])){
  1060. $this->error = 2404;
  1061. return false;
  1062. }
  1063. $userInfo = $this->model->with(['merchant'])
  1064. ->where(['id'=> $userId,'mark'=>1])
  1065. ->select(['id','nickname','usdt','trc_url','pay_password','status'])
  1066. ->first();
  1067. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1068. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1069. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1070. $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : [];
  1071. $merchantUsdt = isset($merchant['usdt'])? $merchant['usdt'] : 0;
  1072. $merchantId = isset($merchant['id'])? $merchant['id'] : 0;
  1073. $merchantTradeStatus = isset($merchant['trade_status'])? $merchant['trade_status'] : 0;
  1074. if(empty($userInfo) || $status != 1){
  1075. $this->error = 2024;
  1076. return false;
  1077. }
  1078. if($userType == 2 && (empty($merchant) || !in_array($merchantTradeStatus,[1,2]))){
  1079. $this->error = 2024;
  1080. return false;
  1081. }
  1082. // 提现金额验证
  1083. $accountUsdt = $userType==1? $userUsdt : $merchantUsdt;
  1084. if ($money > $accountUsdt) {
  1085. $this->error = web_lang(2402, ['money' => $accountUsdt]);
  1086. return false;
  1087. }
  1088. // 提现账户
  1089. $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : '';
  1090. if (empty($trcUrl)) {
  1091. $this->error = 2403;
  1092. return false;
  1093. }
  1094. if($userPayPassword != get_password($payPassword)){
  1095. $this->error = 2038;
  1096. return false;
  1097. }
  1098. $cacheKey = "caches:member:withdraw:lock_{$userId}";
  1099. if(RedisService::get($cacheKey)){
  1100. $this->error = 1034;
  1101. return false;
  1102. }
  1103. DB::beginTransaction();
  1104. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1105. // 提现记录
  1106. $orderNo = get_order_num('DW');
  1107. $feeRate = ConfigService::make()->getConfigByCode('withdraw_fee_rate',5);
  1108. $feeRate = $feeRate>0 && $feeRate<100? moneyFormat($feeRate/100,2) : 0;
  1109. $fee = round($money*$feeRate, 2);
  1110. $realUsdt = moneyFormat($money - $fee, 2);
  1111. $data = [
  1112. 'order_no'=> $orderNo,
  1113. 'user_id'=> $userType==1? $userId : $merchantId,
  1114. 'type'=> 2,
  1115. 'user_type'=> $userType,
  1116. 'coin_type'=> 1,
  1117. 'money'=> $money,
  1118. 'actual_money'=> $realUsdt,
  1119. 'fee'=> $fee,
  1120. 'trc_url'=> $trcUrl,
  1121. 'pay_type'=> 20,
  1122. 'date'=> date('Y-m-d'),
  1123. 'create_time'=> time(),
  1124. 'update_time'=> time(),
  1125. 'status'=> 1,
  1126. 'mark'=> 1,
  1127. ];
  1128. if(!$id = BalanceLogModel::insertGetId($data)){
  1129. DB::rollBack();
  1130. $this->error = 2405;
  1131. RedisService::clear($cacheKey);
  1132. return false;
  1133. }
  1134. // 商户扣款
  1135. if($userType == 2){
  1136. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1137. if(!MerchantModel::where(['user_id'=> $userId,'mark'=>1])->update($updateData)){
  1138. DB::rollBack();
  1139. $this->error = 2406;
  1140. RedisService::clear($cacheKey);
  1141. return false;
  1142. }
  1143. // 明细
  1144. $log = [
  1145. 'user_id' => $merchantId,
  1146. 'source_id' => $userId,
  1147. 'source_order_no' => $orderNo,
  1148. 'type' => 5,
  1149. 'coin_type' => 1,
  1150. 'user_type'=> 2,
  1151. 'money' => -$money,
  1152. 'actual_money' => -$money,
  1153. 'balance' => $merchantUsdt,
  1154. 'create_time' => time(),
  1155. 'update_time' => time(),
  1156. 'remark' => "商户账户余额提现",
  1157. 'status' => 1,
  1158. 'mark' => 1,
  1159. ];
  1160. if (!AccountLogModel::insertGetId($log)) {
  1161. $this->error = 2407;
  1162. DB::rollBack();
  1163. RedisService::clear($cacheKey);
  1164. return false;
  1165. }
  1166. }
  1167. // 用户扣款
  1168. else{
  1169. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1170. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  1171. DB::rollBack();
  1172. $this->error = 2406;
  1173. RedisService::clear($cacheKey);
  1174. return false;
  1175. }
  1176. // 明细
  1177. $log = [
  1178. 'user_id' => $userId,
  1179. 'source_id' => 0,
  1180. 'source_order_no' => $orderNo,
  1181. 'type' => 5,
  1182. 'coin_type' => 1,
  1183. 'user_type'=> 1,
  1184. 'money' => -$money,
  1185. 'actual_money' => -$money,
  1186. 'balance' => $userUsdt,
  1187. 'create_time' => time(),
  1188. 'update_time' => time(),
  1189. 'remark' => "USDT余额提现",
  1190. 'status' => 1,
  1191. 'mark' => 1,
  1192. ];
  1193. if (!AccountLogModel::insertGetId($log)) {
  1194. $this->error = 2407;
  1195. DB::rollBack();
  1196. RedisService::clear($cacheKey);
  1197. return false;
  1198. }
  1199. }
  1200. DB::commit();
  1201. // 站内消息
  1202. $dateTime = date('Y-m-d H:i:s');
  1203. $title = $userType == 1 ? 'USDT余额提现申请成功' : '商户余额提现申请成功';
  1204. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额成功,请耐心等候审核!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额成功,请耐心等候审核!!!";
  1205. MessageService::make()->pushMessage($userId, $title, $message);
  1206. // 提现自动审核,低于该金额自动审核
  1207. $autoCheckUsdt = ConfigService::make()->getConfigByCode('withdraw_auto_money', 300);
  1208. $autoCheckUsdt = $autoCheckUsdt > 0 ? $autoCheckUsdt : 0;
  1209. if ($money <= $autoCheckUsdt) {
  1210. // 打款处理
  1211. $result = WalletService::make()->usdtTrcTransfer($trcUrl, $realUsdt);
  1212. $txID = isset($result['txId']) ? $result['txId'] : '';
  1213. $payAddress = isset($result['address']) ? $result['address'] : '';
  1214. if ($txID && $payAddress) {
  1215. $updateData = ['hash'=> $txID,'wallet_url'=> $payAddress,'audit_remark'=>'自动审核打款','status'=>2,'update_time'=>time()];
  1216. if(BalanceLogModel::where(['order_no'=> $orderNo,'user_type'=> $userType])->update($updateData)){
  1217. $title = $userType == 1 ? 'USDT余额提现审核成功' : '商户余额提现审核成功';
  1218. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额审核成功,请耐心等候打款到账!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额审核成功,请耐心等候打款到账!!!";
  1219. MessageService::make()->pushMessage($userId, $title, $message);
  1220. AccountLogModel::where(['source_order_no'=> $orderNo])->update(['hash'=> $txID,'update_time'=>time()]);
  1221. // 平台明细
  1222. $log = [
  1223. 'user_id' => 0,
  1224. 'source_id' => $userId,
  1225. 'source_order_no' => $orderNo,
  1226. 'type' => 5,
  1227. 'coin_type' => 1,
  1228. 'user_type'=> 4,
  1229. 'money' => $fee,
  1230. 'actual_money' => $fee,
  1231. 'balance' => 0,
  1232. 'create_time' => time(),
  1233. 'update_time' => time(),
  1234. 'hash' => $txID,
  1235. 'remark' => "USDT余额提现",
  1236. 'status' => 1,
  1237. 'mark' => 1,
  1238. ];
  1239. AccountLogModel::insertGetId($log);
  1240. // 平台流水
  1241. FinanceService::make()->saveLog(0, $fee, 1);
  1242. }
  1243. }
  1244. }
  1245. $this->error = $title;
  1246. RedisService::clear($cacheKey);
  1247. return [
  1248. 'id'=> $id,
  1249. 'money'=> $money,
  1250. 'user_type'=> $userType,
  1251. ];
  1252. }
  1253. /**
  1254. * 获取点对点上级节点
  1255. * @param $userId 推荐人ID
  1256. * @return int|mixed
  1257. */
  1258. public function getPointParentId($userId)
  1259. {
  1260. if($userId<=0){
  1261. return 0;
  1262. }
  1263. $userList = $this->model->where(['mark'=> 1])->whereRaw('FIND_IN_SET(?,points)', $userId)->select(['id','point_id','points'])->orderBy('create_time','asc')->get();
  1264. $userList = $userList? $userList->toArray() : [];
  1265. if(count($userList) < 3){
  1266. return $userId;
  1267. }
  1268. $users = [];
  1269. foreach($userList as $item){
  1270. $points = isset($item['points']) && $item['points']? explode(',', $item['points']) : [];
  1271. $points = array_filter($points);
  1272. $users[$item['id']]['pointLen'] = count($points);
  1273. $users[$item['id']]['children'] = isset($users[$item['id']]['children'])? $users[$item['id']]['children'] : 0;
  1274. $users[$item['point_id']]['children'] = isset($users[$item['point_id']]['children'])? $users[$item['point_id']]['children'] + 1 : 1;
  1275. }
  1276. //var_dump($users);
  1277. $pointId = 0;
  1278. $tempPointLen = 0;
  1279. $tempChildren = 0;
  1280. foreach ($userList as $item) {
  1281. $id = isset($item['id'])? $item['id'] : 0;
  1282. $children = isset($users[$id]['children'])? $users[$id]['children'] : 0;
  1283. $pointLen = isset($users[$id]['pointLen'])? $users[$id]['pointLen'] : 0;
  1284. //var_dump($id.'++'.$pointLen.'--'.$children.'=='.$pointId.'++'.$tempPointLen.'++'.$tempChildren);
  1285. if($pointLen<=$tempPointLen || $pointId == 0){
  1286. //var_dump($id.'++'.$pointLen.'--'.$children."\n\n");
  1287. if($children <$tempChildren || $pointId == 0){
  1288. $pointId = $id;
  1289. $tempPointLen = $pointLen;
  1290. $tempChildren = $children;
  1291. }
  1292. }
  1293. }
  1294. return $pointId;
  1295. }
  1296. }