MemberService.php 58 KB

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