MemberService.php 55 KB

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