MemberService.php 54 KB

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