MemberService.php 56 KB

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