MemberService.php 55 KB

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