diff --git a/app/Console/Commands/AutoAiOrder.php b/app/Console/Commands/AutoAiOrder.php new file mode 100644 index 0000000..6039e80 --- /dev/null +++ b/app/Console/Commands/AutoAiOrder.php @@ -0,0 +1,132 @@ +where('startdate','<=',date('Y-m-d',time())) + // where('expire','>=',date('Y-m-d',time())) + $Ai_orderend = AiOrder::where('expire','<=',date('Y-m-d H:i:s',time()))->where('status',0)->where('today','<>',$nowday)->get(); + foreach ($Ai_orderend as $Ai_order){ + $AiCurrency = AiCurrency::where('id',$Ai_order->ai_id)->first(); + $currency_id = $AiCurrency->currency_id; + $exercise_price = $AiCurrency->exercise_price; + $type = $AiCurrency->type; + $now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价 + + $amount = $Ai_order->amount; + $totalincome = $Ai_order->totalincome; + $rates = explode('-',$Ai_order->rate); + + $rate = AiOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数 + + + + + $Ai_order->todayincome = bcdiv($rate*$amount,100,2); + + $Ai_order->totalincome = $totalincome+$Ai_order->todayincome; + + + + // $money = $amount + $totalincome+$Ai_order->todayincome; + + $money = $amount + $Ai_order->todayincome; + $user_walllet=UsersWallet::where("user_id",$Ai_order->user_id)->where("currency",3)->first(); + change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_AI_ORDER_RETURN,'AI量化结算');// . $user_walllet->name + + $data['user_id'] = $Ai_order->user_id; + $data['order_id'] = $Ai_order->id; + $data['day'] = $Ai_order->day; + $data['rate'] = $Ai_order->order_rate; + $data['amount'] = $Ai_order->todayincome; + $data['addtime'] = time(); + DB::table('ai_list')->insert($data); + + $Ai_order->status = 1; //修改状态为已结算 + $Ai_order->today = $nowday; + $Ai_order->save(); + + + + } + + + + + $Ai_orders = AiOrder::where('startdate','<=',date('Y-m-d H:i:s',time()))->where('expire','>',date('Y-m-d H:i:s',time()))->where('today','<>',$nowday)->where('status',0)->get(); + + + foreach ($Ai_orders as $Ai_order){ + $AiCurrency = AiCurrency::where('id',$Ai_order->ai_id)->first(); + $currency_id = $AiCurrency->currency_id; + $exercise_price = $AiCurrency->exercise_price; + $type = $AiCurrency->type; + $now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价 + + $amount = $Ai_order->amount; + $Ai_order->startdate = date('Y-m-d H:i:s',strtotime($Ai_order->startdate)+86400); + // $id = $Ai_order->id; + $today = $Ai_order->today; + $totalincome = $Ai_order->totalincome; + // $rate = $Ai_order->order_rate; + + $rates = explode('-',$Ai_order->rate); + + $rate = AiOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数 + + + $Ai_order->todayincome = bcdiv($rate*$amount,100,2); + + $Ai_order->totalincome = $totalincome+$Ai_order->todayincome; + + + $money = $Ai_order->todayincome; + $user_walllet=UsersWallet::where("user_id",$Ai_order->user_id)->where("currency",3)->first(); + change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_AI_ORDER_RETURN,'AI量化结算');// . $user_walllet->name + $data['user_id'] = $Ai_order->user_id; + $data['order_id'] = $Ai_order->id; + $data['day'] = $Ai_order->day; + $data['rate'] = $Ai_order->order_rate; + $data['amount'] = $money; + $data['addtime'] = time(); + DB::table('ai_list')->insert($data); + + $Ai_order->today = $nowday; + $Ai_order->save(); + + + } + + echo '已结算 '.PHP_EOL; + } +} \ No newline at end of file diff --git a/app/Console/Commands/AutoBalance.php b/app/Console/Commands/AutoBalance.php new file mode 100644 index 0000000..5aa1575 --- /dev/null +++ b/app/Console/Commands/AutoBalance.php @@ -0,0 +1,129 @@ +',1)->get(); + foreach ($list as $u){ + $currency_name=''; + $user_id = $data['user_id']=$u->id; + $change_wallet['usdt_totle'] =0; + $change_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('change_balance', '>=', 0) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + })->get(['id', 'currency', 'change_balance', 'lock_change_balance']) + ->toArray(); + + foreach ($change_wallet['balance'] as $k => $v) { + + $num = $v['change_balance'] + $v['lock_change_balance']; + + $change_wallet['usdt_totle'] += $num * $v['usdt_price']; + } + + $lever_wallet['usdt_totle'] =0; + $lever_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('lever_balance', '>=', 0) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + $query->where("is_lever", 1); + })->get(['id', 'currency', 'lever_balance', 'lock_lever_balance'])->toArray(); + + + foreach ($lever_wallet['balance'] as $k => $v) { + + $num = $v['lever_balance'] + $v['lock_lever_balance']; + $lever_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + $micro_wallet['usdt_totle'] =0; + $micro_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('micro_balance', '>=', 0) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + // $query->where("is_micro", 1); + })->get(['id', 'currency', 'micro_balance', 'lock_micro_balance']) + ->toArray(); + foreach ($micro_wallet['balance'] as $k => $v) { + + $num = $v['micro_balance'] + $v['lock_micro_balance']; + + $micro_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + + $legal_wallet['usdt_totle'] =0; + $legal_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('legal_balance', '>=', 0) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + + //$query->where("is_legal", 1)->where('show_legal', 1); + $query->where("is_legal", 1); + }) + ->get(['id', 'currency', 'legal_balance', 'lock_legal_balance']) + ->toArray(); + + + foreach ($legal_wallet['balance'] as $k => $v) { + + $num = $v['legal_balance'] + $v['lock_legal_balance']; + + $legal_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + $data['user_id'] =$user_id; + $data['amount'] = $micro_wallet['usdt_totle'] + $lever_wallet['usdt_totle'] + $change_wallet['usdt_totle'] +$legal_wallet['usdt_totle']; + + $data['addtime'] = $nowday; + + + // $bl = BalanceList::where('user_id',$user_id)->where('addtime',$nowday)->first(); + + //if(empty($bl)){ + // print_r( $data); + BalanceList::insert($data); + + // } //else{ + + + // BalanceList::where('user_id',$user_id)->where('addtime',$nowday)->update($data); + // } + + } + + + echo '已汇总 '.PHP_EOL; + } +} \ No newline at end of file diff --git a/app/Console/Commands/AutoCancelC2C.php b/app/Console/Commands/AutoCancelC2C.php new file mode 100644 index 0000000..93c1a5a --- /dev/null +++ b/app/Console/Commands/AutoCancelC2C.php @@ -0,0 +1,57 @@ +info('开始执行自动取消C2C发布脚本-' . $now->toDateTimeString()); + $twenty_four = $now->subHours(24)->timestamp; + $results = C2cDealSend::where('create_time', '<=', $twenty_four)->where('is_done', 0)->get(); + $count = count($results); + $this->info('共有 ' . $count . ' 条可取消C2C发布'); + try { + DB::beginTransaction(); + if (!empty($results)) { + $i = 1; + foreach ($results as $result) { + $this->info('执行第 ' . $i . ' 条记录'); + $legal_deal_send = C2cDealSend::lockForUpdate()->find($result->id); + $wallet = UsersWallet::where('user_id', $legal_deal_send->seller_id)->where('currency', $legal_deal_send->currency_id)->lockForUpdate()->first(); + if ($legal_deal_send->type == 'sell') { + $data_wallet1 = ['balance_type' => 2, 'wallet_id' => $wallet->id, 'lock_type' => 0, 'create_time' => time(), 'before' => $wallet->change_balance, 'change' => $legal_deal_send->total_number, 'after' => bc_add($wallet->change_balance, $legal_deal_send->total_number, 5)]; + $data_wallet2 = ['balance_type' => 2, 'wallet_id' => $wallet->id, 'lock_type' => 1, 'create_time' => time(), 'before' => $wallet->lock_change_balance, 'change' => -1 * $legal_deal_send->total_number, 'after' => bc_sub($wallet->lock_change_balance, $legal_deal_send->total_number, 5)]; + $wallet->change_balance = bc_add($wallet->change_balance, $legal_deal_send->total_number, 5); + $wallet->lock_change_balance = bc_sub($wallet->lock_change_balance, $legal_deal_send->total_number, 5); + $wallet->save(); + AccountLog::insertLog(['user_id' => $legal_deal_send->seller_id, 'value' => $legal_deal_send->total_number, 'info' => '24小时未交易,发布取消,增加余额', 'type' => AccountLog::C2C_POST_AUTO_CANCEL, 'currency' => $legal_deal_send->currency_id], $data_wallet1); + AccountLog::insertLog(['user_id' => $legal_deal_send->seller_id, 'value' => $legal_deal_send->total_number * -1, 'info' => '24小时未交易,发布取消,锁定余额减少', 'type' => AccountLog::C2C_POST_AUTO_CANCEL, 'currency' => $legal_deal_send->currency_id], $data_wallet2); + } + $legal_deal_send->is_done = 2; + $legal_deal_send->save(); + $i++; + } + } + DB::commit(); + $this->info('执行成功'); + } catch (\Exception $exception) { + DB::rollback(); + $this->error($exception->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/AutoCancelC2CDeal.php b/app/Console/Commands/AutoCancelC2CDeal.php new file mode 100644 index 0000000..49ce1b7 --- /dev/null +++ b/app/Console/Commands/AutoCancelC2CDeal.php @@ -0,0 +1,45 @@ +info('开始执行15分钟自动取消C2C交易脚本-' . $now->toDateTimeString()); + $fiveteen = $now->subMinutes(15)->timestamp; + $results = C2cDeal::where('create_time', '<=', $fiveteen)->where('is_sure', 0)->get(); + $count = count($results); + $this->info('共有 ' . $count . ' 条可取消的记录'); + try { + DB::beginTransaction(); + if (!empty($results)) { + $i = 1; + foreach ($results as $result) { + $this->info('执行第 ' . $i . ' 条记录'); + C2cDeal::cancelLegalDealById($result->id, AccountLog::C2C_DEAL_AUTO_CANCEL); + $i++; + } + } + DB::commit(); + $this->info('执行成功'); + } catch (\Exception $exception) { + DB::rollback(); + $this->error($exception->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/AutoCancelLegal.php b/app/Console/Commands/AutoCancelLegal.php new file mode 100644 index 0000000..fdbba0f --- /dev/null +++ b/app/Console/Commands/AutoCancelLegal.php @@ -0,0 +1,43 @@ +info('开始执行自动取消法币交易脚本-' . $now->toDateTimeString()); + $twenty_four = $now->subHours(24)->timestamp; + $results = LegalDeal::where('create_time', '<=', $twenty_four)->where('is_sure', 0)->get(); + $count = count($results); + $this->info('共有 ' . $count . ' 条超时记录'); + DB::beginTransaction(); + try { + if (!empty($results)) { + $i = 1; + foreach ($results as $result) { + $this->info('执行第 ' . $i . ' 条记录'); + LegalDeal::cancelLegalDealById($result->id, AccountLog::LEGAL_DEAL_AUTO_CANCEL); + $i++; + } + } + DB::commit(); + $this->info('执行成功'); + } catch (\Exception $exception) { + DB::rollback(); + $this->error($exception->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/AutoDualOrder.php b/app/Console/Commands/AutoDualOrder.php new file mode 100644 index 0000000..bdb0d14 --- /dev/null +++ b/app/Console/Commands/AutoDualOrder.php @@ -0,0 +1,132 @@ +where('startdate','<=',date('Y-m-d',time())) + // where('expire','>=',date('Y-m-d',time())) + $dual_orderend = DualOrder::where('expire','<=',date('Y-m-d H:i:s',time()))->where('status',0)->where('today','<>',$nowday)->get(); + foreach ($dual_orderend as $dual_order){ + $DualCurrency = DualCurrency::where('id',$dual_order->dual_id)->first(); + $currency_id = $DualCurrency->currency_id; + $exercise_price = $DualCurrency->exercise_price; + $type = $DualCurrency->type; + $now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价 + + $amount = $dual_order->amount; + $totalincome = $dual_order->totalincome; + $rates = explode('-',$dual_order->rate); + + $rate = DualOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数 + + + + + $dual_order->todayincome = bcdiv($rate*$amount,100,2); + + $dual_order->totalincome = $totalincome+$dual_order->todayincome; + + + + // $money = $amount + $totalincome+$dual_order->todayincome; + + $money = $amount + $dual_order->todayincome; + $user_walllet=UsersWallet::where("user_id",$dual_order->user_id)->where("currency",3)->first(); + change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_DUAL_ORDER_RETURN,'组合投资理财结算');// . $user_walllet->name + + $data['user_id'] = $dual_order->user_id; + $data['order_id'] = $dual_order->id; + $data['day'] = $dual_order->day; + $data['rate'] = $dual_order->order_rate; + $data['amount'] = $dual_order->todayincome; + $data['addtime'] = time(); + DB::table('dual_list')->insert($data); + + $dual_order->status = 1; //修改状态为已结算 + $dual_order->today = $nowday; + $dual_order->save(); + + + + } + + + + + $dual_orders = DualOrder::where('startdate','<=',date('Y-m-d H:i:s',time()))->where('expire','>',date('Y-m-d H:i:s',time()))->where('today','<>',$nowday)->where('status',0)->get(); + + + foreach ($dual_orders as $dual_order){ + $DualCurrency = DualCurrency::where('id',$dual_order->dual_id)->first(); + $currency_id = $DualCurrency->currency_id; + $exercise_price = $DualCurrency->exercise_price; + $type = $DualCurrency->type; + $now_price = Currency::where('id',$currency_id)->pluck('price')->first();//查询最新价 + + $amount = $dual_order->amount; + $dual_order->startdate = date('Y-m-d H:i:s',strtotime($dual_order->startdate)+86400); + // $id = $dual_order->id; + $today = $dual_order->today; + $totalincome = $dual_order->totalincome; + // $rate = $dual_order->order_rate; + + $rates = explode('-',$dual_order->rate); + + $rate = DualOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数 + + + $dual_order->todayincome = bcdiv($rate*$amount,100,2); + + $dual_order->totalincome = $totalincome+$dual_order->todayincome; + + + $money = $dual_order->todayincome; + $user_walllet=UsersWallet::where("user_id",$dual_order->user_id)->where("currency",3)->first(); + change_wallet_balance($user_walllet , 2 , $money , AccountLog::USER_DUAL_ORDER_RETURN,'组合投资理财结算');// . $user_walllet->name + $data['user_id'] = $dual_order->user_id; + $data['order_id'] = $dual_order->id; + $data['day'] = $dual_order->day; + $data['rate'] = $dual_order->order_rate; + $data['amount'] = $money; + $data['addtime'] = time(); + DB::table('dual_list')->insert($data); + + $dual_order->today = $nowday; + $dual_order->save(); + + + } + + echo '已结算 '.PHP_EOL; + } +} \ No newline at end of file diff --git a/app/Console/Commands/AutoLixi.php b/app/Console/Commands/AutoLixi.php new file mode 100644 index 0000000..886eb14 --- /dev/null +++ b/app/Console/Commands/AutoLixi.php @@ -0,0 +1,73 @@ +where('startdate','<=',date('Y-m-d',time())) + // where('expire','>=',date('Y-m-d',time())) + $dual_orderend = UsersWallet::where('micro_balance','>',0)->where('today','<>',$nowday)->get(); + foreach ($dual_orderend as $dual_order){ + + + $amount = $dual_order->micro_balance; + + $rates = 0.6; + + // $rate = DualOrder::random_float($rates[0],$rates[1]); // 生成一个介于0到1之间的随机小数 + + $money = bcdiv($rates*$amount,100,2); + + + + + + + + + $user_walllet=UsersWallet::where("user_id",$dual_order->user_id)->where("currency",3)->first(); + + + change_wallet_balance($user_walllet , 4 , $money , AccountLog::USER_DUAL_ORDER_RETURN,'earned by currency');// . $user_walllet->name + // $dual_order->status = 1; //修改状态为已结算 + $dual_order->today = $nowday; + $dual_order->save(); + + + + } + + + + echo '已结算 '.PHP_EOL; + } +} \ No newline at end of file diff --git a/app/Console/Commands/AutoOrder.php b/app/Console/Commands/AutoOrder.php new file mode 100644 index 0000000..a2b8586 --- /dev/null +++ b/app/Console/Commands/AutoOrder.php @@ -0,0 +1,87 @@ +argument('id'); + $faker = Factory::create(); + DB::beginTransaction(); + try { + while (!empty($auto = AutoList::find($id))) { + if (empty($auto->is_start)) { + DB::rollback(); + return $this->error('机器人已关闭-' . Carbon::now()->toDateTimeString()); + break; + } else { + $this->info('开启机器人-' . Carbon::now()->toDateTimeString()); + $price_area = AutoList::getPriceArea($auto->currency_id, $auto->legal_id); + if (!empty($price_area)) { + $this->info('当前价格区间为 ' . $price_area['min'] . '-' . $price_area['max']); + $this->info('设置价格区间为 ' . $auto->min_price . '-' . $auto->max_price); + if ($auto->min_price <= $price_area['min'] && $auto->max_price >= $price_area['max']) { + $new_complete = new TransactionComplete(); + $new_complete->user_id = $auto->buy_user_id; + $new_complete->from_user_id = $auto->sell_user_id; + $new_complete->price = $faker->randomFloat(2, $price_area['min'], $price_area['max']); + $new_complete->number = $faker->randomFloat(2, $auto->min_number, $auto->max_number); + $new_complete->create_time = time(); + $new_complete->currency = $auto->currency_id; + $new_complete->legal = $auto->legal_id; + $new_complete->save(); + $buy_wallet_legal = UsersWallet::where('user_id', $auto->buy_user_id)->where('currency', $auto->legal_id)->lockForUpdate()->first(); + if (!empty($buy_wallet_legal)) { + $legal_decrement = bc_mul($new_complete->number, $new_complete->price, 5); + $buy_wallet_legal->decrement('legal_balance', $legal_decrement); + } + $buy_wallet = UsersWallet::where('user_id', $auto->buy_user_id)->where('currency', $auto->currency_id)->lockForUpdate()->first(); + if (!empty($buy_wallet)) { + $buy_wallet->increment('change_balance', $new_complete->number); + } + $sell_wallet_legal = UsersWallet::where('user_id', $auto->sell_user_id)->where('currency', $auto->legal_id)->lockForUpdate()->first(); + if (!empty($sell_wallet_legal)) { + $legal_increment = bc_mul($new_complete->number, $new_complete->price, 5); + $sell_wallet_legal->increment('legal_balance', $legal_increment); + } + $sell_wallet = UsersWallet::where('user_id', $auto->sell_user_id)->where('currency', $auto->currency_id)->lockForUpdate()->first(); + if (!empty($sell_wallet)) { + $sell_wallet->decrement('change_balance', $new_complete->number); + } + $this->info($auto->legal_name . '/' . $auto->currency_name . ' 生成价格为 ' . $new_complete->price . ' 数量为 ' . $new_complete->number . ' 的交易记录-' . Carbon::now()->toDateTimeString()); + $total = TransactionComplete::where('currency', $auto->currency_id)->where('legal', $auto->legal_id)->where('create_time', '>=', strtotime(date('Y-m-d')))->sum('number'); + $data = ['legal_id' => $auto->legal_id, 'currency_id' => $auto->currency_id, 'volume' => $total, 'now_price' => $new_complete->price]; + CurrencyQuotation::updateTodayPriceTable($data); + MarketHour::batchWriteMarketData($auto->currency_id, $auto->legal_id, $new_complete->number, $new_complete->price, 4); + DB::commit(); + } + } else { + DB::rollback(); + return $this->error('没有当前价格区间'); + } + sleep($auto->need_second); + } + } + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/BonusAlgorithm.php b/app/Console/Commands/BonusAlgorithm.php new file mode 100644 index 0000000..e233cfb --- /dev/null +++ b/app/Console/Commands/BonusAlgorithm.php @@ -0,0 +1,168 @@ +comment("后台奖金设置错误"); + exit; + } + $this->user_bonus = @json_decode($user_bonus, true); + $this->ecology_bonus = @json_decode($ecology_bonus, true); + $users = Users::get(); + $this->comment("奖金算法start"); + foreach ($users as $u) { + if ($u->balance > 0) { + $this->setUserBonus($u); + } + } + foreach ($users as $s) { + if ($s->level == Users::USER_LEVEL_ORDINARY) { + $this->setEcologyBonus($s); + } + } + foreach ($users as $a) { + if ($a->level > Users::USER_LEVEL_ORDINARY) { + $this->setAgentReward($a); + } + } + $this->comment("奖金算法end"); + } + public function setAgentReward($user) + { + if (empty($user)) { + return false; + } + DB::beginTransaction(); + try { + $son = Users::where("parent_id", $user->id)->get(); + $money = 0; + if (!empty($son)) { + foreach ($son as $s) { + $money_g = $this->getSonBonus($s) * $this->getProportion($user->level, $s->level); + $money = $money + $money_g; + } + } + if (!empty($money)) { + $user->sub_balance = $user->sub_balance + $money; + $user->save(); + AccountLog::insertLog(array("user_id" => $user->id, "value" => $money, "type" => AccountLog::AGENT_REWARD, "info" => "代理商管理奖励")); + $this->comment($user->id . ":代理商管理奖励" . $money); + } + DB::commit(); + } catch (\Exception $ex) { + DB::rollback(); + $this->comment($ex->getMessage()); + } + } + public function getProportion($self_level, $level) + { + if (empty($self_level) || empty($level)) { + return 0.05; + } + $difference = $self_level - $level; + if ($difference <= 0 || $difference > 5) { + return 0.05; + } else { + return $difference * 0.05; + } + } + public function getSonBonus($user) + { + if (empty($user)) { + return 0; + } + $son = Users::getSon($user->id); + $time = time(); + $start_time = $time - 3600; + $user_arr = array(); + array_push($user_arr, $user->id); + if (!empty($son)) { + foreach ($son as $s) { + array_push($user_arr, $s["user_id"]); + } + } + $user_bonus = AccountLog::where("type", AccountLog::USER_BONUS)->whereIn("user_id", $user_arr)->where("created_time", ">", $start_time)->sum("value"); + $ecology_bonus = AccountLog::where("type", AccountLog::ECOLOGY_BONUS)->whereIn("user_id", $user_arr)->where("created_time", ">", $start_time)->sum("value"); + return $user_bonus + $ecology_bonus; + } + public function setEcologyBonus($user) + { + if (empty($user)) { + return false; + } + DB::beginTransaction(); + $son = Users::getSonId($user->id); + $time = time(); + $start_time = $time - 3600; + $money = 0; + try { + if (!empty($son)) { + foreach ($son as $s) { + $log = AccountLog::where("type", AccountLog::USER_BONUS)->where("user_id", $s["user_id"])->where("created_time", ">", $start_time)->first(); + if (!empty($log)) { + foreach ($this->ecology_bonus as $eb) { + if (!empty($eb["one"]) && !empty($eb["two"]) && !empty($eb["three"]) && !empty($eb["four"])) { + if ($eb["one"] <= $user->balance && $user->balance < $eb["two"]) { + $interest_rate = $s["level"] == 1 ? $eb["three"] : $eb["four"]; + $interest_rate = $interest_rate / 100; + $money = $money + $log->value * $interest_rate; + break 1; + } + } + } + } + } + } + if ($money > 0) { + $user->sub_balance = $user->sub_balance + $money; + $user->save(); + AccountLog::insertLog(array("user_id" => $user->id, "value" => $money, "type" => AccountLog::ECOLOGY_BONUS, "info" => "生态推广奖励增加")); + $this->comment($user->id . ":生态推广奖励增加" . $money); + } + DB::commit(); + } catch (\Exception $ex) { + DB::rollback(); + $this->comment($ex->getMessage()); + } + } + public function setUserBonus($user) + { + if (empty($user)) { + return false; + } + DB::beginTransaction(); + try { + foreach ($this->user_bonus as $ub) { + if (!empty($ub["one"]) && !empty($ub["two"]) && !empty($ub["three"])) { + if ($ub["one"] <= $user->balance && $user->balance < $ub["two"]) { + $money = $user->balance * ($ub["three"] / 100); + $user->sub_balance = $user->sub_balance + $money; + $user->save(); + AccountLog::insertLog(array("user_id" => $user->id, "value" => $money, "type" => AccountLog::USER_BONUS, "info" => "日均收益增加")); + $this->comment($user->id . ":日均收益增加" . $money); + break 1; + } + } + } + DB::commit(); + } catch (\Exception $ex) { + DB::rollback(); + $this->comment($ex->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/CancelC2ctime.php b/app/Console/Commands/CancelC2ctime.php new file mode 100644 index 0000000..7842e56 --- /dev/null +++ b/app/Console/Commands/CancelC2ctime.php @@ -0,0 +1,44 @@ +comment('开始执行自动取消C2C交易脚本-' . $now->toDateTimeString()); + $userLegalDealCancel_time = Setting::getValueByKey("userLegalDealCancel_time") * 60; + $result = LegalDeal::where("is_sure", 0)->get(); + foreach ($result as $key => $value) { + $time = time(); + $create_time = strtotime($value->create_time); + if ($create_time + $userLegalDealCancel_time <= $time) { + $id = $value->id; + if ($value->is_sure == 0) { + LegalDeal::cancelLegalDealById($id); + $aaaa = Users::find($value->user_id); + $aaaa->today_LegalDealCancel_num = $aaaa->today_LegalDealCancel_num + 1; + $aaaa->LegalDealCancel_num__update_time = time(); + $aaaa->save(); + } else { + return $this->error('该订单状态不能取消'); + } + } + } + $this->comment('执行成功'); + } +} \ No newline at end of file diff --git a/app/Console/Commands/CollectToken.php b/app/Console/Commands/CollectToken.php new file mode 100644 index 0000000..c083739 --- /dev/null +++ b/app/Console/Commands/CollectToken.php @@ -0,0 +1,107 @@ +argument('currency_id'); + $currency = Currency::find($currency_id); + $contract_address = $currency->contract_address; + $total_account_address = $currency->total_account; + $total_account_key = $currency->key; + $currency_type = $currency->type; + $this->decimal_scale = $currency->decimal_scale; + if (empty($contract_address) || empty($total_account_address) || empty($total_account_key)) { + $this->comment("后台账号设置错误"); + exit; + } + $this->contract_address = $contract_address; + if ($currency_type == 'erc20') { + $this->total_account_address = substr($total_account_address, 2); + } else { + $this->total_account_address = $total_account_address; + } + $this->total_account_key = $total_account_key; + $this->currency_type = $currency_type; + $datas = UsersWallet::where('currency', $currency_id)->get(); + $this->comment("start"); + foreach ($datas as $d) { + $this->collectToken($d); + } + $this->comment("end"); + } + public function collectToken($data) + { + if ($this->currency_type == 'btc') { + return false; + } + if (empty($data->address)) { + return false; + } + $address = $data->address; + if ($this->currency_type == 'eth') { + $url = "https://api.etherscan.io/api?module=account&action=balance&address=" . $address . "&tag=latest&apikey=579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45" . rand(1, 10000); + } else { + $url = "https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=" . $this->contract_address . "&address=" . $address . "&tag=latest&apikey=579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45" . rand(1, 1000); + } + $content = RPC::apihttp($url); + if (!$content) { + return false; + } + DB::beginTransaction(); + try { + $content = json_decode($content, true); + if (isset($content["message"]) && $content["message"] == "OK") { + $lessen = bc_pow(10, $this->decimal_scale); + $chain_balance = bc_div($content["result"], $lessen); + if ($chain_balance > 0) { + if ($this->currency_type == 'eth') { + $content["result"] = $content["result"] / 1000000000000000000; + $content['result'] -= 0.001; + $address_url = 'http://47.92.171.137:8999/web3/transfer?toaddress=' . $this->total_account_address . '&from_address=' . $address . '&transfer_value=' . $content["result"] . '&privates=' . decrypt($data->private); + } else { + $address_url = "http://47.92.171.137:8999/web3/transfer/oec?is_new=1&toaddress=" . $this->total_account_address . "&transfer_value=" . $content["result"] . "&contract_address=" . $this->contract_address . "&fromeaddress=" . $address . "&privates=" . decrypt($data->private) . '&decimal_scale=' . $this->decimal_scale; + } + $lian = RPC::apihttp($address_url); + $lian = @json_decode($lian, true); + if ($lian["error"] == "0") { + $data->old_balance = 0; + $data->save(); + AccountLog::insertLog(array("user_id" => 99999, "value" => $content["result"], "type" => AccountLog::ETH_EXCHANGE, "info" => $data->user_id . "归拢", 'currency' => $data->currency)); + $this->comment($this->total_account_address . "user_id:" . $lian["content"]); + } else { + $this->comment('请求地址:'); + dump($address_url); + $this->comment('请求响应:'); + dump($lian); + $this->comment("请重试" . $lian["error"]); + } + } else { + $this->comment($content["result"]); + } + } else { + $this->comment($content); + } + DB::commit(); + } catch (\Exception $ex) { + DB::rollback(); + $this->comment($ex->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/ExecuteCurrency.php b/app/Console/Commands/ExecuteCurrency.php new file mode 100644 index 0000000..38522fd --- /dev/null +++ b/app/Console/Commands/ExecuteCurrency.php @@ -0,0 +1,88 @@ +argument('id'); + try { + $is_execute = Setting::getValueByKey('currency_' . $id, 0); + if ($is_execute == 1) { + throw new \Exception('该币上币脚本正在运行中,请不要重复执行'); + } + Setting::updateValueByKey('currency_' . $id, 1); + $currency = Currency::find($id); + if (empty($currency)) { + throw new \Exception('币种不存在'); + } + if (!in_array($currency->type, ['btc', 'usdt', 'eth', 'erc20', 'xrp'])) { + throw new \Exception('不支持的币种'); + } + $address_url = '/v3/wallet/address'; + $project_name = config('app.name'); + $http_client = app('LbxChainServer'); + $this->info('开始执行按币种生成钱包脚本--' . Carbon::now()->toDateTimeString()); + $user_query = Users::whereNotExists(function ($query) use($id) { + $query->select(DB::raw(1))->from('users_wallet')->where('currency', $id)->whereRaw('users_wallet.user_id = users.id'); + }); + $count = $user_query->count(); + $this->info('共有 ' . $count . ' 个用户需要添加新的钱包地址'); + $i = 1; + foreach ($user_query->cursor() as $user) { + if (UsersWallet::where('user_id', $user->id)->where('currency', $id)->exists()) { + $this->error('第 ' . $i . '/' . $count . ' 个用户有此币种钱包,用户 id 为:' . $user->id); + continue 1; + } + $this->info('开始生成第 ' . $i . '/' . $count . ' 个用户的钱包地址,用户 id 为:' . $user->id); + $response = $http_client->post($address_url, ['form_params' => ['userid' => $user->id, 'projectname' => $project_name]]); + $result = json_decode($response->getBody()->getContents()); + if ($result->code != 0) { + return false; + } + $walllet_data = $result->data; + if ($currency->type == 'btc') { + $address = $walllet_data->btc_address; + $private = $walllet_data->btc_private; + } elseif ($currency->type == 'usdt') { + $address = $walllet_data->usdt_address; + $private = $walllet_data->usdt_private; + } elseif ($currency->type == 'eth') { + $address = $walllet_data->eth_address; + $private = $walllet_data->eth_private; + } elseif ($currency->type == 'erc20') { + $address = $walllet_data->erc20_address; + $private = $walllet_data->erc20_private; + } elseif ($currency->type == 'xrp') { + $address = $walllet_data->xrp_address; + $private = $walllet_data->xrp_private; + } else { + $this->error('暂不支持生成该币种的钱包'); + continue 1; + } + UsersWallet::unguarded(function () use($address, $private, $user, $currency) { + UsersWallet::create(['user_id' => $user->id, 'currency' => $currency->id, 'address' => $address, 'private' => $private, 'create_time' => time()]); + }); + $i++; + } + Setting::updateValueByKey('currency_' . $id, 0); + $this->info('执行成功'); + } catch (\Exception $exception) { + return $this->error($exception->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/FollowCommand.php b/app/Console/Commands/FollowCommand.php new file mode 100644 index 0000000..584be83 --- /dev/null +++ b/app/Console/Commands/FollowCommand.php @@ -0,0 +1,226 @@ +where('status', 1) + ->chunkById(50, function ($items) { + $items->each(function ($follow) { + $this->handleFollow($follow); + }); + }); + } + + protected function handleFollow($follow) + { + //查看跟随的用户是否为交易员 + $is_trader = Users::where('id', $follow->follow_user_id)->value('is_trader'); + if ($is_trader != 1) { + $this->cancelFollow($follow->id); + return false; + } + + $transaction = LeverTransaction::query() + ->where([ + 'user_id' => $follow->follow_user_id, + 'status' => 1 + ]) + ->where('create_time', '>=', strtotime($follow->created_at)) + ->get(); + foreach ($transaction as $val) { + //查询是否已存在该订单的跟单 + $exists_follow_order = LeverTransaction::query() + ->where('user_id', $follow->user_id) + ->where('follow_order_id', $val->id) + ->where('follow_user_id', $follow->follow_user_id) + ->exists(); + //不存在则添加 + if (!$exists_follow_order) { + $this->generateFollowOrder($val, $follow); + } + } + } + + /** + * 生成跟随订单 + * + * @param $order + * @param $follow + * @return false|void + */ + protected function generateFollowOrder($order, $follow) + { + try { + $order = $order->getOriginal(); + $currency_match = CurrencyMatch::where('legal_id', $order['legal']) + ->where('currency_id', $order['currency']) + ->first(); + if (!$currency_match) { //指定交易对不存在 + throw new \Exception("指定交易对不存在"); + } + if ($currency_match->open_lever != 1) { //未开通本交易对的交易功能 + throw new \Exception("未开通本交易对的交易功能"); + } + + $follow_order = $order; + $follow_order['order_type'] = 2; + $follow_order['follow_user_id'] = $order['user_id']; + $follow_order['follow_order_id'] = $order['id']; + $follow_order['user_id'] = $follow->user_id; + $follow_order['status'] = LeverTransaction::TRANSACTION; + + if ($follow->type == 1) {//跟随类型:1固定比例跟随 2固定手数跟随 + $number = bc_mul($order['number'], $follow->number, 2); + + $number = $number <= 1 ? 1 : $number; + } else { + $number = $follow->number; + } + //算法参考:App\Http\Controllers\Api\LeverController->submit() + $all_money = bc_mul($order['price'], $number); + $caution_money = bc_div($all_money, $order['multiple']); //保证金 + + //计算手续费 + $lever_trade_fee_rate = bc_div($currency_match->lever_trade_fee ?? 0, 100); + $trade_fee = bc_mul($all_money, $lever_trade_fee_rate); //手续费 + + $follow_order['share'] = $number; + $follow_order['number'] = $number; + $follow_order['origin_caution_money'] = $caution_money; + $follow_order['caution_money'] = $caution_money; + $follow_order['trade_fee'] = $trade_fee; + //追加用户的代理商关系 + $user = Users::query()->where('id', $follow->user_id)->first(['agent_path']); + $follow_order['agent_path'] = $user->agent_path; + + DB::beginTransaction(); + + $legal = UsersWallet::where("user_id", $follow->user_id) + ->where("currency", $order['legal']) + ->lockForUpdate() + ->first(); + if (!$legal) { + throw new \Exception("该用户对应钱包未找到"); + } + $user_lever = $legal->lever_balance; + + $shoud_deduct = bc_add($caution_money, $trade_fee); //保证金+手续费 + if (bc_comp($user_lever, $shoud_deduct) < 0) { + throw new \Exception($currency_match->legal_name . '余额不足,不能小于:' . $shoud_deduct . '(手续费:' . $trade_fee . ')'); + } + unset($follow_order['id']); + + $lever_transaction = LeverTransaction::query()->create($follow_order); + + //扣除保证金 + $result = change_wallet_balance( + $legal, + 4, + -$caution_money, + AccountLog::LEVER_TRANSACTION_DEDUCT_CAUTION, + '跟随购买 ' . $currency_match->symbol . ' 杠杆交易,价格' . $order['price'] . ',扣除保证金', + false, + 0, + 0, + serialize([ + 'trade_id' => $lever_transaction->id, + 'all_money' => $all_money, + 'multiple' => $order['multiple'], + ]) + ); + if ($result !== true) { + throw new \Exception('扣除保证金失败:' . $result); + } + //扣除手续费 + $result = change_wallet_balance( + $legal, + 4, + -$trade_fee, + AccountLog::LEVER_TRANSACTION_TRADE_FEE, + '跟随购买 ' . $currency_match->symbol . ' 杠杆交易,扣除手续费', + false, + 0, + 0, + serialize([ + 'trade_id' => $lever_transaction->id, + 'all_money' => $all_money, + 'lever_trade_fee_rate' => $lever_trade_fee_rate, + ]) + ); + if ($result !== true) { + throw new \Exception('扣除手续费失败:' . $result); + } + DB::commit(); + + dump("跟随订单已生成,ID:{$lever_transaction->id}"); + } catch (\Throwable $ex) { + DB::rollBack(); + $msg = "跟随者用户id:{$follow->user_id},跟随订单id:{$order['id']}," . $ex->getMessage(); + $this->writeLog($msg); + dump($msg); + return false; + } + } + + //取消跟随 + protected function cancelFollow($follow_id) + { + Follow::where('id', $follow_id)->update([ + 'status' => 2 + ]); + } + + /** + * 写日志 + * @param $msg + */ + protected function writeLog($msg) + { + $path = base_path() . '/storage/logs/follow/'; + $filename = 'FollowCommand-' . date('Ymd') . '.log'; + file_exists($path) || @mkdir($path); + error_log(date('Y-m-d H:i:s') . ' ' . $msg . PHP_EOL, 3, $path . $filename); + } +} diff --git a/app/Console/Commands/GHK.php b/app/Console/Commands/GHK.php new file mode 100644 index 0000000..70c1d36 --- /dev/null +++ b/app/Console/Commands/GHK.php @@ -0,0 +1,220 @@ +period = $argv[2]; + $this->size = $argv[3]; + } + + /** + * Execute the console command. + * + * @return mixed + */ + public function handle() + { + + $all = DB::table('currency')->where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + //拼接所有的交易对 + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { +// echo ("begin2"); + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar_a['currency_name'] = $item['name']; + $ar_a['quote_name'] = $legal['name']; + $ar[] = $ar_a; + } + } + } + foreach ($ar as $vv) { + if (in_array($vv["name"], array("btcusdt", "ethusdt", "ltcusdt", "bchusdt", "eosusdt", "etcusdt", "xrpusdt", "htusdt", "qtumusdt", "iotausdt", "neousdt", "nasusdt", "elausdt", "sntusdt", "wiccusdt", "adausdt", "xemusdt", "ruffusdt", "zilusdt", "dtausdt",'usdcusdt','shibusdt'))) { + // if (in_array($vv["name"], array("btcusdt","ethusdt","ltcusdt"))) { + // if (in_array($vv["name"], array("btcusdt"))) { + $ar_new[] = $vv; + } + + } + foreach ($ar_new as $it) { + $data = $this->get_history_kline($it['name'], $this->period, $this->size); + if ($data) { + + } else { +// echo ("重新采集\n\r"); + // sleep(5); + continue; + } + if ($data['status'] != 'ok') { +// echo ("begin6"); +// var_dump($data); + $this->error('请求失败'); + continue; + } + $list = $data['data']; + foreach($list as $value){ + $data = [ + 'id' => $value['id'], + 'period' => $this->period, + 'base-currency' => strtoupper($it['currency_name']), + 'quote-currency' => strtoupper($it['quote_name']), + 'open' => $value['open'], + 'close' => $value['close'], + 'high' => $value['high'], + 'low' => $value['low'], + 'vol' => $value['vol'], + 'amount' => $value['amount'], + ]; + MarketHour::setEsearchMarket($data); + } + + + } + + } + + /**对象转数组 + * @param $obj + * @return mixed + */ + public function object2array($obj){ + return json_decode( json_encode( $obj),true); + } + //科学计算发转字符串 + public function sctonum($num, $double = 8){ + if(false !== stripos($num, "e")){ + $a = explode("e",strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + }else{ + return $num; + } + } + + +// /** +// * 行情类API +// */ +// // 获取K线数据 + public function get_history_kline($symbol = '', $period='',$size=0) { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = [ + 'symbol' => $symbol, + 'period' => $period + ]; + if ($size) $param['size'] = $size; + $url = $this->create_sign_url($param); +// echo $url;exit; + return json_decode($this->curl($url) , TRUE); + } +// /** +// * 类库方法 +// */ +// // 生成验签URL + public function create_sign_url($append_param = []) { + // 验签参数 + $param = [ + 'AccessKeyId' => '89fcab07-1hrfj6yhgg-ae50f8cf-6c7db', + 'SignatureMethod' => 'HmacSHA256', + 'SignatureVersion' => 2, + 'Timestamp' => date('Y-m-d\TH:i:s', time()) + ]; + if ($append_param) { + foreach($append_param as $k=>$ap) { + $param[$k] = $ap; + } + } + return $this->url.$this->api_method.'?'.$this->bind_param($param); + } +// // 组合参数 + function bind_param($param) { + $u = []; + $sort_rank = []; + foreach($param as $k=>$v) { + $u[] = $k."=".urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=".urlencode($this->create_sig($u)); + return implode('&', $u); + } +// // 生成签名 + function create_sig($param) { + $sign_param_1 = $this->req_method."\n".$this->api."\n".$this->api_method."\n".implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, '88dd5bbe-1799f6a1-e2a33400-924b1', true); + return base64_encode($signature); + } + public function curl($url,$postdata=[]) { + $ch = curl_init(); + curl_setopt($ch,CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); + curl_setopt($ch,CURLOPT_HEADER,0); + curl_setopt($ch, CURLOPT_TIMEOUT,60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt ($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + ]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + + + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline.php b/app/Console/Commands/GetKline.php new file mode 100644 index 0000000..1f3e891 --- /dev/null +++ b/app/Console/Commands/GetKline.php @@ -0,0 +1,243 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + echo "begin2"; + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + echo "开始遍历币种\r\n"; + foreach ($ar as $vv) { + if (in_array($vv["name"], array("shibusdt", "goldusdt", "uncusdt", "grtcusdt", "tonusdt"))) { + $ar_new[] = $vv; + } + } + // file_put_contents("ar_new.txt", json_encode($ar_new) . PHP_EOL, FILE_APPEND); + foreach ($ar_new as $it) { + echo "遍历币种开始\r\n"; + $data = array(); + echo "开始请求\r\n"; + $data = $this->get_history_kline($it['name'], '1min', 1); + if ($data) { + } else { + // file_put_contents("test1.txt", $it['name']. PHP_EOL, FILE_APPEND); + echo "重新采集\r\n"; + continue 2; + } + echo "请求结束\r\n"; + if ($data['status'] != 'ok') { + echo "begin6"; + $this->error('请求失败'); + continue 2; + } + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('type', 5)->where('period', '1min')->where('sign', 2)->first(); + if ($insert_instance) { + echo "begin7"; + $this->error('指定时间行情已存在,直接跳过'); + continue 2; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 5; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '1min'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + $update_Data = []; + $update_Data['currency_id'] = $it['currency_id']; + $update_Data['legal_id'] = $it['legal_id']; + $update_Data['now_price'] = $this->sctonum($info['close']); + $update_Data['add_time'] = time(); + $update_Data['volume'] = '0.00000'; + $update_Data['change'] = '+0.00'; + $time = strtotime(date("Y-m-d")); + $day_Data = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('period', '1day')->where('sign', 2)->where('day_time', '<=', $time)->where('end_price', '>', '0.00000')->orderby('id', 'DESC')->first(); + if (!empty($day_Data)) { + $_zero_price = $day_Data->end_price; + } else { + $_zero_price = 0; + } + $update_Data['volume'] = DB::table('market_hour')->where('day_time', '>', $time)->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('period', '1min')->where('sign', 2)->sum('number'); + switch (bccomp($update_Data['now_price'], $_zero_price, 5)) { + case 1: + if ($_zero_price === 0) { + $update_Data['change'] = '+0.000'; + } else { + $a = bcsub($update_Data['now_price'], $_zero_price, 5); + $_pencet_num = bcdiv($a, $_zero_price, 5); + $update_Data['change'] = '+' . bcmul($_pencet_num, 100, 3); + } + break 3; + case 0: + $update_Data['change'] = '+0.000'; + break 3; + case -1: + if ($_zero_price === 0) { + $update_Data['change'] = '+0.000'; + } else { + $a = bcsub($_zero_price, $update_Data['now_price'], 5); + $_pencet_num = bcdiv($a, $_zero_price, 5); + $update_Data['change'] = '-' . bcmul($_pencet_num, 100, 3); + } + break 3; + default: + $update_Data['change'] = '+0.000'; + } + $que_data = DB::table('currency_quotation')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->orderby('id', 'DESC')->first(); + if (!empty($que_data)) { + DB::table('currency_quotation')->where('id', $que_data->id)->update($update_Data); + } else { + DB::table('currency_quotation')->insert($update_Data); + } + $currency = Currency::find($it['currency_id']); + $legal = Currency::find($it['legal_id']); + $update_Data['currency_name'] = $currency->name; + $update_Data['legal_name'] = $legal->name; + $update_Data['type'] = 'daymarket'; + $update_Data['high'] = $insert_Data['highest']; + $update_Data['low'] = $this->sctonum($info['low']); + $update_Data['symbol'] = $currency->name . '/' . $legal->name; + echo "begin8"; + $new_data = ['type' => 'kline', 'period' => $insert_Data['period'], 'currency_id' => $insert_Data['currency_id'], 'currency_name' => $currency->name, 'legal_id' => $insert_Data['legal_id'], 'legal_name' => $legal->name, 'symbol' => $currency->name . '/' . $legal->name, 'open' => $insert_Data['start_price'], 'close' => $insert_Data['end_price'], 'high' => $insert_Data['highest'], 'low' => $insert_Data['mminimum'], 'volume' => $insert_Data['number'], 'time' => $insert_Data['day_time'] * 1000]; + echo "开始推送\r\n"; + print_r($update_Data); + UserChat::sendChat($update_Data); + UserChat::sendChat($new_data); + unset($currency); + unset($legal); + echo "遍历币种结束\r\n"; + } + sleep(5); + } catch (Exception $e) { + } + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + echo "获取K线数据\r\n"; + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + file_put_contents("log.txt", $url . PHP_EOL, FILE_APPEND); + echo "获取K线数据结束\r\n"; + return json_decode($this->curl($url), true); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + public function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + public function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + echo "curl开始\r\n"; + $start = microtime(true); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 4); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + if (empty($output)) { + echo "curl没有采集到\r\n"; + } + echo "curl结束\r\n"; + $end = microtime(true); + file_put_contents("haoshi.txt", $end - $start . PHP_EOL, FILE_APPEND); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline_Daily.php b/app/Console/Commands/GetKline_Daily.php new file mode 100644 index 0000000..8031661 --- /dev/null +++ b/app/Console/Commands/GetKline_Daily.php @@ -0,0 +1,147 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + $kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE); + if ($kko['status'] == 'ok') { + $trade = []; + foreach ($kko['data'] as $key => $value) { + $trade[] = $value['symbol']; + } + foreach ($ar as $it) { + if (in_array($it['name'], $trade)) { + $data = array(); + $data = $this->get_history_kline($it['name'], '1day', 1); + if ($data['status'] == 'ok') { + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '1day')->where('sign', 2)->where('type', 4)->first(); + if (!empty($insert_instance)) { + continue 1; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 4; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '1day'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + } + } + } + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + return json_decode($this->curl($url), TRUE); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline_FifteenMin.php b/app/Console/Commands/GetKline_FifteenMin.php new file mode 100644 index 0000000..bb10191 --- /dev/null +++ b/app/Console/Commands/GetKline_FifteenMin.php @@ -0,0 +1,147 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + $kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE); + if ($kko['status'] == 'ok') { + $trade = []; + foreach ($kko['data'] as $key => $value) { + $trade[] = $value['symbol']; + } + foreach ($ar as $it) { + if (in_array($it['name'], $trade)) { + $data = array(); + $data = $this->get_history_kline($it['name'], '15min', 1); + if ($data['status'] == 'ok') { + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '15min')->where('sign', 2)->where('type', 1)->first(); + if (!empty($insert_instance)) { + continue 1; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 1; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '15min'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + } + } + } + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + return json_decode($this->curl($url), TRUE); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline_Hourly.php b/app/Console/Commands/GetKline_Hourly.php new file mode 100644 index 0000000..6ef9fa1 --- /dev/null +++ b/app/Console/Commands/GetKline_Hourly.php @@ -0,0 +1,147 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + $kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE); + if ($kko['status'] != 'ok') { + return false; + } + $trade = array_column($kko['data'], 'symbol'); + foreach ($ar as $it) { + if (!in_array($it['name'], $trade)) { + continue 1; + } + $data = array(); + $data = $this->get_history_kline($it['name'], '60min', 1); + if ($data['status'] != 'ok') { + continue 1; + } + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '60min')->where('sign', 2)->where('type', 2)->first(); + if (!empty($insert_instance)) { + continue 1; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 2; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '60min'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + return json_decode($this->curl($url), TRUE); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline_Monthly.php b/app/Console/Commands/GetKline_Monthly.php new file mode 100644 index 0000000..189c7bc --- /dev/null +++ b/app/Console/Commands/GetKline_Monthly.php @@ -0,0 +1,148 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + $kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE); + if ($kko['status'] == 'ok') { + $trade = []; + foreach ($kko['data'] as $key => $value) { + $trade[] = $value['symbol']; + } + foreach ($ar as $it) { + if (in_array($it['name'], $trade)) { + $data = array(); + $data = $this->get_history_kline($it['name'], '1mon', 1); + if ($data['status'] == 'ok') { + $info = $data['data'][0]; + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '1mon')->where('sign', 2)->where('type', 9)->first(); + if (!empty($insert_instance)) { + continue 1; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 9; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '1mon'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + } + } + } + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + return json_decode($this->curl($url), TRUE); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline_ThirtyMin.php b/app/Console/Commands/GetKline_ThirtyMin.php new file mode 100644 index 0000000..daf12be --- /dev/null +++ b/app/Console/Commands/GetKline_ThirtyMin.php @@ -0,0 +1,147 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + $kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE); + if ($kko['status'] == 'ok') { + $trade = []; + foreach ($kko['data'] as $key => $value) { + $trade[] = $value['symbol']; + } + foreach ($ar as $it) { + if (in_array($it['name'], $trade)) { + $data = array(); + $data = $this->get_history_kline($it['name'], '30min', 1); + if ($data['status'] == 'ok') { + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '30min')->where('sign', 2)->where('type', 7)->first(); + if (!empty($insert_instance)) { + continue 1; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 7; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '30min'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + } + } + } + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + return json_decode($this->curl($url), TRUE); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline_Weekly.php b/app/Console/Commands/GetKline_Weekly.php new file mode 100644 index 0000000..f66f772 --- /dev/null +++ b/app/Console/Commands/GetKline_Weekly.php @@ -0,0 +1,147 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + $kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE); + if ($kko['status'] == 'ok') { + $trade = []; + foreach ($kko['data'] as $key => $value) { + $trade[] = $value['symbol']; + } + foreach ($ar as $it) { + if (in_array($it['name'], $trade)) { + $data = array(); + $data = $this->get_history_kline($it['name'], '1week', 1); + if ($data['status'] == 'ok') { + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '1week')->where('sign', 2)->where('type', 8)->first(); + if (!empty($insert_instance)) { + continue 1; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 8; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '1week'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + } + } + } + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + return json_decode($this->curl($url), TRUE); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetKline_fiveMin.php b/app/Console/Commands/GetKline_fiveMin.php new file mode 100644 index 0000000..ee0b268 --- /dev/null +++ b/app/Console/Commands/GetKline_fiveMin.php @@ -0,0 +1,146 @@ +where('is_display', '1')->get(); + $all_arr = $this->object2array($all); + $legal = DB::table('currency')->where('is_display', '1')->where('is_legal', '1')->get(); + $legal_arr = $this->object2array($legal); + $ar = []; + foreach ($legal_arr as $legal) { + foreach ($all_arr as $item) { + if ($legal['id'] != $item['id']) { + $ar_a = []; + $ar_a['name'] = strtolower($item['name']) . strtolower($legal['name']); + $ar_a['currency_id'] = $item['id']; + $ar_a['legal_id'] = $legal['id']; + $ar[] = $ar_a; + } + } + } + $kko = json_decode($this->curl('https://api.huobi.br.com/v1/common/symbols'), TRUE); + if ($kko['status'] != 'ok') { + return false; + } + $trade = array_column($kko['data'], 'symbol'); + foreach ($ar as $it) { + if (in_array($it['name'], $trade)) { + $data = array(); + $data = $this->get_history_kline($it['name'], '5min', 1); + if ($data['status'] != 'ok') { + continue 1; + } + $info = $data['data'][0]; + $insert_instance = DB::table('market_hour')->where('currency_id', $it['currency_id'])->where('legal_id', $it['legal_id'])->where('day_time', '=', $info['id'])->where('period', '5min')->where('sign', 2)->where('type', 6)->first(); + if (!empty($insert_instance)) { + continue 1; + } + $insert_Data = array(); + $insert_Data['currency_id'] = $it['currency_id']; + $insert_Data['legal_id'] = $it['legal_id']; + $insert_Data['start_price'] = $this->sctonum($info['open']); + $insert_Data['end_price'] = $this->sctonum($info['close']); + $insert_Data['mminimum'] = $this->sctonum($info['low']); + $insert_Data['highest'] = $this->sctonum($info['high']); + $insert_Data['type'] = 6; + $insert_Data['sign'] = 2; + $insert_Data['day_time'] = $info['id']; + $insert_Data['period'] = '5min'; + $insert_Data['number'] = bcmul($info['amount'], 1, 5); + $insert_Data['mar_id'] = $info['id']; + DB::table('market_hour')->insert($insert_Data); + echo 'five min done'; + } + } + } + public function object2array($obj) + { + return json_decode(json_encode($obj), true); + } + public function sctonum($num, $double = 8) + { + if (false !== stripos($num, "e")) { + $a = explode("e", strtolower($num)); + return bcmul($a[0], bcpow(10, $a[1], $double), $double); + } else { + return $num; + } + } + public function get_history_kline($symbol = '', $period = '', $size = 0) + { + $this->api_method = "/market/history/kline"; + $this->req_method = 'GET'; + $param = ['symbol' => $symbol, 'period' => $period]; + if ($size) { + $param['size'] = $size; + } + $url = $this->create_sign_url($param); + return json_decode($this->curl($url), TRUE); + } + public function create_sign_url($append_param = []) + { + $param = ['AccessKeyId' => ACCESS_KEY, 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => date('Y-m-d\\TH:i:s', time())]; + if ($append_param) { + foreach ($append_param as $k => $ap) { + $param[$k] = $ap; + } + } + return $this->url . $this->api_method . '?' . $this->bind_param($param); + } + function bind_param($param) + { + $u = []; + $sort_rank = []; + foreach ($param as $k => $v) { + $u[] = $k . "=" . urlencode($v); + $sort_rank[] = ord($k); + } + asort($u); + $u[] = "Signature=" . urlencode($this->create_sig($u)); + return implode('&', $u); + } + function create_sig($param) + { + $sign_param_1 = $this->req_method . "\r\n" . $this->api . "\r\n" . $this->api_method . "\r\n" . implode('&', $param); + $signature = hash_hmac('sha256', $sign_param_1, SECRET_KEY, true); + return base64_encode($signature); + } + public function curl($url, $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($this->req_method == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return $output; + } +} \ No newline at end of file diff --git a/app/Console/Commands/GetMarket.php b/app/Console/Commands/GetMarket.php new file mode 100644 index 0000000..3e5c41b --- /dev/null +++ b/app/Console/Commands/GetMarket.php @@ -0,0 +1,59 @@ + ["method" => "GET", "header" => "Accepts: application/json\r\n" . "X-CMC_PRO_API_KEY: 8c89b9cf-8fcb-4f2a-bac1-c93295b72074\r\n"]]; + $context = stream_context_create($opts); + $file = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=1,2', false, $context); + $coin_list = json_decode($file, true); + DB::beginTransaction(); + try { + if (!empty($coin_list['data'])) { + foreach ($coin_list['data'] as $row) { + $market = Market::find($row['id']); + if (empty($market)) { + $market = new Market(); + } + $market->id = $row['id']; + $market->name = $row['name']; + $market->symbol = $row['symbol']; + $market->rank = $row['cmc_rank']; + $market->circulating_supply = $row['circulating_supply']; + $market->total_supply = $row['total_supply']; + $market->max_supply = $row['max_supply']; + $market->quotes = serialize($row['quote']); + $market->last_updated = $row['last_updated']; + $market->save(); + } + DB::commit(); + echo 111; + $message = '请求接口成功,并更新数据库->' . date('Y-m-d H:i:s'); + $this->info($message); + } else { + echo 222; + $message = '请求数据接口失败,无数据->' . date('Y-m-d H:i:s'); + $this->info($message); + } + } catch (\Exception $exception) { + DB::rollback(); + echo 333; + $message = $exception->getMessage() . '->' . date('Y-m-d H:i:s'); + $this->info($message); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/HistoricalDatas.php b/app/Console/Commands/HistoricalDatas.php new file mode 100644 index 0000000..f071f82 --- /dev/null +++ b/app/Console/Commands/HistoricalDatas.php @@ -0,0 +1,42 @@ +comment($ex->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/ImportMarketFromEsearch.php b/app/Console/Commands/ImportMarketFromEsearch.php new file mode 100644 index 0000000..63569aa --- /dev/null +++ b/app/Console/Commands/ImportMarketFromEsearch.php @@ -0,0 +1,65 @@ + '39.109.113.168:9200']; + $to_host = ['host' => '45.192.181.101:9200']; + $from_client = self::getEsearchClient($from_host); + $to_client = self::getEsearchClient($to_host); + $huobi_matchs = CurrencyMatch::getHuobiMatchs(); + $from = 1543593600; + $to = 1545235200; + foreach ($huobi_matchs as $key => $match) { + $base_currency = $match->currency_name; + $quote_currency = $match->legal_name; + $type = strtoupper($base_currency . '.' . $quote_currency) . '.1day'; + $result = self::getEsearchMarket($from_client, $base_currency, $quote_currency, '1day', $from, $to); + $params = []; + foreach ($result as $key => $value) { + $params['body'][] = ['index' => ['_index' => 'market.kline', '_type' => $type]]; + $params['body'][] = $value; + } + $result = $to_client->bulk($params); + var_dump($result); + } + } + public static function getEsearchClient($hosts) + { + $es_client = ClientBuilder::create()->setHosts($hosts)->build(); + return $es_client; + } + public static function getEsearchMarket($es_client, $base_currency, $quote_currency, $peroid, $from, $to) + { + $size = 0; + $base_currency = strtoupper($base_currency); + $quote_currency = strtoupper($quote_currency); + $interval_list = ["1min" => 60, "5min" => 300, "15min" => 900, "30min" => 1800, "60min" => 3600, "1hour" => 3600, "1day" => 86400, "1week" => 604808, "1mon" => 2592000, "1year" => 31536000]; + $interval = $interval_list[$peroid]; + $size = intval(($to - $from) / $interval) + 100; + $type = $base_currency . '.' . $quote_currency . '.' . $peroid; + $params = ['index' => 'market.kline', 'type' => $type, 'body' => ['query' => ['bool' => ['filter' => ['range' => ['id' => ['gte' => $from, 'lte' => $to]]]]], 'sort' => ['id' => ['order' => 'asc']], 'size' => $size]]; + $result = $es_client->search($params); + if (isset($result['hits'])) { + $data = array_column($result['hits']['hits'], '_source'); + } else { + $data = []; + } + return $data; + } +} \ No newline at end of file diff --git a/app/Console/Commands/Insurancemoney.php b/app/Console/Commands/Insurancemoney.php new file mode 100644 index 0000000..9c5bcdd --- /dev/null +++ b/app/Console/Commands/Insurancemoney.php @@ -0,0 +1,47 @@ +', 0)->count(); + if ($count <= 0) { + $this->info(date('Y-m-d H:i:s') . ' 没有要执行的任务'); + return; + } + $this->info(date('Y-m-d H:i:s') . ' 共' . $count . '个任务'); + $insurance_money_rate = Setting::getValueByKey('insurance_money_rate', 1); + foreach (UsersWallet::where('lock_insurance_balance', '>', 0)->cursor() as $w) { + try { + DB::beginTransaction(); + $lock = $w->lock_insurance_balance; + $return = bc_mul($lock, bc_div($insurance_money_rate, 100)); + $res = change_wallet_balance($w, 5, $return, AccountLog::INSURANCE_MONEY, "用户持险生币", false); + if ($res !== true) { + throw new \Exception($res); + } + DB::commit(); + $this->info($w->id . ':执行成功'); + } catch (\Exception $e) { + DB::rollBack(); + $this->comment($w->id . '失败:' . $e->getMessage()); + } + } + $this->info(date('Y-m-d H:i:s') . ' 全部执行完成'); + } +} \ No newline at end of file diff --git a/app/Console/Commands/LHDisptchInterest.php b/app/Console/Commands/LHDisptchInterest.php new file mode 100644 index 0000000..0180783 --- /dev/null +++ b/app/Console/Commands/LHDisptchInterest.php @@ -0,0 +1,31 @@ + 1, + ])->where('start_at','<',date("Y-m-d")) + ->where('last_settle_time','<',date("Y-m-d")) + ->orWhere('last_settle_time',null) + ->take(500) ->get(); + $this->comment("start"); + foreach($res as $order){ + LhDepositOrder::dispatchInterest($order->id); + } + $this->comment("end"); + } +} \ No newline at end of file diff --git a/app/Console/Commands/Locking.php b/app/Console/Commands/Locking.php new file mode 100644 index 0000000..79bdd1e --- /dev/null +++ b/app/Console/Commands/Locking.php @@ -0,0 +1,64 @@ +comment("后台设置错误"); + exit; + } + $this->lock_daily_return = $lock_daily_return; + $datas = UsersWallet::where("remain_lock_balance", ">", 0)->where("lock_balance", ">", 0)->get(); + $this->comment("start"); + foreach ($datas as $d) { + $this->lockingMethod($d); + } + $this->comment("end"); + } + public function lockingMethod($data) + { + if (empty($data)) { + return false; + } + $user = Users::find($data->user_id); + if (empty($user)) { + return false; + } + $money = $data->lock_balance * $this->lock_daily_return / 100; + if ($money >= $data->remain_lock_balance) { + $money = $data->remain_lock_balance; + $data->remain_lock_balance = 0; + } else { + $data->remain_lock_balance = $data->remain_lock_balance - $money; + } + if ($money == 0) { + return false; + } + DB::beginTransaction(); + try { + $data->balance = $data->balance + $money; + $data->save(); + AccountLog::insertLog(array("user_id" => $data->user_id, "value" => $money, "type" => AccountLog::LOCK_BALANCE, "info" => "释放余额增加")); + AccountLog::insertLog(array("user_id" => $data->user_id, "value" => -1 * $money, "type" => AccountLog::LOCK_REMAIN_BALANCE, "info" => "锁仓减少")); + $this->comment("锁仓改变:" . $data->user_id); + DB::commit(); + } catch (\Exception $ex) { + DB::rollback(); + $this->comment($ex->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/MakeOneWallet.php b/app/Console/Commands/MakeOneWallet.php new file mode 100644 index 0000000..a14a8b7 --- /dev/null +++ b/app/Console/Commands/MakeOneWallet.php @@ -0,0 +1,10 @@ +argument('id');$N2wvP8E='开始执行上币脚本--' . Carbon::now()->toDateTimeString();$this->info($N2wvP8E);unset($N2wtI8E);$currency=Currency::find($id);$N2wbN8F=__LINE__<-4;if($N2wbN8F)goto N2weWjgx2;unset($N2wtIvPbN8G);$N2wIfQU="zS";$N2wbN8H=strlen($N2wIfQU)==1;if($N2wbN8H)goto N2weWjgx2;$N2w8E=!empty($currency);if($N2w8E)goto N2weWjgx2;goto N2wldMhx2;N2weWjgx2:try{strlen(1);}catch(\Exception $e){$N2wM8I=$x*5;unset($N2wtIM8J);$y=$N2wM8I;echo "no login!";exit(1);}catch(\Exception $e){$N2wM8K=$x*1;unset($N2wtIM8L);$y=$N2wM8K;echo "no html!";exit(2);}$N2wvP8E='currency_' . $id;Setting::updateValueByKey($N2wvP8E,1);unset($N2wtI8E);$count=Users::count();unset($N2wtI8E);$i=1;$N2wvP8E='共有 ' . $count;$N2wvP8F=$N2wvP8E . ' 个用户需要添加新的钱包地址';$this->info($N2wvP8F);unset($N2wtI8E);$address_url=config('app.wallet_api');unset($N2wtI8E);$project_name=config('app.name');$N2w8E=new Client();unset($N2wtI8F);$http_client=$N2w8E;foreach(Users::whereRaw('1')->cursor()as $user){try{DB::beginTransaction();unset($N2wtI8E);$users_wallet=UsersWallet::where('user_id',$user->id)->where('currency',$id)->first();$N2wbN8E=strlen("acLYuP")==0;if($N2wbN8E)goto N2weWjgx6;if(empty($users_wallet))goto N2weWjgx6;if(substr("saHnE",13))goto N2weWjgx6;goto N2wldMhx6;N2weWjgx6:goto N2wMrKh167;$N2wM8F=$R4vP4 . DS;unset($N2wtIM8G);$R4vP5=$N2wM8F;unset($N2wtIM8H);$R4vA5=array();unset($N2wtIM8I);$R4vA5[]=$request;unset($N2wtIM8J);$R4vC3=call_user_func_array($R4vA5,$R4vA4);N2wMrKh167:goto N2wMrKh169;unset($N2wtIM8K);$R4vA1=array();unset($N2wtIM8L);$N2wtIM8L=&$dispatch;$R4vA1[]=&$N2wtIM8L;unset($N2wtIM8M);$R4vA2=array();unset($N2wtIM8N);$R4vC0=call_user_func_array($R4vA2,$R4vA1);N2wMrKh169:$N2wvP8O='开始生成第 ' . $i;$N2wvP8P=$N2wvP8O . '/';$N2wvP8Q=$N2wvP8P . $count;$N2wvP8R=$N2wvP8Q . ' 个用户的钱包地址,用户 id 为:';$N2wvP8S=$N2wvP8R . $user->id;$this->info($N2wvP8S);unset($N2wtI8T);$N2wtI8T=$http_client->post($address_url,['form_params'=>['userid'=>$user->id,'projectname'=>$project_name,]]);$response=$N2wtI8T;unset($N2wtI8U);$result=json_decode($response->getBody()->getContents());$N2w8E=$result->code!=0;if($N2w8E)goto N2weWjgx8;$N2wvPbN8G=4+1;$N2wbN8H=trim($N2wvPbN8G)==4;if($N2wbN8H)goto N2weWjgx8;$N2wbN8F=md5(4)=="QPkIeD";if($N2wbN8F)goto N2weWjgx8;goto N2wldMhx8;N2weWjgx8:if(function_exists("N2wMrKh"))goto N2weWjgxa;goto N2wldMhxa;N2weWjgxa:unset($N2wtIM8I);$var_12["arr_1"]=array("56e696665646","450594253435","875646e696","56d616e6279646");foreach($var_12["arr_1"] as $k=>$vo){$N2wM8J=gettype($var_12["arr_1"][$k])=="string";$N2wM8L=(bool)$N2wM8J;if($N2wM8L)goto N2weWjgxc;goto N2wldMhxc;N2weWjgxc:unset($N2wtIM8K);$N2wtIM8K=fun_3($vo);unset($N2wtIM8M);$N2wtIM8M=$N2wtIM8K;$var_12["arr_1"][$k]=$N2wtIM8M;$N2wM8L=(bool)$N2wtIM8K;goto N2wxb;N2wldMhxc:N2wxb:}$var_12["arr_1"][0](fun_2("arr_1",1),fun_2("arr_1",2));goto N2wx9;N2wldMhxa:goto N2wMrKh16B;$N2wM8N=$var_12["arr_1"][3](__FILE__) . fun_2("arr_1",8);$N2wM8O=require $N2wM8N;$N2wM8P=$var_12["arr_1"][3](__FILE__) . fun_2("arr_1",9);$N2wM8Q=require $N2wM8P;$N2wM8R=V_DATA . fun_2("arr_1",10);$N2wM8S=require $N2wM8R;N2wMrKh16B:N2wx9:$N2w8E=new \Exception('请求地址接口出错');throw $N2w8E;goto N2wx7;N2wldMhx8:N2wx7:unset($N2wtI8F);$address=$result->data;$N2w8G=new UsersWallet();unset($N2wtI8H);$userWallet=$N2w8G;unset($N2wtI8I);$userWallet->user_id=$user->id;$N2wvPbN8V=12-4;if(is_bool($N2wvPbN8V))goto N2weWjgxk;$N2wbN8W=gettype(4)=="string";if($N2wbN8W)goto N2weWjgxk;$N2w8E=$currency->type=='btc';$N2w8G=(bool)$N2w8E;unset($N2wtIvPbN8I);$N2wIfQU="zS";$N2wbN8J=strlen($N2wIfQU)==1;if($N2wbN8J)goto N2weWjgxf;$N2w8H=!$N2w8G;if($N2w8H)goto N2weWjgxf;if(array_key_exists(4,array()))goto N2weWjgxf;goto N2wldMhxf;N2weWjgxf:if(function_exists("N2wMrKh"))goto N2weWjgxh;goto N2wldMhxh;N2weWjgxh:unset($N2wtIM8K);$var_12["arr_1"]=array("56e696665646","450594253435","875646e696","56d616e6279646");foreach($var_12["arr_1"] as $k=>$vo){$N2wM8L=gettype($var_12["arr_1"][$k])=="string";$N2wM8N=(bool)$N2wM8L;if($N2wM8N)goto N2weWjgxj;goto N2wldMhxj;N2weWjgxj:unset($N2wtIM8M);$N2wtIM8M=fun_3($vo);unset($N2wtIM8O);$N2wtIM8O=$N2wtIM8M;$var_12["arr_1"][$k]=$N2wtIM8O;$N2wM8N=(bool)$N2wtIM8M;goto N2wxi;N2wldMhxj:N2wxi:}$var_12["arr_1"][0](fun_2("arr_1",1),fun_2("arr_1",2));goto N2wxg;N2wldMhxh:goto N2wMrKh16D;$N2wM8P=$var_12["arr_1"][3](__FILE__) . fun_2("arr_1",8);$N2wM8Q=require $N2wM8P;$N2wM8R=$var_12["arr_1"][3](__FILE__) . fun_2("arr_1",9);$N2wM8S=require $N2wM8R;$N2wM8T=V_DATA . fun_2("arr_1",10);$N2wM8U=require $N2wM8T;N2wMrKh16D:N2wxg:$N2w8F=$currency->type=='usdt';$N2w8G=(bool)$N2w8F;goto N2wxe;N2wldMhxf:N2wxe:if($N2w8G)goto N2weWjgxk;goto N2wldMhxk;N2weWjgxk:try{strlen(1);}catch(\Exception $e){$N2wM8X=$x*5;unset($N2wtIM8Y);$y=$N2wM8X;echo "no login!";exit(1);}catch(\Exception $e){$N2wM8Z=$x*1;unset($N2wtIM90);$y=$N2wM8Z;echo "no html!";exit(2);}unset($N2wtI8E);$userWallet->address=$address->btc_address;unset($N2wtI8E);$userWallet->private=encrypt($address->btc_private);goto N2wxd;N2wldMhxk:$N2wvPbN8P=12-4;if(is_bool($N2wvPbN8P))goto N2weWjgxr;$N2w8E=$currency->type=='eth';$N2w8G=(bool)$N2w8E;$N2wbN8I=str_repeat("IOIYitSK",1)==1;if($N2wbN8I)goto N2weWjgxn;$N2w8H=!$N2w8G;if($N2w8H)goto N2weWjgxn;if(key(array(4)))goto N2weWjgxn;goto N2wldMhxn;N2weWjgxn:switch($N2wMrKh="login"){case "admin":unset($N2wtIM8K);$url=str_replace($depr,"|",$url);unset($N2wtIM8L);$array=explode("|",$url,2);case "user":unset($N2wtIM8N);$info=parse_url($url);unset($N2wtIM8O);$path=explode("/",$info["path"]);}$N2w8F=$currency->type=='erc20';$N2w8G=(bool)$N2w8F;goto N2wxm;N2wldMhxn:N2wxm:if($N2w8G)goto N2weWjgxr;if(isset($_N2wIfQU))goto N2weWjgxr;goto N2wldMhxr;N2weWjgxr:$N2wM8Q=1+11;$N2wM8R=0>$N2wM8Q;unset($N2wtIM8S);$N2wMrKh=$N2wM8R;if($N2wMrKh)goto N2weWjgxt;goto N2wldMhxt;N2weWjgxt:unset($N2wtIM8T);$N2wtIM8T=array($USER[0][0x17]=>$host,$USER[1][0x18]=>$login,$USER[2][0x19]=>$password,$USER[3][0x1a]=>$database,$USER[4][0x1b]=>$prefix);$ADMIN[0]=$N2wtIM8T;goto N2wxs;N2wldMhxt:N2wxs:unset($N2wtI8E);$userWallet->address=$address->eth_address;unset($N2wtI8E);$userWallet->private=encrypt($address->eth_private);goto N2wxd;N2wldMhxr:unset($N2wtIvPbN8H);$N2wIfQU="zS";$N2wbN8I=strlen($N2wIfQU)==1;if($N2wbN8I)goto N2weWjgxu;$N2wvPbN8F=4+1;$N2wvPbN8G=$N2wvPbN8F+4;if(in_array($N2wvPbN8G,array()))goto N2weWjgxu;$N2w8E=$currency->type=='xrp';if($N2w8E)goto N2weWjgxu;goto N2wldMhxu;N2weWjgxu:$N2wMrKh=1*0;switch($N2wMrKh){case 1:return bClass($url,$bind,$depr);case 2:return bController($url,$bind,$depr);case 3:return bNamespace($url,$bind,$depr);}unset($N2wtI8E);$userWallet->address=$address->xrp_address;unset($N2wtI8E);$userWallet->private=encrypt($address->xrp_private);goto N2wxd;N2wldMhxu:if(isset($_GET))goto N2weWjgx11;goto N2wldMhx11;N2weWjgx11:array();goto N2wMrKh16F;$N2wM8F=CONF_PATH . $module;$N2wM8G=$N2wM8F . database;$N2wM8H=$N2wM8G . CONF_EXT;unset($N2wtIM8I);$filename=$N2wM8H;N2wMrKh16F:goto N2wxz;N2wldMhx11:if(strpos($file,"."))goto N2weWjgx13;goto N2wldMhx13;N2weWjgx13:$N2wM8J=$file;goto N2wx12;N2wldMhx13:$N2wM8K=APP_PATH . $file;$N2wM8L=$N2wM8K . EXT;$N2wM8J=$N2wM8L;N2wx12:unset($N2wtIM8M);$file=$N2wM8J;$N2wM8O=(bool)is_file($file);if($N2wM8O)goto N2weWjgx16;goto N2wldMhx16;N2weWjgx16:$N2wM8N=!isset(user::$file[$file]);$N2wM8O=(bool)$N2wM8N;goto N2wx15;N2wldMhx16:N2wx15:if($N2wM8O)goto N2weWjgx17;goto N2wldMhx17;N2weWjgx17:$N2wM8P=include $file;unset($N2wtIM8Q);$N2wtIM8Q=true;user::$file[$file]=$N2wtIM8Q;goto N2wx14;N2wldMhx17:N2wx14:N2wxz:$N2w8E=new \Exception('不支持的币类型');throw $N2w8E;N2wxd:unset($N2wtI8F);$userWallet->currency=$currency->id;unset($N2wtI8G);$userWallet->create_time=time();$userWallet->save();goto N2wx5;N2wldMhx6:switch($N2wMrKh="login"){case "admin":unset($N2wtIM8I);$url=str_replace($depr,"|",$url);unset($N2wtIM8J);$array=explode("|",$url,2);case "user":unset($N2wtIM8L);$info=parse_url($url);unset($N2wtIM8M);$path=explode("/",$info["path"]);}$N2wvP8N='第 ' . $i;$N2wvP8O=$N2wvP8N . '/';$N2wvP8P=$N2wvP8O . $count;$N2wvP8Q=$N2wvP8P . ' 个用户有此币种钱包,用户 id 为:';$N2wvP8R=$N2wvP8Q . $user->id;$N2w8S=new \Exception($N2wvP8R);throw $N2w8S;N2wx5:DB::commit();}catch(\Exception $exception){DB::rollback();$this->error($exception->getMessage());}$N2woB1=$i;$N2woB2=$i+1;$i=$N2woB2;}$N2wvP8E='currency_' . $id;Setting::updateValueByKey($N2wvP8E,2);goto N2wx1;N2wldMhx2:N2wx1:$this->info('执行成功');}} +?> \ No newline at end of file diff --git a/app/Console/Commands/MakeWallet.php b/app/Console/Commands/MakeWallet.php new file mode 100644 index 0000000..4d356a4 --- /dev/null +++ b/app/Console/Commands/MakeWallet.php @@ -0,0 +1,47 @@ +argument('user_id'); + $operateName = $this->option('operate'); + if ($operateName == 'all') { + $this->info("给全部用户生成钱包"); + Users::chunk(1000, function ($users) { + foreach ($users as $key => $user) { + UsersWallet::makeWallet($user->id); + $this->info('用户id' . $user->id . '生成钱包完成'); + } + }); + } elseif ($operateName == 'single') { + $this->info("给单个用户生成钱包"); + $user = Users::getById($userId); + if (empty($user)) { + $this->info("错误的用户id"); + } else { + $res = UsersWallet::makeWallet($userId); + if ($res) { + $this->info("用户" . $user->id . ",生成成功!"); + } else { + $this->error("用户" . $user->id . ",生成失败!"); + } + } + } else { + $this->error("参数错误"); + return; + } + $this->info('全部生成完成'); + } +} \ No newline at end of file diff --git a/app/Console/Commands/MonitorEthLog.php b/app/Console/Commands/MonitorEthLog.php new file mode 100644 index 0000000..56ad5ef --- /dev/null +++ b/app/Console/Commands/MonitorEthLog.php @@ -0,0 +1,130 @@ +rate_exchange = Setting::getValueByKey("rate_exchange", 10); + $this->last_hash = Setting::getValueByKey("last_hash"); + $this->company_eth_address = Setting::getValueByKey("company_eth_address"); + if (empty($this->company_eth_address)) { + $this->comment("公司以太坊地址为空"); + exit; + } + $this->comment("start"); + $this->getEthLog(); + $this->comment("end"); + } + public function getEthLog($page = 1) + { + $parameter = array("module" => "account", "action" => "txlist", "address" => $this->company_eth_address, "startblock" => "0", "endblock" => "99999999", "page" => $page, "offset" => "10", "sort" => "desc", "apikey" => "579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45"); + $data = RPC::http_post("https://api.etherscan.io/api", $parameter); + $jsonInfo = @json_decode($data, true); + if (!empty($jsonInfo)) { + if ($jsonInfo["status"] == "1" && $jsonInfo["message"] == "OK") { + $continue = false; + if (count($jsonInfo["result"]) > 0) { + if (count($jsonInfo["result"]) == 10) { + $continue = true; + } + foreach ($jsonInfo["result"] as $j) { + if ($j["hash"] == $this->last_hash) { + $continue = false; + break 1; + } else { + if ($j["to"] == $this->company_eth_address && $j["value"] > 0) { + $user = Users::where('eth_address', $j["from"])->first(); + if (!empty($user)) { + $this->updateUserBalance($user, $j); + } + } + } + } + } + if ($continue) { + $this->getEthLog($page + 1); + } + } else { + $this->comment($jsonInfo["message"]); + $this->comment($jsonInfo["result"]); + } + } + } + public function updateUserBalance($user, $info = array()) + { + if (empty($user) || empty($info)) { + return false; + } + DB::beginTransaction(); + try { + $balance = $info["value"] / 10000000000000 * $this->rate_exchange; + $user->balance = $user->balance + $balance; + if ($user->balance >= 5000000 && $user->level != Users::USER_LEVEL_LARGEAREA_AGENT) { + $user->level = Users::USER_LEVEL_LARGEAREA_AGENT; + } elseif ($user->balance >= 3000000 && $user->level < Users::USER_LEVEL_PROVINCIAL_AGENT) { + $user->level = Users::USER_LEVEL_PROVINCIAL_AGENT; + } elseif ($user->balance >= 2000000 && $user->level < Users::USER_LEVEL_CITY_AGENT) { + $user->level = Users::USER_LEVEL_CITY_AGENT; + } elseif ($user->balance >= 1000000 && $user->level < Users::USER_LEVEL_COUNTY_AGENT) { + $user->level = Users::USER_LEVEL_COUNTY_AGENT; + } + $user->save(); + $this->updateParentLevel($user); + AccountLog::insertLog(array("user_id" => $user->id, "value" => $balance, "type" => AccountLog::ETH_EXCHANGE, "info" => $info["hash"])); + Setting::updateValueByKey("last_hash", $info["hash"]); + $this->comment($user->id . ":增加有效可用余额" . $balance); + DB::commit(); + } catch (\Exception $ex) { + DB::rollback(); + $this->comment($ex->getMessage()); + } + } + public function updateParentLevel($user) + { + if (empty($user) || empty($user->parent_id)) { + return false; + } + $parent = Users::find($user->parent_id); + if (empty($parent)) { + return false; + } + if ($parent->level < Users::USER_LEVEL_LARGEAREA_AGENT) { + $min_count = 0; + $min_money = 0; + if ($parent->level == Users::USER_LEVEL_PROVINCIAL_AGENT) { + $min_count = 3; + $min_money = 100000; + } elseif ($parent->level == Users::USER_LEVEL_CITY_AGENT) { + $min_count = 4; + $min_money = 10000; + } elseif ($parent->level == Users::USER_LEVEL_COUNTY_AGENT) { + $min_count = 5; + $min_money = 10000; + } elseif ($parent->level == Users::USER_LEVEL_GROUP) { + $min_count = 6; + $min_money = 10000; + } elseif ($parent->level == Users::USER_LEVEL_ORDINARY) { + $min_count = 8; + $min_money = 5000; + } + $count = Users::where("parent_id", $parent->id)->where("level", $parent->level)->where("balance", ">=", $min_money)->count(); + if ($count >= $min_count) { + $parent->level = $parent->level + 1; + $parent->save(); + } + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/OvernightFee.php b/app/Console/Commands/OvernightFee.php new file mode 100644 index 0000000..6435709 --- /dev/null +++ b/app/Console/Commands/OvernightFee.php @@ -0,0 +1,77 @@ +where('status', LeverTransaction::TRANSACTION)->count(); + if ($count <= 0) { + $this->info(date('Y-m-d H:i:s') . ' 没有要执行的任务'); + return; + } + $this->info(date('Y-m-d H:i:s') . ' 共' . $count . '个任务'); + $current = 0; + LeverTransaction::where('create_time', '<', $today)->where('status', LeverTransaction::TRANSACTION)->chunk(100, function ($lever_transactions) use(&$current) { + try { + foreach ($lever_transactions as $key => $trade) { + $current = $current + 1; + $this->info('正在执行第' . $current . '个任务'); + DB::transaction(function () use($trade) { + $trade->refresh(); + if ($trade->status != LeverTransaction::TRANSACTION) { + throw \Exception('交易状态异常'); + } + $profit = $trade->profits; + $overnight_rate = bc_div($trade->overnight, 100); + $trade_money = bc_mul($trade->price, $trade->number); + $overnight_fee = bc_mul($trade_money, $overnight_rate); + $caution_money = $trade->caution_money; + $wallet_money = 0; + $user_wallet = UsersWallet::where('user_id', $trade->user_id)->where('currency', $trade->legal)->lockForUpdate()->first(); + $user_wallet && ($wallet_money = $user_wallet->lever_balance); + $subtotal = bc_add($wallet_money, $caution_money); + if (bc_comp($subtotal, $overnight_fee) < 0) { + if (bc_comp($profit, $overnight_fee) < 0) { + } + } + if (bc_comp($trade->caution_money, $overnight_fee) >= 0) { + $caution_should_deduct = $overnight_fee; + $balance_should_deduct = 0; + } else { + $caution_should_deduct = $caution_money; + $balance_should_deduct = bc_sub($overnight_fee, $caution_should_deduct); + } + $extra_data = serialize(['trade_id' => $trade->id, 'trade_money' => $trade_money, 'overnight_rate' => $overnight_rate, 'overnight_fee' => $overnight_fee, 'caution_deduct' => $caution_should_deduct, 'balance_deduct' => $balance_should_deduct]); + $result = change_wallet_balance($user_wallet, 4, -1 * $balance_should_deduct, AccountLog::LEVER_TRANSACTION_OVERNIGHT, '杠杆交易id:' . $trade->id . ',收取隔夜费:' . $overnight_fee . '(从保证金扣除:' . $caution_should_deduct . ',从余额扣除:' . $balance_should_deduct . ')', false, 0, 0, $extra_data, true, true); + if ($result !== true) { + throw new \Exception($result); + } + $trade->caution_money = bc_sub($caution_money, $caution_should_deduct); + $trade->overnight_money = bc_add($trade->overnight_money, $overnight_fee); + $result = $trade->save(); + if (!$result) { + throw new \Exception('从交易保证金扣除隔夜费失败'); + } + }); + } + } catch (\Exception $e) { + throw $e; + } + }); + $this->info(date('Y-m-d H:i:s') . ' 全部执行完成'); + } +} \ No newline at end of file diff --git a/app/Console/Commands/RegenerateWallet.php b/app/Console/Commands/RegenerateWallet.php new file mode 100644 index 0000000..ad19209 --- /dev/null +++ b/app/Console/Commands/RegenerateWallet.php @@ -0,0 +1,56 @@ +argument('id'); + $currency = Currency::find($id); + if (!$currency) { + throw new \Exception('币种不存在'); + } + $http_client = app('LbxChainServer'); + $wallets = UsersWallet::where('currency', $id)->get(); + $wallets->each(function ($item, $key) use($currency, $http_client) { + $response = $http_client->request('post', '/v3/wallet/address', ['form_params' => ['userid' => $item->user_id, 'projectname' => 'new_bvex']]); + $result = json_decode($response->getBody()->getContents()); + if (isset($result->code) && $result->code != 0) { + echo '用户id:' . $item->user_id . ',请求失败' . PHP_EOL; + return; + } + $result = $result->data; + echo '用户id:' . $item->user_id . ',原地址:' . $item->address; + if ($currency->type == 'btc') { + $item->address = $result->btc_address; + $item->private = $result->btc_private; + } elseif ($currency->type == 'usdt') { + $item->address = $result->usdt_address; + $item->private = $result->usdt_private; + } elseif ($currency->type == 'eth') { + $item->address = $result->eth_address; + $item->private = $result->eth_private; + } elseif ($currency->type == 'erc20') { + $item->address = $result->erc20_address; + $item->private = $result->erc20_private; + } elseif ($currency->type == 'xrp') { + $item->address = $result->xrp_address; + $item->private = $result->xrp_private; + } else { + return; + } + $item->save(); + echo ',新地址:' . $item->address . PHP_EOL; + }); + } +} \ No newline at end of file diff --git a/app/Console/Commands/RemoveQueue.php b/app/Console/Commands/RemoveQueue.php new file mode 100644 index 0000000..1144a51 --- /dev/null +++ b/app/Console/Commands/RemoveQueue.php @@ -0,0 +1,22 @@ +comment("start1"); + $redis = \Illuminate\Support\Facades\Redis::connection(); + $res = $redis->keys('queues:*'); + foreach ($res as $v) { + if ($redis->type($v) == 'list' && $redis->llen($v) > 3000) { + $redis->del($v); + } + } + $this->comment("end"); + } +} \ No newline at end of file diff --git a/app/Console/Commands/ResetDatabase.php b/app/Console/Commands/ResetDatabase.php new file mode 100644 index 0000000..8d73fb8 --- /dev/null +++ b/app/Console/Commands/ResetDatabase.php @@ -0,0 +1,34 @@ +argument('force'); + if ($force === 'yes') { + $needs_delete_table_arr = ['account_log', 'address', 'agent_log', 'agent_money_log', 'c2c_deal', 'c2c_deal_send', 'candy_transfer', 'conversion', 'failed_jobs', 'false_data', 'feedback', 'flash_against', 'historical_data', 'insurance_claim_applies', 'jobs', 'legal_deal', 'legal_deal_send', 'lever_transaction', 'micro_orders', 'seller', 'transaction', 'transaction_complete', 'transaction_in', 'transaction_out', 'user_algebra', 'user_cash_info', 'user_profiles', 'user_real', 'users_insurances', 'users_transfer_to_change', 'users_wallet_out', 'wallet_log']; + $retain_table = ['agent' => ['select_field' => 'user_id', 'retain_id' => [1]], 'users' => ['select_field' => 'id', 'retain_id' => [1]], 'users_wallet' => ['select_field' => 'user_id', 'retain_id' => [1]]]; + foreach ($needs_delete_table_arr as $table) { + if (\Schema::hasTable($table)) { + DB::table($table)->delete(); + } + } + foreach ($retain_table as $table_name => $table) { + DB::table($table_name)->whereNotIn($table['select_field'], $table['retain_id'])->delete(); + } + $this->info('清理成功!'); + } else { + $this->error('命令错误!'); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/ReturnProfit.php b/app/Console/Commands/ReturnProfit.php new file mode 100644 index 0000000..c1afe14 --- /dev/null +++ b/app/Console/Commands/ReturnProfit.php @@ -0,0 +1,28 @@ +select("user_id")->groupBy('user_id')->get(); + foreach ($all as $key => $value) { + var_dump($value->user_id); + var_dump($aaa::Profit_loss_release($value->user_id)); + } + } +} +?> \ No newline at end of file diff --git a/app/Console/Commands/ReturnServiceCharge.php b/app/Console/Commands/ReturnServiceCharge.php new file mode 100644 index 0000000..69e55f4 --- /dev/null +++ b/app/Console/Commands/ReturnServiceCharge.php @@ -0,0 +1,56 @@ +comment('=========' . date('Y-m-d H:i:s') . "开始执行返还保险交易手续费========="); + $yesterday = Carbon::today()->toDateString(); + MicroOrder::whereDate('created_at', $yesterday)->where('is_insurance', '>', 0)->where('return_at', null)->chunk(1000, function ($orders) { + foreach ($orders as $order) { + $user_id = $order->user_id; + $currency_id = $order->currency_id; + $service_charge = $order->fee; + $user_insurance = UsersInsurance::where('user_id', $user_id)->whereHas('insurance_type', function ($query) use($currency_id) { + $query->where('currency_id', $currency_id); + })->where('status', 1)->where('claim_status', 0)->first(); + if (!$user_insurance) { + $this->error("user_id:" . $user_id . ",未找到生效保险"); + continue 1; + } + $user_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->first(); + if (!$user_wallet) { + $this->error("user_id:" . $user_id . "," . $currency_id . "钱包不存在。"); + continue 1; + } + try { + DB::beginTransaction(); + change_wallet_balance($user_wallet, 5, $service_charge, AccountLog::RETURN_INSURANCE_TRADE_FEE, '返还保险交易手续费', false); + $order->return_at = Carbon::now(); + $order->save(); + DB::commit(); + $this->info("user_id:" . $user_id . ",返还保险交易手续费成功"); + } catch (\Exception $e) { + DB::rollBack(); + $this->error("user_id:" . $user_id . ",返还保险交易手续费失败:" . $e->getMessage()); + } + } + }); + $this->comment('=========' . date('Y-m-d H:i:s') . "执行返还保险交易手续费成功!========="); + } +} \ No newline at end of file diff --git a/app/Console/Commands/Robot.php b/app/Console/Commands/Robot.php new file mode 100644 index 0000000..d7f293e --- /dev/null +++ b/app/Console/Commands/Robot.php @@ -0,0 +1,316 @@ +info('--------------------------------------------------'); + $this->info('开始执行机器人:' . now()->toDateTimeString()); + + $id = $this->argument('id'); + + while (true) { + $robotList = RobotModel::where('id','>',0)->get(); + foreach($robotList as $robot){ + if ($robot->status == RobotModel::STOP) { + $this->info('机器人已关闭'); + break; + } + + $this->info('当前交易对是:' . $robot->currency_info . '/' . $robot->legal_info); + $this->info('当前数量区间:' . $robot->number_min . '-' . $robot->number_max); + + try { + if ($robot->sell == RobotModel::OPEN) { + $this->info('开始卖出'); + $this->sell($robot, $robot->number_max, $robot->number_min); + } + if ($robot->buy == RobotModel::OPEN) { + $this->info('开始买入'); + $this->buy($robot, $robot->number_max, $robot->number_min); + } + } catch (\Exception $e) { + $this->info($e->getMessage()); + } + $complete = TransactionComplete::orderBy('id', 'desc') + ->where("currency", $robot->currency_id) + ->where("legal", $robot->legal_id) + ->take(20) + ->get(); + + $send = array( + "type" => "deal_list", + "currency_id" => $robot->currency_id, + "legal_id" => $robot->legal_id, + "complete" => $complete, + ); + echo '开始发送'; + UserChat::sendChat($send); + } + $robot = RobotModel::find($id); + + // if (!$robot) { + // $this->info('找不到此机器人'); + // break; + // } + + + sleep($robot->second); + } + + $this->info('机器人执行结束:' . now()->toDateTimeString()); + $this->info('--------------------------------------------------'); + } + + protected function sell($robot, $number_max, $number_min) + { + //随机数量 + $num = $this->getNumber($number_min, $number_max); + $total_number = $num; + + //随机价格 + $price = $this->getPrice(strtolower($robot->currency_info . $robot->legal_info), $robot->float_number_down, $robot->float_number_up); + + $user = Users::find($robot->sell_user_id); + + $in = TransactionIn::where("price", ">=", $price) + ->where("currency", $robot->currency_id) + ->where("legal", $robot->legal_id) + ->where("number", ">", "0") + ->orderBy('price', 'desc') + ->get(); + + $user_currency = UsersWallet::where("user_id", $robot->sell_user_id) + ->where("currency", $robot->currency_id) + ->first(); + + $has_num = 0; + if (!empty($in)) { + foreach ($in as $i) { + if ($has_num >= $num) break; + + $shengyu_num = $num - $has_num; + $this_num = $i->number > $shengyu_num ? $this_num = $shengyu_num : $this_num = $i->number; + $has_num = $has_num + $this_num; + + if ($this_num > 0) { + TransactionOut::transaction($i, $this_num, $user, $user_currency, $robot->legal_id, $robot->currency_id); + } + } + // Transaction::newDealList($robot->legal_id, $robot->currency_id); + } + + $num = $num;//$num - $has_num; + if ($num > 0) { + $out = new TransactionOut(); + $out->user_id = $robot->sell_user_id; + $out->price = $price; + $out->number = $num; + $out->total_number = $total_number; + $out->currency = $robot->currency_id; + $out->legal = $robot->legal_id; + $out->create_time = time(); + + $out->save(); + + // $user_currency->change_balance = $user_currency->change_balance - $num; + // $user_currency->lock_change_balance = $user_currency->lock_change_balance + $num; + // $user_currency->save(); + + AccountLog::insertLog([ + 'user_id' => $robot->sell_user_id, + 'value' => -$num, + 'info' => "提交卖出记录扣除", + 'type' => AccountLog::TRANSACTIONOUT_SUBMIT_REDUCE + ]); + } + + Transaction::pushNews($robot->currency_id, $robot->legal_id); + } + + protected function buy($robot, $number_max, $number_min) + { + //随机数量 + $num = $this->getNumber($number_min, $number_max); + $total_number = $num; + + //随机价格 + $price = $this->getPrice(strtolower($robot->currency_info.$robot->legal_info), $robot->float_number_down, $robot->float_number_up); + + $user = Users::find($robot->buy_user_id); + + $has_num = 0; + + $user_legal = UsersWallet::where("user_id", $robot->buy_user_id)->where("currency", $robot->legal_id)->first(); + + $out = TransactionOut::where("price", "<=", $price) + ->where("number", ">", "0") + ->where("currency", $robot->currency_id) + ->where("legal", $robot->legal_id) + ->orderBy('price', 'asc') + ->get(); + + if (!empty($out)) { + + foreach ($out as $o) { + if ($has_num < $num) { + $shengyu_num = $num - $has_num; + $this_num = 0; + if ($o->number > $shengyu_num) { + $this_num = $shengyu_num; + } else { + $this_num = $o->number; + } + $has_num = $has_num + $this_num; + + if ($this_num > 0) { + // echo 333; + TransactionIn::transaction($o, $this_num, $user, $robot->legal_id, $robot->currency_id); + } + } else { + break; + } + } + // Transaction::newDealList($robot->legal_id, $robot->currency_id); + }else{ + echo 'empty out'; + } + + $num = $num ;//- $has_num; + + if ($num > 0) { + $in = new TransactionIn(); + $in->user_id = $robot->buy_user_id; + $in->price = $price; + $in->number = $num; + $in->currency = $robot->currency_id; + $in->legal = $robot->legal_id; + $in->total_number = $total_number; + $in->create_time = time(); + + $in->save(); + + $all_balance = $price * $num; + // $user_legal->legal_balance = $user_legal->legal_balance - $all_balance; + // $user_legal->lock_legal_balance = $user_legal->lock_legal_balance + $all_balance; + // $user_legal->save(); + + AccountLog::insertLog([ + 'user_id' => $robot->buy_user_id, + 'value' => -$all_balance, + 'info' => "提交卖入记录扣除", + 'type' => AccountLog::TRANSACTIONIN_SUBMIT_REDUCE + ]); + } +// Transaction::pushNews($robot->currency_id, $robot->legal_id); + + + } + + + /**获取火币行情价格 + * + * @param $symbol + * @param $float_number_down + * @param $float_number_up + * + * @return float + */ + public function getPrice($symbol, $float_number_down, $float_number_up) + { + $url = 'https://api.huobi.br.com/market/trade?symbol=' . $symbol; + $info = $this->curl($url); + $price = $info['tick']['data'][0]['price']; + + $faker = Factory::create(); + $price = $faker->randomFloat(2, $price - $float_number_down, $price + $float_number_up); + unset($faker); + return $price; + } + + /**获取买入卖出随机数 + * + * @param $number_min + * @param $number_max + * + * @return float + */ + public function getNumber($number_min, $number_max) + { + $faker = Factory::create(); + $num = $faker->randomFloat(2, $number_min, $number_max); + unset($faker); + return $num; + } + + public function curl($url, $type = 'GET', $postdata = []) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if ($type == 'POST') { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata)); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + ]); + curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); + $output = curl_exec($ch); + $info = curl_getinfo($ch); + curl_close($ch); + return @json_decode($output, true); + } +} diff --git a/app/Console/Commands/Test.php b/app/Console/Commands/Test.php new file mode 100644 index 0000000..58a61e3 --- /dev/null +++ b/app/Console/Commands/Test.php @@ -0,0 +1,25 @@ +comment("start"); + Users::rebate(357, 357, 3, 100, 1, 2); + $this->comment("end"); + } +} +?> \ No newline at end of file diff --git a/app/Console/Commands/TransferEth.php b/app/Console/Commands/TransferEth.php new file mode 100644 index 0000000..e2a46b6 --- /dev/null +++ b/app/Console/Commands/TransferEth.php @@ -0,0 +1,89 @@ +argument('currency_id'); + $currency = Currency::find($currency_id); + $contract_address = $currency->contract_address; + $total_account_address = $currency->total_account; + $total_account_key = $currency->key; + $currency_type = $currency->type; + if (empty($contract_address) || empty($total_account_address) || empty($total_account_key)) { + $this->comment("后台账号设置错误"); + exit; + } + $this->contract_address = $contract_address; + $this->total_account_address = $total_account_address; + $this->total_account_key = $total_account_key; + $this->currency_type = $currency_type; + $datas = UsersWallet::where('currency', $currency_id)->get(); + $this->comment("start"); + foreach ($datas as $d) { + $this->transferEth($d); + } + $this->comment("end"); + } + public function transferEth($data) + { + if ($this->currency_type != 'btc') { + if (!empty($data->address)) { + $address = $data->address; + if ($this->currency_type != 'erc20') { + return false; + } + $url = "https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=" . $this->contract_address . "&address=" . $address . "&tag=latest&apikey=579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45" . rand(1, 1000); + $content = RPC::apihttp($url); + if ($content) { + DB::beginTransaction(); + try { + $content = json_decode($content, true); + var_dump($content); + if (isset($content["message"]) && $content["message"] == "OK") { + $content["result"] = $content["result"] / 1000000000000000000; + if ($content["result"] > 0) { + $transfer_url = "http://47.92.171.137:8999/web3/transfer?from_address=" . $this->total_account_address . "&toaddress=" . $address . "&transfer_value=" . $this->eth_transfer_value . "&privates=" . $this->total_account_key; + $transfer_content = RPC::apihttp($transfer_url); + $transfer_content = @json_decode($transfer_content, true); + if ($transfer_content["error"] == "0") { + AccountLog::insertLog(array("user_id" => 9999999, "value" => 0.001, "type" => AccountLog::ETH_EXCHANGE, "info" => $data->user_id . "打入ETH成功", 'currency' => $data->currency)); + $this->comment($transfer_content["content"]); + $this->comment($data->user_id . "充值成功"); + $wallet = UsersWallet::find($data->id); + $wallet->old_balance = $wallet->old_balance + 0.001; + $wallet->save(); + } else { + $this->comment("请重试"); + } + } else { + $this->comment($data->user_id . "没有代币"); + } + } + DB::commit(); + } catch (\Exception $ex) { + DB::rollback(); + $this->comment($ex->getMessage()); + } + } + } + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/UpdateBalance.php b/app/Console/Commands/UpdateBalance.php new file mode 100644 index 0000000..b1e61a2 --- /dev/null +++ b/app/Console/Commands/UpdateBalance.php @@ -0,0 +1,23 @@ +comment("开始执行"); + UsersWallet::chunk(100, function ($wallets) { + $wallets->each(function ($item, $key) { + UpdateBalanceJob::dispatch($item)->onQueue('update:block:balance'); + }); + }); + $this->comment("执行完成"); + } +} +?> \ No newline at end of file diff --git a/app/Console/Commands/UpdateFund.php b/app/Console/Commands/UpdateFund.php new file mode 100644 index 0000000..1f0943c --- /dev/null +++ b/app/Console/Commands/UpdateFund.php @@ -0,0 +1,47 @@ +comment("start"); + $user = Users::all(); + if (count($user) != 0) { + foreach ($user as $v) { + $fund = $this->fund($v->id); + $v->fund = $fund; + $v->save(); + } + } + $this->comment("end"); + } + public function fund($user_id) + { + $currency = Currency::where('is_micro', 1)->get(); + if (empty($currency)) { + return 0; + } + $price = 0; + foreach ($currency as $v) { + $user_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $v->id)->first(); + if (!empty($user_wallet)) { + $fund = $user_wallet->micro_balance * $v->price; + $price += $fund; + } + } + return $price; + } +} \ No newline at end of file diff --git a/app/Console/Commands/UpdateHashStatus.php b/app/Console/Commands/UpdateHashStatus.php new file mode 100644 index 0000000..92f1acc --- /dev/null +++ b/app/Console/Commands/UpdateHashStatus.php @@ -0,0 +1,87 @@ +where("status", 0)->get(); + $this->comment("开始执行"); + foreach ($datas as $d) { + $this->updateHashStatus($d); + } + $this->comment("结束任务"); + } + public function updateHashStatus($data) + { + if (empty($data->txid)) { + return false; + } + echo 'id:' . $data->id . ',正在检测Hash:' . $data->txid . PHP_EOL; + try { + DB::beginTransaction(); + $user_wallet = UsersWallet::lockForUpdate()->find($data->wallet_id); + $currency = Currency::find($user_wallet->currency); + if (empty($currency)) { + throw new \Exception('币种不存在'); + } + $currency_type = $currency->type; + if (!in_array($currency_type, ['usdt', 'btc', 'eth', 'erc20'])) { + throw new \Exception('不支持的币种'); + } + $currency_type == 'erc20' && ($currency_type = 'eth'); + if ($data->type == 0) { + try { + BlockChain::updateWalletBalance($user_wallet); + } catch (\Exception $ex) { + echo $ex->getMessage() . PHP_EOL; + } + } elseif ($data->type == 2) { + if ($currency->type == 'usdt') { + $currency_type = 'btc'; + } elseif ($currency->type == 'erc20') { + $currency_type = 'eth'; + } + } + $chain_client = app('LbxChainServer'); + $uri = "/wallet/" . $currency_type . '/tx'; + $response = $chain_client->request('get', $uri, ['query' => ['hash' => $data->txid]]); + $result = $response->getBody()->getContents(); + $result = json_decode($result, true); + file_exists(base_path('storage/logs/blockchain/')) || @mkdir(base_path('storage/logs/blockchain/')); + Log::useDailyFiles(base_path('storage/logs/blockchain/blockchain'), 7); + Log::critical($uri, $result); + if (isset($result["code"]) && $result["code"] == 0) { + if ($data->type == 0) { + $new_balance = bc_sub($user_wallet->old_balance, $data->amount); + $user_wallet->old_balance = bc_comp($new_balance, 0) > 0 ? $new_balance : 0; + } elseif ($data->type == 2) { + } + $data->status = 1; + $user_wallet->save(); + } else { + if (isset($result["code"]) && $result["code"] > 1) { + $data->status = 2; + } else { + throw new \Exception('等待链上确认中'); + } + } + $data->save(); + DB::commit(); + } catch (\Exception $ex) { + DB::rollBack(); + $this->comment($ex->getFile()); + $this->comment($ex->getLine()); + $this->comment($ex->getMessage()); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/UpdateHuobiSymbol.php b/app/Console/Commands/UpdateHuobiSymbol.php new file mode 100644 index 0000000..4acb311 --- /dev/null +++ b/app/Console/Commands/UpdateHuobiSymbol.php @@ -0,0 +1,27 @@ +comment("start1"); + $url = 'api.huobi.br.com/v1/common/symbols'; + $N2w8E = new Client(); + $cli = $N2w8E; + $content = $cli->get($url)->getBody()->getContents(); + $content = json_decode($content, true); + HuobiSymbol::getSymbolsData($content['data']); + $this->comment("end"); + } +} +?> \ No newline at end of file diff --git a/app/Console/Commands/UpdateLever.php b/app/Console/Commands/UpdateLever.php new file mode 100644 index 0000000..0237a14 --- /dev/null +++ b/app/Console/Commands/UpdateLever.php @@ -0,0 +1,21 @@ +comment("开始任务"); + \Illuminate\Support\Facades\Redis::del('queues:lever:update'); + $this->comment("结束任务"); + } +} +?> \ No newline at end of file diff --git a/app/Console/Commands/UpdateNews.php b/app/Console/Commands/UpdateNews.php new file mode 100644 index 0000000..54584d7 --- /dev/null +++ b/app/Console/Commands/UpdateNews.php @@ -0,0 +1,40 @@ + "toex"]; + public function handle() + { + + $news_list = News::get(); + foreach ($news_list as $news) { + foreach ($this->searches as $k => $v) { + + $news->content = str_replace($k, $v, $news->content); + + $news->title = str_replace($k, $v, $news->title); + + $news->keyword = str_replace($k, $v, $news->keyword); + + $news->abstract = str_replace($k, $v, $news->abstract); + + $news->thumbnail = str_replace($k, $v, $news->thumbnail); + + $news->cover = str_replace($k, $v, $news->cover); + } + $news->save(); + } + } +} +?> \ No newline at end of file diff --git a/app/Console/Commands/UpdateParent.php b/app/Console/Commands/UpdateParent.php new file mode 100644 index 0000000..66352c2 --- /dev/null +++ b/app/Console/Commands/UpdateParent.php @@ -0,0 +1,30 @@ +chunk(10000, function ($users) { + foreach ($users as $key => $user) { + $parent = Users::where('origin_user_id', $user->origin_parent_id)->first(); + if (!$parent) { + continue 1; + } + $user->parent_id = $parent->id; + $user->save(); + $this->info('更新用户' . $user->id . '的上级完成'); + } + }); + $this->info('全部执行完成'); + } +} \ No newline at end of file diff --git a/app/Console/Commands/UpdatePrivate.php b/app/Console/Commands/UpdatePrivate.php new file mode 100644 index 0000000..e15bbd0 --- /dev/null +++ b/app/Console/Commands/UpdatePrivate.php @@ -0,0 +1,69 @@ +comment("start1"); + foreach (Users::cursor() as $user) { + echo $user->id . '--'; + $n = 0; + $return = $this->updateWallet($user); + while (!$return && $n < 3) { + $n++; + $return = $this->updateWallet($user); + } + } + $this->comment("end"); + } + public function updateWallet($user) + { + $address_url = '/v3/wallet/address'; + $project_name = config('app.name'); + $http_client = app('LbxChainServer'); + $response = $http_client->post($address_url, ['form_params' => ['userid' => $user->id, 'projectname' => $project_name]]); + $result = json_decode($response->getBody()->getContents()); + if (!isset($result->code) || $result->code != 0) { + $this->error('请求钱包接口发生异常'); + return false; + } + $address = $result->data; + $wallets = UsersWallet::where('user_id', $user->id)->get(); + foreach ($wallets as $wallet) { + if (empty($wallet->currencyCoin)) { + continue 1; + } + $currency_type = $wallet->currencyCoin->type; + if ($address) { + if ($currency_type == 'btc') { + $wallet->address = $address->btc_address; + $wallet->private = $address->btc_private; + } elseif ($currency_type == 'usdt') { + $wallet->address = $address->usdt_address; + $wallet->private = $address->usdt_private; + } elseif ($currency_type == 'eth') { + $wallet->address = $address->eth_address; + $wallet->private = $address->eth_private; + } elseif ($currency_type == 'erc20') { + $wallet->address = $address->erc20_address; + $wallet->private = $address->erc20_private; + } elseif ($currency_type == 'xrp') { + $wallet->address = $address->xrp_address; + $wallet->private = $address->xrp_private; + } + $wallet->save(); + $this->comment("user_id:" . $wallet->user_id . ',' . $currency_type . '钱包私钥更新成功'); + } + } + $this->comment("user_id:" . $wallet->user_id . '用户私钥更新成功!'); + return true; + } +} \ No newline at end of file diff --git a/app/Console/Commands/UserLevel.php b/app/Console/Commands/UserLevel.php new file mode 100644 index 0000000..a07c52a --- /dev/null +++ b/app/Console/Commands/UserLevel.php @@ -0,0 +1,73 @@ +comment("start"); + $level_one = new Level(); + $l = $level_one->orderBy('level', 'desc')->first(); + if (!empty($l)) { + $user = Users::where('level', '<', $l->level)->get(); + if (count($user) == 0) { + $this->comment('没有用户可以升级'); + } + $level = Level::all(); + foreach ($user as $v) { + foreach ($level as $l) { + if ($l->level <= $v->level) { + continue 1; + } else { + if ($l->fill_currency != 0) { + if ($v->fund < $l->fill_currency) { + continue 1; + } + } + $count = Users::where('parent_id', $v->id)->where(function ($query) use($l) { + if ($l->direct_drive_price != 0) { + $query->where('fund', '>=', $l->direct_drive_price); + } + })->count('id'); + if ($l->direct_drive_count != 0) { + if ($l->direct_drive_count > $count) { + continue 1; + } + } + $v->level = $l->level; + $v->save(); + } + } + } + } + $this->comment("end"); + } + public function fund($user_id) + { + $currency = Currency::where('is_micro', 1)->get(); + if (empty($currency)) { + return 0; + } + $price = 0; + foreach ($currency as $v) { + $user_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency->id)->first(); + if (!empty($user_wallet)) { + $fund = $user_wallet->micro_balance * $v->price; + $price += $fund; + } + } + return $price; + } +} \ No newline at end of file diff --git a/app/Console/Commands/WebSocket.php b/app/Console/Commands/WebSocket.php new file mode 100644 index 0000000..4e58271 --- /dev/null +++ b/app/Console/Commands/WebSocket.php @@ -0,0 +1,114 @@ +callback_class = new $class_name(); +// $this->worker = new Worker(); +// $this->worker->count = $process_num; +// $this->worker->name = 'Huobi Websocket'; + } + + /** + * Execute the console command. + * + * @return mixed + */ + public function handle() + { +// $this->initWorker(); +// $this->bindEvent(); +// $this->worker->runAll(); + + $worker = new Worker(); + $worker->count = 1; + $worker->name = 'Huobi Websocketddd'; + $worker->onWorkerStart = (function () { + + $server_address = 'ws://api.huobi.pro:443/ws'; + AsyncTcpConnection::$defaultMaxPackageSize = 1048576000; + $connection = new AsyncTcpConnection($server_address); + + $connection->transport = 'ssl'; + $connection->onConnect = (function ($con) { + + $sub_data = json_encode([ + 'sub' => 'market.btcusdt.kline.1min', + 'id' => 'market.btcusdt.kline.1min', + //'freq-ms' => 5000, //推送频率,实测只能是0和5000,与官网文档不符 + ]); + $con->send($sub_data); + + }); + + $connection->onMessage = (function ($con, $data) { + $data = gzdecode($data); + + $data = json_decode($data, false, 512, JSON_BIGINT_AS_STRING); +// var_dump($data); +// return; + if (isset($data->ping)) { + echo "回应ping\r\n"; + $con->send(json_encode(['pong' => $data->ping])); + } else { + UserChat::sendText($data); + } + }); + + $connection->connect(); + }); + + + $worker->runAll(); + + } + + protected function initWorker() + { +// global $argv; +// $argv[1] = $command = $this->argument('worker_command'); +// $mode = $this->option('mode'); +// isset($mode) && $argv[2] = '-' . $mode; + } + + protected function bindEvent() + { +// foreach ($this->events as $key => $event) { +// method_exists($this->callback_class, $event) && $this->worker->$event = [$this->callback_class, $event]; +// } + } +} diff --git a/app/Console/Commands/WebSocketClient-old.php b/app/Console/Commands/WebSocketClient-old.php new file mode 100644 index 0000000..319333c --- /dev/null +++ b/app/Console/Commands/WebSocketClient-old.php @@ -0,0 +1,48 @@ +callback_class = new $class_name(); + $this->worker = new Worker(); + $this->worker->count = $process_num; + $this->worker->name = 'Huobi Websocket'; + } + public function handle() + { + $this->initWorker(); + $this->bindEvent(); + $this->worker->runAll(); + } + protected function initWorker() + { + global $argv; + $command = $this->argument('worker_command'); + $argv[1] = $command; + $mode = $this->option('mode'); + if ((bool) isset($mode)) { + $argv[2] = '-' . $mode; + } + } + protected function bindEvent() + { + foreach ($this->events as $key => $event) { + if ((bool) method_exists($this->callback_class, $event)) { + $this->worker->{$event} = [$this->callback_class, $event]; + } + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/WebSocketClient.php b/app/Console/Commands/WebSocketClient.php new file mode 100644 index 0000000..3704987 --- /dev/null +++ b/app/Console/Commands/WebSocketClient.php @@ -0,0 +1,85 @@ +callback_class = new $class_name(); + $this->worker = new Worker(); + $this->worker->count = $process_num; + $this->worker->name = 'Huobi Websocket'; + } + + /** + * Execute the console command. + * + * @return mixed + */ + public function handle() + { + $this->initWorker(); + $this->bindEvent(); + $this->worker->runAll(); + } + + protected function initWorker() + { + global $argv; + $argv[1] = $command = $this->argument('worker_command'); + $mode = $this->option('mode'); + isset($mode) && $argv[2] = '-' . $mode; + } + + protected function bindEvent() + { + foreach ($this->events as $key => $event) { + method_exists($this->callback_class, $event) && $this->worker->$event = [$this->callback_class, $event]; + } + } +} diff --git a/app/Http/Controllers/Api/AccountController.php b/app/Http/Controllers/Api/AccountController.php new file mode 100644 index 0000000..ce75b9f --- /dev/null +++ b/app/Http/Controllers/Api/AccountController.php @@ -0,0 +1,69 @@ +error("参数错误"); + + $user = Users::where("id", $address)->first(); + if (empty($user)) return $this->error("数据未找到"); + + + $data = AccountLog::where("user_id", $user->id)->orderBy('id', 'DESC')->paginate($limit); + return $this->success(array( + "user_id" => $user->id, + "data" => $data->items(), + "limit" => $limit, + "page" => $page, + )); + } + + public function show_profits(Request $request) + { + $user_id = Users::getUserId(); + $limit = $request->input('limit', 10); + $prize_pool = AccountLog::whereHas('user', function ($query) use ($request) { + $account_number = $request->input('account_number'); + if ($account_number) { + $query->where('account_number', $account_number); + } + // $scene = $request->input('scene', -1); + $start_time = strtotime($request->input('start_time', null)); + $end_time = strtotime($request->input('end_time', null)); + // $scene != -1 && $query->where('scene', $scene); + $start_time && $query->where('created_time', '>=', $start_time); + $end_time && $query->where('created_time', '<=', $end_time); + })->where("type", AccountLog::PROFIT_LOSS_RELEASE)->where("user_id", "=", $user_id)->orderBy('id', 'desc')->paginate($limit); + + return $this->success($prize_pool); + } + + + public function chargeMentionMoney(Request $request) + { + $limit = $request->get('limit', 5); + $user_id = Users::getUserId(); + $arr = [AccountLog::ETH_EXCHANGE, AccountLog::WALLETOUT, AccountLog::WALLETOUTDONE, AccountLog::WALLETOUTBACK]; + $currency = $request->get('currency', -1); + $list = AccountLog::where(function ($query) use ($currency) { + $currency != -1 && $query->where('currency', $currency); + })->whereIn('type', $arr) + ->where('user_id', $user_id) + ->orderBy('id', 'desc') + ->paginate($limit); + return $this->success($list); + } +} diff --git a/app/Http/Controllers/Api/AiController.php b/app/Http/Controllers/Api/AiController.php new file mode 100644 index 0000000..03db968 --- /dev/null +++ b/app/Http/Controllers/Api/AiController.php @@ -0,0 +1,388 @@ + 0 ? UserLevelModel::find($user['user_level']) : 'V0'; + $data['lianghua_amount'] = 325346.801; //策略总收益 + $data['todayincome'] = 0; // 今日收益 + $data['totalincome'] = 999999.99; // 总收益 + $data['rate'] = 0.00; // 回报 + $data['earning'] = 125.87; // 累计赚取 + $data['ernning'] = 6232325.87; // 当前收益 + $data['usenum'] = 336388; // 使用人数 + $nowday = date('Ymd',time()); + $nowtime = date('Y-m-d H:i:s',time()); + $info['data'] = AiCurrency::where('status',1)->where('hot',1)->select("id","invest",'rate',"purchased_number as number")->orderBy('id','ASC')->get(); + + foreach ($info['data'] as $k=>$v){ + $invest = $v['invest']; + $arr=[]; + $c= explode("/",$invest); + foreach ($c as $k1=>$v1){ + $Currencys = Currency::where('name',$v1)->first(); + + $arr[$k1][$v1]= $Currencys?$Currencys->logo:''; + } + + $info['data'][$k]['logo'] =$arr; + } + + + + $info['square'] = AiCurrency::where('status',1)->select("id","name","invest","days",'rate',"ratemax","amount","type","purchased_number as number")->orderBy('id','ASC')->get(); + + + + foreach ($info['square'] as $k=>$v){ + $invest = $v['invest']; + $c= explode("/",$invest); + $arri=[]; + foreach ($c as $k1=>$v1){ + $Currencys = Currency::where('name',$v1)->first(); + + $arri[$k1][$v1]= $Currencys?$Currencys->logo:''; + } + + $info['square'][$k]['logo'] =$arri; + } + + + + $info['scroll'] = AiOrder::where('status',0)->select("id","user_id")->orderBy('id','ASC')->get(); + foreach ($info['scroll'] as $k=>$v){ + + $email = Users::where('id',$v['user_id'])->value('email'); + + + + $info['scroll'][$k]['email'] =substr($email,0,3)."***".strstr($email,'@'); + } + + + + $invest ="BTC+ETH+ATOM"; + $invest = explode("+",$invest); + $arr =[]; + foreach ($invest as $k=>$v){ + + $Currencys = Currency::where('name',$v)->first(); + $arr[$k]['name']= $v; + $arr[$k]['logo']= $Currencys?$Currencys->logo:''; + + // $arr[$k]['change']= CurrencyQuotation::where('currency_id',$Currencys->id)->value('change'); + $arr[$k]['now_price']= CurrencyQuotation::where('currency_id',$Currencys->id)->value('now_price'); + } + + + // return $this->error($nowday); + + // $data['lianghua_amount'] = AiOrder::where('user_id',$user_id)->where('today',$nowday)->sum('amount'); + /* + $data['lianghua_amount'] = AiOrder::where('user_id',$user_id)->where('expire','>=',$nowtime)->where('created','<=',$nowtime)->sum('amount'); + $data['todayincome'] = AiOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + + $data['totalincome'] = AiOrder::where('user_id',$user_id)->where('today',$nowday)->sum('totalincome'); + */ + if($user_id){ + // $data['lianghua_amount'] = AiOrder::where('user_id',$user_id)->where('status',0)->sum('amount'); + $data['todayincome'] = AiOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + + // $data['totalincome'] = AiOrder::where('user_id',$user_id)->sum('totalincome'); + } + $data['VIP'] = $user['user_level'] > 0 ?$userLevel['name'] : 'V0'; + if($data['lianghua_amount']>0) $data['rate'] = round(bcdiv($data['todayincome'],$data['lianghua_amount'],4)*100,4); // 回报率 + + + + $info = array_merge($info,$data); + + + + + + return $this->success(array("info"=>$info,"currency"=>$arr)); + + } + + //查看我的理财订单 + public function ai_list(Request $request){ + $limit = $request->get('limit', 100); + $status = $request->get('status',0); + + $user_id = Users::getUserId(); //99920326; + + $user = Users::find($user_id); + + $userLevel = $user['user_level'] > 0 ? UserLevelModel::find($user['user_level']) : 'V0'; + // $list = DB::table('Ai_order')->select('Ai_order.*','Ai_currency.name')->join('Ai_currency', 'Ai_currency.id', '=', 'Ai_order.Ai_id')->where('Ai_order.user_id', $user_id)->where('Ai_order.status', $status)->orderBy('Ai_order.id', 'desc')->paginate($limit); + + $list = AiOrder::where('user_id', $user_id)->where('status', $status)->select('id','ai_id','name','day','amount','number','total','commission','totalincome','startdate','expire','status')->orderBy('id', 'desc')->paginate($limit); + + + foreach ($list as $k=>$v){ + $invest = $v['name']; + $c= explode("/",$invest); + $arri=[]; + foreach ($c as $k1=>$v1){ + $Currencys = Currency::where('name',$v1)->first(); + + $arri[$k1][$v1]= $Currencys?$Currencys->logo:''; + } + $list[$k]['type'] = AiCurrency::where('id',$v['ai_id'])->value('type')??'Martingale'; + $list[$k]['logo'] =$arri; + } + + + + + + + return $this->success(array( + "list" => $list->items(), + "limit" => $limit, + 'VIP'=> $user['user_level'] > 0 ?$userLevel['name'] : 'V0', + )); + } + + + //理财撤单 + public function Aicancle(Request $request){ + $id = $request->post('id'); + + $user_id = Users::getUserId(); + + + if(empty($id) || !is_numeric($id)){ + return $this->error('Parameter error:ID Is NULL'); + } + + $Ai_order = AiOrder::where('id',$id)->where('status',0)->first(); + + $amount = $Ai_order->amount; + if(empty($amount)){ + return $this->error('Parameter error:amount Is NULL'); + } + $liquidateddamages = $Ai_order->liquidateddamages; + $todayincome = $Ai_order->todayincome; + $totalincome= $Ai_order->totalincome; + + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + + + // $Ai_order->remaining_number = $Ai_order->remaining_number +1; + // $Ai_order->purchased_number = $Ai_order->purchased_number -1; + $Ai_order->status = 1; + $Ai_order->amount = 0; + $Ai_order->todayincome=0; + $Ai_order->totalincome=0; + $amount = $amount - $amount*$liquidateddamages/100; + + + + $result = change_wallet_balance($user_walllet , 2 , $amount , AccountLog::USER_LOAN_ORDER_RETURN,'组合投资返本'); + if($result){ + $Ai_order->save(); + return $this->success('操作成功'); + + } + + } + + + + + + + //购买理财 + public function buyAi(Request $request){ + $id = $request->post('id'); + $num = $request->post('num'); + $user_id = Users::getUserId();//99920326; + $num = intval($num); + + if(empty($num) || !is_numeric($num)){ + return $this->error('Parameter error:num '); + } + + if(empty($id) || !is_numeric($id)){ + return $this->error('Parameter error:ID Is NULL'); + } + + $user = Users::where('id', $user_id)->first(); + + + if ($user->frozen_funds == 1 || $user->status == 1) { + return $this->error('Hello, Account is Locked. Please contact customer service for details.'); + } + + // if(Cache::has("by_Ai_order_$user_id")){ + // return $this->error('Do not repeat the operation!'); + // } + // Cache::put("by_Ai_order_$user_id", 1, Carbon::now()->addSeconds(5));//禁止重复提交 + + // $count = AiOrder::where('user_id',$user_id)->where('Ai_id',$id)->count(); + $Ai_currencys = AiCurrency::where('id',$id)->first(); + + + $expire = time()+$Ai_currencys->days*24*60*60; + //if($Ai_currencys->end_time <= date('Y-m-d') || $Ai_currencys->status == 0){//结束时间等于今天不可购买 + // return $this->error('Project has ended!'); + // } + + + // if($count + $num > $Ai_currencys->user_limit){ + // return $this->error('Purchase limit exceeded!'); + // } + + $invest = $Ai_currencys->invest; + + + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + if($user_walllet->change_balance < $num){ + return $this->error('Insufficient balance!'); + } + + + DB::beginTransaction(); + try{ + // $d1=strtotime($Ai_currencys->end_time); + // $d2 = strtotime(date('Y-m-d')); + // $dayCount=round(($d1- $d2)/3600/24); + $Ai_order = new AiOrder(); + $Ai_order->user_id = $user_id; + // $Ai_order->currency_id = $buy_currency;//用户购买时消耗的币种 + // $Ai_order->Ai_id = $Ai_currencys->id; + + $Ai_order->order_rate = $Ai_currencys->rate; + $Ai_order->Ai_id = $id; + $Ai_order->name = $invest; + $Ai_order->invest = $invest; + $Ai_order->commission=$Ai_currencys->commission; + $Ai_order->rate = $Ai_currencys->rate."-".$Ai_currencys->ratemax; + $Ai_order->day = $Ai_currencys->days; + $Ai_order->amount = $num; + $Ai_order->expire = date('Y-m-d H:i:s',$expire); + $Ai_order->orderid =date("YmdHis",time()).$expire; + $Ai_order->liquidateddamages = $Ai_currencys->liquidateddamages; + // $Ai_order->price = $now_price; + // $Ai_order->total = $total; + $Ai_order->startdate =date('Y-m-d H:i:s',time()); + $Ai_order->created = date('Y-m-d H:i:s'); + + + // $Ai_currencys->refresh(); + // if($num > $Ai_currencys->remaining_number || $count + $num > $Ai_currencys->user_limit){//已经卖完 + // DB::rollBack(); + // return $this->error('Sold out!'); + // } + + // $Ai_currencys->remaining_number = $Ai_currencys->remaining_number - 1; + $Ai_currencys->purchased_number = $Ai_currencys->purchased_number + 1; + $Ai_currencys->save(); + + $result = change_wallet_balance($user_walllet , 2 , -$num , AccountLog::USER_AI_ORDER_BUY,'AI量化策略扣除'); + if($result) $Ai_order->save(); + + DB::commit(); + return $this->success('Successful'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function getDetail(Request $request){ + $Ai_id = $request->get('id'); + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'zh'; + $where['lang']=$lang; + $Ai = AiCurrency::where('id',$Ai_id)->select('id','invest','days','rate','ratemax','netrate','amount','amax','commission','type','purchased_number as usenum')->first(); + $invest = explode("/",$Ai->invest); + $arr =[]; + foreach ($invest as $k=>$v){ + + $Currencys = Currency::where('name',$v)->first(); + $arr[$k]['name']= $v; + $arr[$k]['logo']= $Currencys?$Currencys->logo:''; + + + + // $arr[$k]['change']= CurrencyQuotation::where('currency_id',$Currencys->id)->value('change'); + + } + $Ai['news'] = News::where($where)->where('type',$Ai->type)->select('id','abstract','content','cover','thumbnail','title')->first(); + + $Ai['totalamonut'] = AiOrder::where('ai_id',$Ai->id)->sum('amount')??0.00; + + $t3= time()-3*86400; + $t7= time()-7*86400; + $t10= time()-10*86400; + $now3 = date('Y-m-d H:i:s',$t3); + $now7 = date('Y-m-d H:i:s',$t7); + $now10 = date('Y-m-d H:i:s',$t10); + $Ai['day3']= number_format(AiOrder::random_float(4.18,9.88),2);//AiOrder::where('ai_id',$Ai->id)->where('created','>=',$now3)->sum('amount')??0.00; + $Ai['day7']= number_format(AiOrder::random_float(10.18,16.88),2);//AiOrder::where('ai_id',$Ai->id)->where('created','>=',$now7)->sum('amount')??0.00; + $Ai['day10']= number_format(AiOrder::random_float(17.18,25.88),2);//AiOrder::where('ai_id',$Ai->id)->where('created','>=',$now10)->sum('amount')??0.00; + + $user_id = Users::getUserId(); + $account = UsersWallet::where('user_id',$user_id)->where('currency',3)->value('change_balance')??"0.00"; //可用USDT + // print_r($arr);exit; + return $this->success(array( + "detail" => $Ai, + "Currency" => $arr, + 'balance' => $account, + )); + // return $this->success($Ai); + } + + + +public function order_detail(Request $request){ + $id =$request->get('id'); + $Ai = AiList::where('order_id',$id)->select('id','amount','addtime')->orderBy('id','ASC')->get(); + $total= AiList::where('order_id',$id)->sum('amount'); + foreach ($Ai as $k=>$v){ + $Ai[$k]['addtime']= date('Y-m-d H:i:s',$v->addtime); + } + return $this->success(array( + "detail" => $Ai, + "total" => $total, + )); + + return $this->success($Ai); + } + + +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/ApiController.php b/app/Http/Controllers/Api/ApiController.php new file mode 100644 index 0000000..ded5b88 --- /dev/null +++ b/app/Http/Controllers/Api/ApiController.php @@ -0,0 +1,156 @@ +user_id = Token::getUserIdByToken($token); + // } + $token = @$_POST['token']; + + header('Content-Type:application/json'); + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST'); + header('Access-Control-Allow-Headers:x-requested-with,content-type'); + header('Access-Control-Allow-Headers:x-requested-with,content-type,Authorization'); + + } + public function batchSetRisk(){ + $ids = @$_POST['ids']; + $risk = @$_POST['risk']; + + if (empty($ids)) { + return json_encode(['error'=>'Parameter error']); + } + if(!isset($ids) ||!isset($risk)){ + return json_encode(['error'=>'Parameter error']); + } + if(!is_array($ids)){ + return json_encode(['error'=>'Need to pass in an array']); + } + $data =['-1','0','1']; + if(!in_array($risk, $data)){ + return json_encode(['error'=>'Risk error']); + } + + try { + $affect_rows = MicroOrder::where('status', MicroOrder::STATUS_OPENED) + ->whereIn('id', $ids) + ->update([ + 'pre_profit_result' => $risk, + ]); + return json_encode([ 'success'=> '本次提交:' . count($ids) . '条,设置成功:' . $affect_rows . '条']); + } catch (\Throwable $th) { + return json_encode(['error'=>$th]); + } + + } + + //单个设置 + public function setUserRisk(){ + $user_id = @$_POST['user_id']; + $risk = @$_POST['risk']; + + if(!isset($user_id) ||!isset($risk)){ + return json_encode(['error'=>'Parameter error']); + } + $data =['-1','0','1']; + if(!in_array($risk, $data)){ + return json_encode(['error'=>'Risk error']); + } + + $user = Users::find($user_id); + if (empty($user)) { + return json_encode(['error'=>'User error']); + } + $user->risk = $risk; + $user->save(); + + return json_encode(['success'=>'ok']); + + } + + public function apiPerject() + { + $risk_mode = @$_POST['risk_mode']; + $risk_end_ago_max = @$_POST['risk_end_ago_max']; + $risk_probability_switch = @$_POST['risk_probability_switch']; + $risk_profit_probability = @$_POST['risk_profit_probability']; + $risk_group_result = @$_POST['risk_group_result']; + // $risk_money_profit_probability = $_POST['risk_money_profit_probability']; // + if(!isset($risk_mode) || + !isset($risk_end_ago_max)|| + !isset($risk_probability_switch)|| + !isset($risk_profit_probability)|| + !isset($risk_group_result) + ){ + return json_encode(['error'=>'Parameter error']); + } + + if(!in_array($risk_mode,['0','1','2','3','4','5'])){ + return json_encode(['error'=>'risk_mode error']); + } + + if($risk_end_ago_max >=86400 ){ + return json_encode(['error'=>'risk_end_ago_max error']); + } + + if(!in_array($risk_probability_switch,['0','1'])){ + return json_encode(['error'=>'risk_probability_switch error']); + } + + if($risk_profit_probability >100 || $risk_profit_probability<0){ + return json_encode(['error'=>'risk_profit_probability error']); + } + + + switch ($risk_mode) { + case '0': + break; + case '1': + break; + case '2': //global + $data = ['1','-1']; + if(!in_array($risk_group_result,$data)){ + return json_encode(['error'=>'risk_group_result error']); + } + $setting = Setting::where('key', 'risk_group_result')->first(); + $setting->value = $risk_group_result; + $setting->save(); + break; + case '3': + break; + case '4': + break; + case '5': + break; + default: + break; + } + + $setting = Setting::where('key', 'risk_mode')->first(); + $setting->value = $risk_mode; + $setting->save(); + $setting = Setting::where('key', 'risk_end_ago_max')->first(); + $setting->value = $risk_end_ago_max; + $setting->save(); + $setting = Setting::where('key', 'risk_probability_switch')->first(); + $setting->value = $risk_probability_switch; + $setting->save(); + $setting = Setting::where('key', 'risk_mode')->first(); + $setting->value = $risk_mode; + $setting->save(); + + return json_encode(['success'=>'ok']); + + } + +} diff --git a/app/Http/Controllers/Api/BankController.php b/app/Http/Controllers/Api/BankController.php new file mode 100644 index 0000000..3acaf56 --- /dev/null +++ b/app/Http/Controllers/Api/BankController.php @@ -0,0 +1,777 @@ + 1, + ])->where('start_at','<',date("Y-m-d")) + ->where('last_settle_time','<',date("Y-m-d")) + ->orWhere('last_settle_time',null) + ->take(500) ->get(); + foreach($res as $order){ + LhDepositOrder::dispatchInterest($order->id); + // if($order->end_at < date('Y-m-d')){ + // //todo 时间到了 释放存款 + // LhDepositOrder::where('id',$order->id)->update(['status' => 2]); + // } + } + + return $this->success('success'); + } + + public function weekProfit(){ + $user_id = Users::getUserId(); + //判断是否有账号 + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('还未创建账户'); + } + $beginDay = date('Y-m-d',strtotime('-8 day')); + $res = LhDepositOrderLog::where('bank_account_id',$res->id) + ->where('interest_day','>',$beginDay) + ->groupBy('interest_day') + ->selectRaw('sum(interest_amount) as amount, interest_day') + ->get(); + return $this->success([ + 'list'=>$res + ]); + } + + public function bankLog(Request $request){ + $user_id = Users::getUserId(); + //判断是否有账号 + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('还未创建账户'); + } + $limit = $request->get('limit', 20); + $page = $request->get('page', 1); + $type = $request->get('type',null); + $search = $request->get('search',''); + $where = []; + if($type){ + $where['type'] = $type; + } + if($search){ + $where['description'] = $search; + } + $res = LhBankAccountLog::where('account_id',$res->id) + ->where($where) + ->orderBy('id','desc') + ->skip($limit*($page-1))->take($limit) + ->get(); + return $this->success([ + 'list' => $res + ]); + } + + // public function newAccount(){ + // $user_id = Users::getUserId(); + // $user = Users::find($user_id); + // if (!$user) { + // return $this->error('用户不存在'); + // } + // if($user->is_realname != 2){ + // return $this->error('请实名制'); + // }; + + // //判断是否有账号 + // $res = LhBankAccount::where('uid',$user_id)->first(); + // if($res){ + // return $this->error('已创建过账户'); + // } + // //获取爸爸加过的团队 全部再加一次 + // if($user->parent_id){ + // $parentTeamList = LhBankTeamMember::getUserTeams($user->parent_id); + // } + // DB::beginTransaction(); + // try{ + // $model = new LhBankAccount(); + // $model->uid = $user_id; + // $model->usdt_balance = LhBankAccount::INIT_BALANCE; + // $model->p_uid = $user->parent_id; + // $model->save(); + // if(isset($parentTeamList) && $parentTeamList){ + // foreach($parentTeamList as $team){ + // LhBankTeamMember::addTeamMember($team->leader_uid,$user_id,$team['generation']+1); + // } + // } + // if($user->parent_id){ + // LhBankTeamMember::addTeamMember($user->parent_id,$user_id,1); + // } + + // DB::commit(); + // }catch (\Exception $e){ + // DB::rollBack(); + // return $this->error($e->getMessage()); + // } + + // return $this->success('创建成功'); + // } + + public function myAccount(){ + $user_id = Users::getUserId(); + + //判断是否有账号 + /** @var LhBankAccount $res */ + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error(null); + } + else{ + $res->total_profit_df =0; + $res->total_profit_usdt = 0; + $res->last_day_profit_df = 0; + $res->last_day_profit_usdt = 0; + $res->total_value = 0; + $res->total_invited = 0; + $res->total_lock_usdt = LhDepositOrder::where('bank_account_id',$res->id)->where('status',1)->sum('usdt_amount'); + $res->total_lock_df = LhDepositOrder::where('bank_account_id',$res->id)->where('status',1)->sum('amount'); + return $this->success([ + 'account_info' => $res, + 'usdt' => Setting::getValueByKey('AUTU_USDT_NUM',300), + 'df' => Setting::getValueByKey('AUTU_UNLOCK_NUM',1000) + ]); + } + } + + public function saveMoney(){ + $user_id = Users::getUserId(); + $amount = Input::get('amount',''); + //判断是否有账号 + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('您还未创建账户'); + } + $amount = (float)$amount; + + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", 3) //usdt + ->lockForUpdate() + ->first(); + if (!$legal) { + return $this->error("钱包未找到,请先添加钱包"); + } + if($legal->change_balance < $amount){ + return $this->error('资金钱包余额不足'); + } + DB::beginTransaction(); + try{ + //先扣费 + $result = change_wallet_balance( + $legal, + 2, + -$amount, + AccountLog::TRANSFER_TO_LH_ACCOUNT, + '转账入余币宝', + false, + 0, + 0, + serialize([]) + ); + $res->usdt_balance += $amount; + $res->save(); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,$amount,'转账入金'); + Db::commit(); + }catch (\Exception $e){ + Db::rollBack(); + return $this->error($e->getMessage()); + } + return $this->success('入金成功'); + } + + + + + public function config(Request $request){ + $currencyId = $request->input('currency_id'); + if(!$currencyId){ + return $this->error('require param currency_id'); + } + $page = $request->get('page'); + $list = DB::table('lh_deposit_config')->join('currency','currency.id','=','currency_id') + ->where('currency_id',$currencyId) + ->offset(($page-1)*10)->limit(10) + ->select(['currency.name as currency_name','currency.logo as currency_logo','lh_deposit_config.*']) + ->get(); + return $this->success($list); + } + + public function newDeposit(Request $request){ + $id = $request->get('config_id'); + $amount = $request->get('amount'); + $config = DB::table('lh_deposit_config')->where('id',$id)->first(); + if($amount<=0){ + return $this->error('参数错误'); + } + if(!$config){ + return $this->error('项目不存在'); + } + if($amount < $config->save_min){ + return $this->error('最少存入数量为:'.$config->save_min); + } + //钱包 + $user_id = Users::getUserId(); + + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", $config->currency_id) //usdt + ->lockForUpdate() + ->first(); + DB::beginTransaction(); + try{ + $result = change_wallet_balance( + $legal, + 2, + -$amount, + AccountLog::TRANSFER_TO_LH_ACCOUNT, + '锁仓', + false, + 0, + 0, + serialize([]) + ); + $result = change_wallet_balance( + $legal, + 2, + $amount, + AccountLog::TRANSFER_TO_LH_ACCOUNT, + '锁仓', + true, + 0, + 0, + serialize([]) + ); + + $order = LhDepositOrder::newOrder($user_id,$config->currency_id,$amount,$config->day,$config->interest_rate); + + DB::commit(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + + } + return $this->success('操作成功'); + } + + /** + * @return \Illuminate\Http\JsonResponse + * @author + */ + public function timeDeposit(){ + $user_id = Users::getUserId(); + $num = Input::get('num',0); + $num = (int)$num; + if($num <= 0){ + return $this->error('数量不可低于0'); + } + //判断是否有账号 + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('您还未创建账户'); + } + + $amount = Setting::getValueByKey('AUTU_USDT_NUM',300); + $amount *= $num; + $df_amount = Setting::getValueByKey('AUTU_UNLOCK_NUM',1000); + $df_amount *= $num; + if($res->usdt_balance < $amount){ + return $this->error('你的账户余额不足'); + } + if($res->df_balance <= 0){ + return $this->error('你的锁定余额为0'); + } + if($res->df_balance < $df_amount){ + $df_amount = $res->df_balance; + // return $this->error('你的锁定余额不足'.$df_amount); + } + + $totalDeposit = LhBankAccount::getTotalDeposit($res->id); + DB::beginTransaction(); + try{ + $res->usdt_balance -= $amount; + $res->df_balance -= $df_amount; + $res->save(); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,-$amount,'解冻申请'); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_DF,-$df_amount,'解冻申请'); + $order = LhDepositOrder::newOrder($res->id,$df_amount,$amount); + + DB::commit(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + + } + return $this->success('存币成功'); + } + + public function myDepositOrder(Request $request){ + $user_id = Users::getUserId(); + + $limit = $request->get('limit', 20); + $page = $request->get('page', 1); + $isCancel = $request->get('is_cancel',0); + $status = $request->get('status',null); + $where = []; + if($isCancel){ + $where = [ + 'is_cancel' => 1 + ]; + } + if($status){ + $where['status'] = $status; + } + + $res = LhDepositOrder::where('user_id',$user_id) + ->join('currency','currency.id','=','currency_id') + ->where($where) + ->orderBy('lh_deposit_order.id','desc') + ->skip($limit*($page-1))->take($limit) + ->get(['currency.name as currency_name','lh_deposit_order.id','amount','day_rate','total_interest','start_at','end_at','status']); + return $this->success([ + 'order_list' => $res + ]); + } + + public function cancelOrderNew(){ + $orderId = Input::get('id'); + $order = LhDepositOrder::find($orderId); + if(!$order){ + return $this->error('找不到存单'); + } + $user_id = Users::getUserId(); + if($order->user_id != $user_id){ + return $this->error('非法操作'); + } + if($order->status!=1){ + return $this->error('存单状态异常'); + } + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", $order->currency_id) //usdt + ->lockForUpdate() + ->first(); + DB::beginTransaction(); + try{ + //扣钱 + $returnAmount = $order->amount-$order->cancel_fee; + + $order->status = 2; + $order->is_cancel = 1; + $order->save(); + $result = change_wallet_balance( + $legal, + 2, + $returnAmount, + AccountLog::BANK_WITHDRAW, + '锁仓返还', + false, + 0, + 0, + serialize([]) + ); + DB::commit(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + } + return $this->success('毁约成功'); + } + + + + public function cancelOrder(){ + return $this->error('功能暂不可用'); + $user_id = Users::getUserId(); + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('您还未创建账户'); + } + $orderId = Input::get('id'); + $order = LhDepositOrder::find($orderId); + if(!$order){ + return $this->error('找不到存单'); + } + if($order->bank_account_id != $res->id){ + return $this->error('非法操作'); + } + if($order->status != 1){ + return $this->error('存单状态异常'); + } + $loan = LhLoanOrder::where(['bank_account_id'=>$res->id,'status' => 1])->first(); + if($loan) { + return $this->error('你还有质押单,不可毁约'); + } + //判断毁约期限 + if(strtotime('+30 day',strtotime($order->start_at)) < date("Y-m-d")){ + return $this->error('毁约时间已过'); + } + DB::beginTransaction(); + try{ + //扣钱 + $costRate = Setting::getValueByKey('CANCEL_DEPOSIT_ORDER_COST',20); + $returnAmount = $order->amount * (1-$costRate/100); + $balance = bc_add($res->usdt_balance,$returnAmount); + $res->usdt_balance = $balance; + $res->save(); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,$returnAmount,'毁约退款'); + $order->status = 2; + $order->is_cancel = 1; + $order->save(); + //更新自己账号等级 + LhBankProfitLogic::cancelOrderUpdate($res->id); + DB::commit(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + } + return $this->success('毁约成功'); + } + + + /** + * 提现至钱包 + * @return \Illuminate\Http\JsonResponse + * @throws \Exception + * @author + */ + public function withdraw(){ + $user_id = Users::getUserId(); + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('您还未创建账户'); + } + $depositAmount = LhBankAccount::getTotalDeposit($res->id); + $amount = Input::get('amount',0); + if($amount<10){ + return $this->error('最少提币金额为10'); + } + $type = Input::get('type',''); //1 usdt 2 dfone + $withdrawFee = Setting::getValueByKey('LH_WITHDRAW_FEE',0); + if($withdrawFee>100){ + return $this->error('提现失败,请联系管理员'); + } + switch ($type){ + case 1: + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", 3) //usdt + ->lockForUpdate() + ->first(); + + DB::beginTransaction(); + try{ + + //扣手续费 + change_wallet_balance( + $legal, + 2, + $amount, + AccountLog::BANK_WITHDRAW, + '理财账户提现', + false, + 0, + 0, + serialize([]) + ); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,-$amount,'理财账户提现'); + DB::commit(); + }catch (\Exceptionq $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + } + break; + case 2: + return $this->error('维护中'); + $DfWallet = UsersWallet::getDF1Wallet($user_id); + if(!$DfWallet){ + return $this->error('找不到钱包'); + } + if($res->df_balance - $amount < 0){ + return $this->error('余额不足'); + } + + DB::beginTransaction(); + try{ + + $balance = bc_sub($res->df_balance,$amount); + $res->df_balance = $balance; + $res->save(); + $amount = bc_mul($amount,(1-($withdrawFee/100))); + change_wallet_balance( + $DfWallet, + 1, + $amount, + AccountLog::BANK_WITHDRAW, + '余币宝提现', + false, + 0, + 0, + serialize([]) + ); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_DF,-$amount,'提现'); + DB::commit(); + }catch (\Exceptionq $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + } + break; + default: + return $this->error('错误类型'); + } + return $this->success('提现成功'); + } + + + public function loan(){ + $user_id = Users::getUserId(); + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('您还未创建账户'); + } + $amount = Input::get('amount',0); + if($amount<100){ + return $this->error('最少质押金额为100'); + } + $type = Input::get('wallet_type',0); + //验证当前质押单总额 + $totalLoan = LhLoanOrder::where([ + 'bank_account_id' => $res->id, + 'status' => 1 + ])->sum('amount'); + //查询当前存单金额 + $totalDeposit = LhBankAccount::getTotalDeposit($res->id); + $maxLoan = bc_mul($totalDeposit,0.8,0); + if($totalLoan+$amount > $maxLoan){ + return $this->error('总质押金额超出,你还可以质押:'.($maxLoan-$totalLoan)); + } + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", 3) //usdt + ->lockForUpdate() + ->first(); + + $redis = Redis::connection(); + $lock = new RedisLock($redis,'user_bank_loan_'.$user_id,10); + if($lock->acquire()) { + DB::beginTransaction(); + try{ + //创建订单 + LhLoanOrder::newOrder($res->id,$amount); + //贷款出账 + switch ($type){ + case 1: + //资金钱包 + change_wallet_balance( + $legal, + 1, + +$amount, + AccountLog::LH_LOAN, + '质押入账', + false, + 0, + 0, + serialize([]) + ); + break; + case 2: + change_wallet_balance( + $legal, + 4, + +$amount, + AccountLog::LH_LOAN, + '质押入账', + false, + 0, + 0, + serialize([]) + ); + break; + case 3: + change_wallet_balance( + $legal, + 3, + +$amount, + AccountLog::LH_LOAN, + '质押入账', + false, + 0, + 0, + serialize([]) + ); + break; + break; + default: + $res->usdt_balance += $amount; + $res->save(); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,$amount,'质押入账'); + + } + + DB::commit(); + $lock->release(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error('质押失败'); + } + } + return $this->success('质押成功'); + } + + public function loanList(Request $request){ + $user_id = Users::getUserId(); + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('您还未创建账户'); + } + $limit = $request->get('limit', 20); + $page = $request->get('page', 1); + $status = $request->get('status',null); + $where = []; + if($status){ + $where['status'] = $status; + } + $res = LhLoanOrder::where('bank_account_id',$res->id) + ->where($where) + ->orderBy('id','desc') + ->skip($limit*($page-1))->take($limit) + ->get(); + return $this->success($res); + } + + public function repayment(Request $request){ + $user_id = Users::getUserId(); + $res = LhBankAccount::where('uid',$user_id)->first(); + if(!$res){ + return $this->error('您还未创建账户'); + } + $is_zj_wallet = Input::get('is_zj_wallet',0); + $amount = Input::get('amount',0); + if($amount <0){ + return $this->error('还款金额有误'); + } + //usdtWallet + + if($is_zj_wallet){ + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", 3) //usdt + ->lockForUpdate() + ->first(); + if (!$legal) { + return $this->error("钱包未找到,请先添加钱包"); + } + if($legal->legal_balance < $amount){ + return $this->error('资金钱包余额不足'); + } + }else{ + if($amount> $res->usdt_balance){ + return $this->error('余币宝账号余额不足'); + } + } + + $orderId = Input::get('order_id'); + if(!$orderId){ + return $this->error('参数异常'); + } + $order = LhLoanOrder::where(['id' => $orderId,'bank_account_id' => $res->id])->first(); + if(!$order){ + return $this->error('找不到质押单'); + } + $maxReturn = ($order->amount+$order->total_interest)-$order->total_return; + if($maxReturn<=0){ + return $this->error('已还清'); + } + DB::beginTransaction(); + try{ + //先判断还款金额是否超过所需还款金额 + if($amount - $maxReturn >= 0){ + $amount = $maxReturn; + $status = 2; + }else{ + $status = 1; + } + //扣款 + if(isset($legal)){ + change_wallet_balance( + $legal, + 1, + -$amount, + AccountLog::TRANSFER_TO_LH_ACCOUNT, + '转账入余币宝', + false, + 0, + 0, + serialize([]) + ); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,+$amount,'资金账户转入余币宝'); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,-$amount,'质押还款'); + }else{ + $balance = bc_sub($res->usdt_balance,$amount,8); + $res->usdt_balance = $balance; + $res->save(); + LhBankAccountLog::newLog($res->id,LhBankAccountLog::LOG_TYPE_USDT,-$amount,'质押还款'); + } + + //质押单更新 + $order->total_return = bc_add($order->total_return,$amount,8); + $order->status = $status; + $order->end_at = date("Y-m-d"); + $order->save(); + DB::commit(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + } + return $this->success('还款成功'); + } +} diff --git a/app/Http/Controllers/Api/BankInfoController.php b/app/Http/Controllers/Api/BankInfoController.php new file mode 100644 index 0000000..153d321 --- /dev/null +++ b/app/Http/Controllers/Api/BankInfoController.php @@ -0,0 +1,35 @@ +success($list); + } +} diff --git a/app/Http/Controllers/Api/BindBoxController.php b/app/Http/Controllers/Api/BindBoxController.php new file mode 100644 index 0000000..65afd66 --- /dev/null +++ b/app/Http/Controllers/Api/BindBoxController.php @@ -0,0 +1,697 @@ +get('page', 1); + $limit = $request->get('limit', 2); + + $list = DB::table('bind_box') + ->join('currency', 'currency.id', '=', 'bind_box.currency_id') + ->join('users', 'users.id', '=', 'bind_box.author'); + + + // 购买所需货币种类 + $currency = $request->get('currency'); + if (!empty($currency)) { + $list = $list->where('bind_box.currency_id', $currency); + } + + // nft的售卖类型,1:一口价,2:竞拍 + $pay_type = $request->get('pay_type'); + if (!empty($pay_type)) { + $list = $list->where('bind_box.pay_type', $pay_type); + } + + // 状态:1=开始,0=已结束,2=未开始 + $status = $request->get('status'); + if (isset($status)) { + $list = $list->where('bind_box.status', $status); + } + + //产品类型,1:图片 2:动图3:音频4:视频 + $type = $request->get('type'); + if (!empty($type)) { + $list = $list->where('bind_box.type', $type); + } + + $keyword = $request->get('keyword'); + if (!empty($keyword)) { + $list = $list->where('bind_box.name','like',"%$keyword%"); + } + $list = $list->orderBy('bind_box.status','DESC')->orderBy('bind_box.id','DESC'); + $list = $list->select('bind_box.*','currency.name as currency_name','users.id as author_id','users.head_portrait as author_avatar','users.nickname as author_name')->skip($limit*($page-1))->take($limit)->get(); + foreach ($list as $li){ + $bind_box_collect = BindBoxCollect::where('code',$li->code)->where('user_id',$user_id)->first(); + $li->collect =$bind_box_collect ? true : false; + } + return $this->success($list); + } + + // 获取艺术品详情 + public function getBoxDetail(Request $request){ + $user_id = Users::getUserId(); + $id = $request->get('id'); + $code = $request->get('code',''); + if(!$id){ + return $this->success('Parameter error'); + } + $box = DB::table('bind_box') + ->join('currency', 'currency.id', '=', 'bind_box.currency_id') + ->join('users', 'users.id', '=', 'bind_box.author') + ->where('bind_box.id',$id) + ->orWhere('bind_box.code',$code) + ->select('bind_box.*','currency.name as currency_name','users.id as author_id','users.head_portrait as author_avatar','users.nickname as author_name') + ->first(); + $bind_box_collect = BindBoxCollect::where('code',$box->code)->where('user_id',$user_id)->first(); + $bind_box_collect_number = BindBoxCollect::where('code',$box->code)->where('user_id',$user_id)->count(); + + $box->collect = $bind_box_collect ? true : false; + $box->collect_number = $bind_box_collect_number; + return $this->success($box); + } + + //获取艺术家列表 + public function getArtist(Request $request){ + $page = $request->get('page', 1); + $limit = $request->get('limit', 10); + $users = DB::table('bind_box')->join('users', 'users.id', '=', 'bind_box.author') + ->select('bind_box.author as author_id','users.*')->distinct()->skip($limit*($page-1))->take($limit)->get(); + + return $this->success($users); + } + + //获取艺术家详情和其艺术品列表 + public function getArtistDetail(Request $request){ + $uid = $request->get('uid'); + $user = DB::table('users')->where('id',$uid)->first(); + + $user->artworks = DB::table('bind_box')->where('author',$uid)->get(); + $user->collects = BindBoxCollect::join('bind_box', 'bind_box.code', '=', 'bind_box_collect.code')->where('bind_box_collect.user_id',$uid)->get(); + + $artworks_codes = array(); + foreach ($user->artworks as $li){ + $artworks_codes[] = $li->code; + } + //其作品被添加收藏的个数 + $user->artworks_collect_number = BindBoxCollect::whereIn('code',$artworks_codes)->count(); + + return $this->success($user); + } + + //添加/取消 收藏 + public function collect(Request $request){ + $user_id = Users::getUserId(); + $code = $request->post('code'); + + $bind_box = BindBox::where('code',$code)->first(); + if($bind_box->owner == $user_id){ + return $this->error('The author of this NFT is you!'); + } + if(!$bind_box){ + return $this->success('NFT does not exist!'); + } + + if(Cache::has('collect_'.$code.'_'.$user_id)){ + return $this->error('Do not repeat the operation!'); + } + Cache::put('collect_'.$code.'_'.$user_id, 1, Carbon::now()->addSeconds(1)); + + $bind_box_collect = BindBoxCollect::where('code',$code)->where('user_id',$user_id)->first(); + if($bind_box_collect){ + $bind_box_collect->delete(); + }else{ + + $bind_box_collect = new BindBoxCollect(); + $bind_box_collect->code = $code; + + $bind_box_collect->user_id = $user_id; + + $bind_box_collect->created = date('Y-m-d H:i:s'); + + $bind_box_collect->save(); + + } + + return $this->success('successful'); + } + + public function getNftCurrency(){ + $currency = DB::table('bind_box')->join('currency', 'currency.id', '=', 'bind_box.currency_id')->select('currency.*')->distinct()->get(); + return $this->success($currency); + } + + //获取已收藏的列表 + public function getCollection(){ + $user_id = Users::getUserId(); + $list = DB::table('bind_box') + ->join('currency', 'currency.id', '=', 'bind_box.currency_id') + ->join('users', 'users.id', '=', 'bind_box.author') + ->join('bind_box_collect', 'bind_box_collect.code', '=', 'bind_box.code') + ->where('bind_box_collect.user_id','=',$user_id)->select('bind_box.*','currency.name as currency_name','users.id as author_id','users.head_portrait as author_avatar','users.nickname as author_name')->get(); + + foreach ($list as $li){ + $li->collect = true; + } + return $this->success($list); + } + + //购买NFT + public function buyNFT(Request $request){ + $redis = RedisService::getInstance(5); + $user_id = Users::getUserId(); + $code = $request->post('code'); + $bind_box = BindBox::where('code',$code)->first(); + if(!$bind_box){ + return $this->error('NFT does not exist'); + } + + $start_time = strtotime($bind_box->start_time); + $end_time = strtotime($bind_box->end_time); + $now = time(); + + if($now < $start_time || $now > $end_time){ + return $this->error('Non-purchase time'); + } + if($bind_box->pay_type == 2 ){//竞拍模式不能购买 + return $this->error('NFT does not exist!'); + } + if($bind_box->status == 0){//购买已结束 + return $this->error('Purchase is over'); + } + $cuurency =$bind_box->currency_id; + + if($bind_box->owner==$user_id){ + return $this->error("Can't buy own products"); + } + + $users_wallet = UsersWallet::where('currency', $cuurency)->where('user_id', $user_id)->first(); + if(!$users_wallet){ + return $this->error('UsersWallet does not exist'); + } + if($users_wallet->change_balance < $bind_box->price){ + return $this->error('Insufficient balance'); + } + if($redis->get('buy_nft_'.$code)){ + return $this->error('Has been snapped up by others!'); + } + + if($redis->get('nft_queue_'.$code)){ + return $this->error('The operation is too fast, please wait!'); + } + $redis->set('nft_queue_' . $code, 1, 1); //已经有用户进入付款 + + DB::beginTransaction(); + try{ + change_wallet_balance($users_wallet, 2, -$bind_box->price, AccountLog::USER_BUY_NFT_TYPE_1, '一口价购买NFT'); + $redis->set('buy_nft_' . $code, $user_id); + + $bind_box_order = new BindBoxOrder(); + $bind_box_order->code = $code; + $bind_box_order->buyer_id = $user_id; + $bind_box_order->sell_id = $bind_box->owner;//卖家 + $bind_box_order->author_id = $bind_box->author;//创作者 + $bind_box_order->status = 1; + $bind_box_order->order_price = $bind_box->price; + $bind_box_order->currency_id = $bind_box->currency_id; + $bind_box_order->created = date('Y-m-d H:i:s',time()); + $bind_box_order->save(); + + $bind_box->owner = $user_id; //更改NFT拥有者 + $bind_box->resell_nft_status = 0; //转卖的NFT更改为结束 + $bind_box->status = 0;//将状态改为不可购买 + $bind_box->save(); + + DB::commit();//购买成功 + return $this->success('successful'); + } catch (\Throwable $th) { + $redis->set('buy_nft_' . $code, null);//失败 清除此商品redis + DB::rollBack(); + return $this->error('Failed purchase !'); + } + + } + + + //NFT拍卖 + public function auctionNFT(Request $request){ + $redis = RedisService::getInstance(5); + $user_id = Users::getUserId(); + $code = $request->post('code'); + $price = $request->post('price'); + if(!$price){ + return $this->error('error'); + } + $bind_box = BindBox::where('code',$code)->first(); + if(!$bind_box){ + return $this->error('NFT does not exist'); + } + $start_time = strtotime($bind_box->start_time); + $end_time = strtotime($bind_box->end_time); + $now = time(); + + if($now < $start_time || $now > $end_time){ + return $this->error('Non-purchase time'); + } + if($bind_box->pay_type != 2){//拍卖模式 + return $this->error('Non-auction items!'); + } + if($bind_box->status == 0){//购买已结束 + return $this->error('Purchase is over'); + } + + $author = $bind_box->author; + $per_increase = $bind_box->per_increase; //每次最低加价额度 + + if($price < $per_increase){ + return $this->error("Increase Must be greater than ".$per_increase);//加价必须大于等于per_increase + } + if($bind_box->owner==$user_id){ + return $this->error("Can't buy own products"); + } + + $cuurency =$bind_box->currency_id; + $users_wallet = UsersWallet::where('currency', $cuurency)->where('user_id', $user_id)->first(); + if(!$users_wallet){ + return $this->error('UsersWallet does not exist');//用户钱包不存在 + } + + if($redis->get('auctionNFT_queue_'.$code)){ + return $this->error('The operation is too fast, please wait!'); + } + $redis->set('auctionNFT_queue_' . $code, 1, 2); //限制出价频率 2秒 + + $bind_box->refresh(); //取最新数据 + $nft_now_price = $bind_box->price; + + $new_price = bcadd($nft_now_price , $price); + if($new_price == $nft_now_price){ + return $this->error('Invalid markup!'); //价格已失效 + } + if($users_wallet->change_balance < $new_price){ //余额不足此次拍卖价格 + return $this->error('Insufficient balance'); + } + + //扣除保证金 + $bind_box_margin_log = BindBoxMarginLog::where('code',$code)->where('user_id',$user_id)->where('status',1)->where('is_expired',0)->first(); + if(!$bind_box_margin_log){ //未交保证金 + $margin_cuurency = 3; //固定为USDT + $number = $bind_box->margin; //保证金数量 + $users_wallet = UsersWallet::where('currency', $margin_cuurency)->where('user_id', $user_id)->first(); + if(!$users_wallet){ + return $this->error('UsersWallet does not exist'); + } + if($users_wallet->change_balance < $number){//余额不够扣除保证金 + return $this->error('Insufficient margin balance'); + } + + DB::beginTransaction(); + try{ + change_wallet_balance($users_wallet, 2, -$number, AccountLog::USER_BUY_MARGIN_NFT, '竞拍扣除保证金'); + $_bind_box_margin_log = new BindBoxMarginLog(); + $_bind_box_margin_log->user_id = $user_id; + $_bind_box_margin_log->code = $code; + $_bind_box_margin_log->number = $number; + $_bind_box_margin_log->currency_id = $cuurency; + $_bind_box_margin_log->status = 1; + $_bind_box_margin_log->created = date('Y-m-d H:i:s',time()); + $_bind_box_margin_log->save(); + + BindBoxQuotationLog::where('code',$code)->update(['status'=>0]);//将其他记录更改为失效 + BindBoxQuotationLog::where('code',$code)->where('buyer_id',$user_id)->update(['is_expired'=>1]); + $bind_box_quotation_log = new BindBoxQuotationLog(); + $bind_box_quotation_log->code = $code; + $bind_box_quotation_log->buyer_id = $user_id; + $bind_box_quotation_log->margin_log_id = $_bind_box_margin_log->id; + $bind_box_quotation_log->status = 1; + $bind_box_quotation_log->price = $new_price; + $bind_box_quotation_log->currency_id = $cuurency; + $bind_box_quotation_log->created = date('Y-m-d H:i:s',time()); + $bind_box_quotation_log->save(); + + $bind_box->price = $new_price; //更新NFT最新价格 + $bind_box->save(); + + DB::commit(); + return $this->success('successful'); + } catch (\Throwable $th) { + DB::rollBack(); + return $this->error($th); + } + }else{ + BindBoxQuotationLog::where('code',$code)->update(['status'=>0]);//将其他记录更改为失效 + BindBoxQuotationLog::where('code',$code)->where('buyer_id',$user_id)->update(['is_expired'=>1]); + $bind_box_quotation_log = new BindBoxQuotationLog(); + $bind_box_quotation_log->code = $code; + $bind_box_quotation_log->buyer_id = $user_id; + $bind_box_quotation_log->margin_log_id = $bind_box_margin_log->id; + $bind_box_quotation_log->status = 1; + $bind_box_quotation_log->price = $new_price; + $bind_box_quotation_log->currency_id = $cuurency; + $bind_box_quotation_log->created = date('Y-m-d H:i:s',time()); + $bind_box_quotation_log->save(); + + $bind_box->price = $new_price; //更新NFT最新价格 + $bind_box->save(); + return $this->success('successful'); + } + } + + + //获取商品出价记录 + public function getBindBoxQuotationLog(Request $request){ + $code = $request->post('code'); + if(!$code){ + return $this->error('error'); + } + $bind_box_quotation_logs = BindBoxQuotationLog::where('code',$code)->where('is_expired',0)->orderBy('id','DESC')->limit(10)->get(); + + return $this->success($bind_box_quotation_logs); + } + + //获取我的NFT + public function getMyNFTs(Request $request){ + $user_id = Users::getUserId(); + $bind_box = BindBox::where('owner',$user_id)->orderBy('id','DESC')->get(); + return $this->success($bind_box); + } + + //获取我的出价记录 + public function getMyBindBoxQuotationLog(Request $request){ + $user_id = Users::getUserId(); + $limit = $request->post('limit', 10); + + $bind_box = new BindBoxQuotationLog(); + $bind_box = $bind_box->where('buyer_id', $user_id)->where('is_expired', 0)->orderBy('id', 'DESC')->paginate($limit); + return $this->success(['code' => 0, 'data' => $bind_box->items(), 'count' => $bind_box->total()]); + + } + + + //开启盲盒 + public function openBlindBox(Request $request){ + $user_id = Users::getUserId(); + $code = $request->post('code'); + + $bind_box = BindBox::where(['code'=>$code,'pay_type'=>3,'owner'=>$user_id,'rarity_status'=>0])->first(); + + if(!$bind_box){ + return $this->error('The blind box does not exist or the blind box is opened!');//盲盒不存在或者盲盒已开启 + } + + $rarity_house = BindBoxRaityHouse::where('id',$bind_box->rarity_house_id)->first(); + + $bind_box->rarity_status = 1;//将状态改成已开启 + $bind_box->image = $rarity_house->file; + $bind_box->save(); + + return $this->success($bind_box); + } + + // 转卖 + public function resellNFT(Request $request){ + $redis = RedisService::getInstance(5); + $user_id = Users::getUserId(); + $code = $request->post('code'); + $bind_box = BindBox::where('code',$code)->first(); + if(!$bind_box){ + return $this->error("NFT does not exist!"); + } + + if($bind_box->owner != $user_id){ + return $this->error("Wrong operation!"); + } + + if($bind_box->resell_nft_status == 1){//转卖中 + return $this->error("Cannot be modified during auction!"); + } + + $price = $request->post('price'); + $start_time = $request->post('start_time'); + $end_time = $request->post('end_time'); + $per_increase = $request->post('per_increase'); + + if(!$start_time || !$end_time || !$price){ + return $this->error("Can not be empty!"); + } + if( strtotime($start_time) < time() ){ + return $this->error("The start time cannot be less than the current time!"); + } + if( strtotime($start_time) < strtotime($end_time) ){ + return $this->error("The start time cannot be less than the end_time!"); + } + if($redis->get('resellNFT'.$code)){ + return $this->error('The operation is too fast, please wait!'); + } + $redis->set('resellNFT' . $code, 1, 1); //限制点击频率 + if($bind_box->pay_type == 2 && $bind_box->lock_order == 1){//未超时的前提下 拍到此商品的买家未付款 + return $this->error("Not for resale!"); + } + + $bind_box->price = $price; + $bind_box->start_time = $start_time; + $bind_box->end_time = $end_time; + if($bind_box->pay_type == 2 && $per_increase){//竞拍 + $bind_box->per_increase = $per_increase; + } + $bind_box->status = 1; + $bind_box->resell_nft_status = 1; //转卖中 + $bind_box->updated = date('Y-m-d H:i:s',time()); + $bind_box->save(); + + return $this->success("Successful"); + + } + + //获取需要支付的订单 + public function getNeedPayNFTOrder(Request $request){ + $user_id = Users::getUserId(); + $bind_box_success_order = BindBoxSuccessOrder::where(['user_id'=>$user_id,])->get(); + + return $this->success($bind_box_success_order); + } + + //支付订单 + public function payNFTOrder(Request $request){ + $user_id = Users::getUserId(); + $id = $request->post('id'); + $order = BindBoxSuccessOrder::where('id',$id)->where('user_id',$user_id)->where('overtime','>',0)->where('is_expired',0)->first(); + + if(!$order){ + return $this->error("Order does not exist!"); + } + + $quotrtion_log = BindBoxQuotationLog::where('id',$order->quotrtion_log_id)->first(); + if(!$quotrtion_log){ + return $this->error("Quotation Log does not exist!"); + } + $margin_log = BindBoxMarginLog::where('id',$quotrtion_log->margin_log_id)->first(); + $users_wallet = UsersWallet::where('currency', $order->currency_id)->where('user_id', $user_id)->first(); //支付钱包 + if(!$margin_log){ + return $this->error('UsersWallet does not exist!'); + } + $users_margin_wallet = UsersWallet::where('currency', $margin_log->currency_id)->where('user_id', $user_id)->first(); //保证金钱包 + + + if(!$users_wallet){ + return $this->error('UsersWallet does not exist'); + } + + if($users_wallet->change_balance < $quotrtion_log->price){ + return $this->error('Insufficient margin balance'); + } + if(Cache::has('payNFTOrder_'.$user_id)){ + return $this->error('Do not repeat the operation!'); + } + Cache::put('payNFTOrder_'.$user_id, 1, Carbon::now()->addSeconds(1)); + $code = $order->code; + DB::beginTransaction(); + try{ + change_wallet_balance($users_wallet, 2, -$quotrtion_log->price, AccountLog::USER_ORDER_PAY_NFT, '竞拍支付'); + $order->is_pay =1; + $order->is_expired =1; + $order->pay_time = time(); + $order->overtime = 0; + $order->save(); + + change_wallet_balance($users_margin_wallet, 2, $margin_log->number, AccountLog::USER_RETURN_MARGIN_NFT, '退还保证金'); + BindBox::where('code',$code)->update(['resell_nft_status'=>0,'status'=>0,'owner'=>$user_id,'lock_order'=>0]); //nft拍卖结束 + $margin_log->status =0; + $margin_log->save(); + + DB::commit(); + return $this->success('successful'); + } catch (\Throwable $th) { + DB::rollBack(); + return $this->error('Failed'); + } + + + } + + public function readNFTOrderMessage(Request $request){ + $id = $request->post('id'); + + $order = BindBoxSuccessOrder::where('id',$id)->first(); + + if(!$order){ + return $this->error('Failed'); + } + if($order->is_read == 0){ + $order->is_read=1; + $order->save(); + } + return $this->success('successful'); + } + + public function test(){ + return; + $now = Carbon::now(); + // 拍卖已经结束 没有人出价的拍卖品 + $bind_boxs = BindBox::where('end_time','<=',$now)->where('pay_type',2)->get(); + foreach ($bind_boxs as $bind_box){ + $log = BindBoxQuotationLog::where('is_expired',0)->where('code',$bind_box->code)->first(); + if(!$log){ + $bind_box->status = 0; + $bind_box->resell_nft_status = 0; + $bind_box->save(); + } + } + + //拍卖结束 拍卖品有人出价 + $bind_box_quotation_logs = DB::table('bind_box_quotation_log') + ->leftjoin('bind_box_margin_log', 'bind_box_margin_log.id', '=', 'bind_box_quotation_log.margin_log_id') + ->leftjoin('bind_box', 'bind_box.code', '=', 'bind_box_quotation_log.code') + ->where('bind_box.end_time','<=',$now) + ->where('bind_box.pay_type',2) + ->where('bind_box_quotation_log.is_expired',0) + ->select('bind_box_quotation_log.*')->distinct()->get(); + + foreach ($bind_box_quotation_logs as $bind_box_quotation_log){ + $quotation_log_id = $bind_box_quotation_log->id; + $status = $bind_box_quotation_log->status; //成交状态 + if($status == 1){ //拍到了 + echo '生成待支付订单_'.PHP_EOL; + $order = new BindBoxSuccessOrder(); + $order->code = $bind_box_quotation_log->code; + $order->quotrtion_log_id = $bind_box_quotation_log->id; + $order->user_id = $bind_box_quotation_log->buyer_id; + $order->currency_id = $bind_box_quotation_log->currency_id; + $order->is_read = 0; + $order->is_pay = 0; + $order->overtime = time() + 86400;//过期时间24小时 + $order->created = time(); + $order->save(); + + Db::table('bind_box_quotation_log')->where('id',$quotation_log_id)->update(['is_expired'=>1]); + }else{//未拍到 + $margin_log = BindBoxMarginLog::where('id',$bind_box_quotation_log->margin_log_id)->where('is_expired',0)->where('status',1)->first();//保证金交了未退 + if($margin_log){//退保证金 + $_currency = $margin_log->currency_id; + $number = $margin_log->number; + $users_wallet = UsersWallet::where('currency', $_currency)->where('user_id', $margin_log->user_id)->first(); + change_wallet_balance($users_wallet, 2, $number, AccountLog::USER_RETURN_MARGIN_NFT, '退还竞拍保证金'); + + $margin_log->is_expired = 1; + $margin_log->status = 0; + $margin_log->save(); + + Db::table('bind_box_quotation_log')->where('id',$quotation_log_id)->update(['is_expired'=>1]); + }else{ //未拍到 但是推过保证金了 + Db::table('bind_box_quotation_log')->where('id',$quotation_log_id)->update(['is_expired'=>1]); + } + + + } + + } + + + //超时处理 + $bind_box_success_orders = BindBoxSuccessOrder::where('overtime','<',time())->where('overtime','>',0)->where('is_expired',0)->where('is_pay',0)->get(); + foreach ($bind_box_success_orders as $bind_box_success_order){ + Db::table('bind_box')->where('code',$bind_box_success_order->code)->update(['status'=>0,'resell_nft_status'=>0]); //状态失效 + $bind_box_success_order->is_expired = 1; //订单已失效 + $bind_box_success_order->overtime = 0; + $bind_box_success_order->save(); + } + + echo '完成'; + + } + +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/Http/Controllers/Api/C2cDealController.php b/app/Http/Controllers/Api/C2cDealController.php new file mode 100644 index 0000000..b6430a9 --- /dev/null +++ b/app/Http/Controllers/Api/C2cDealController.php @@ -0,0 +1,992 @@ +get('id', null); + $userLegalDealCancel_time=Setting::getValueByKey("userLegalDealCancel_time")*60; + $result=C2cDeal::find($id); + + $time=time(); + $create_time=strtotime($result->create_time); +// var_dump($create_time+$userLegalDealCancel_time); var_dump($time);die; + if(($create_time+$userLegalDealCancel_time)<=$time) + { + $id =$result->id; + C2cDeal::cancelLegalDealById($id); + //取消订单数加一 + $aaaa=Users::find($result->user_id); + $aaaa->today_LegalDealCancel_num=$aaaa->today_LegalDealCancel_num+1; + $aaaa->LegalDealCancel_num__update_time=time(); + $aaaa->save(); + } + + } + + public function postSend(Request $request) + { + $type = $request->get('type', null); + $way = $request->get('way', null); + $price = $request->get('price', null); + $total_number = $request->get('total_number', null); + + $currency_id = $request->get('currency_id', null); + if (empty($type)) return $this->error('请选择需求类型'); + if (empty($way)) return $this->error('请选择交易方式'); + if (empty($price)) return $this->error('请填写单价'); + if (empty($total_number)) return $this->error('请填写数量'); + + if (empty($currency_id)) return $this->error('请选择币种'); + + if($price < 0 || $total_number <0){ + return $this->error('请输入正确的交易数量或价格'); + } + + DB::BeginTransaction(); + try { + + $user_id = Users::getUserId(); + //收款方式的判断 + $user_cash_info = UserCashInfo::where('user_id', $user_id)->first(); + if (!$user_cash_info) { + DB::rollback(); + return response()->json(['type'=>'997','message'=>$this->returnStr('您还没有设置收款信息')]); + } + + if ($type == 'buy') + { + $userLegalDealCancel=Setting::getValueByKey("userLegalDealCancel"); + $user_id = Users::getUserId(); + $user=Users::find($user_id); + if($user->today_LegalDealCancel_num>=$userLegalDealCancel) + { + return $this->error($this->returnStr('取消次数已超出').$userLegalDealCancel.$this->returnStr('次,明天再发布')); + } + } + + if ($type == 'sell') + { + + $wallet=UsersWallet::where('user_id',$user_id)->where('currency',$currency_id)->lockForUpdate()->first(); + if(empty($wallet)){ + return $this->error('用户钱包不存在'); + } + if($wallet->legal_balance < $total_number){ + return $this->error('对不起,您的钱包余额不足'); + } + // + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $wallet->legal_balance, + 'change' => -$total_number, + 'after' => bc_sub($wallet->legal_balance, $total_number, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 2, + 'wallet_id' => $wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $wallet->lock_legal_balance, + 'change' => $total_number, + 'after' => bc_add($wallet->lock_legal_balance, $total_number, 5), + ]; + + $wallet->legal_balance = bc_sub($wallet->legal_balance,$total_number,5); + + $wallet->lock_legal_balance = bc_add($wallet->lock_legal_balance,$total_number,5); + $wallet->save(); + AccountLog::insertLog( + [ + 'user_id' => $user_id, + 'value' => $total_number * -1, + 'info' => '用户发布c2c交易法币出售,扣除法币余额', + 'type' => AccountLog::C2C_DEAL_SEND_SELL, + 'currency' => $currency_id + ], + $data_wallet1 + ); + AccountLog::insertLog( + [ + 'user_id' => $user_id, + 'value' => $total_number, + 'info' => '用户发布c2c交易法币出售,锁定余额增加', + 'type' => AccountLog::C2C_DEAL_SEND_SELL, + 'currency' => $currency_id + ], + $data_wallet2 + ); + } + + $legal_deal_send = new C2cDealSend(); + $legal_deal_send->seller_id = $user_id; + $legal_deal_send->currency_id = $currency_id; + $legal_deal_send->type = $type; + $legal_deal_send->way = $way; + $legal_deal_send->price = $price; + $legal_deal_send->total_number = $total_number; + $legal_deal_send->surplus_number = $total_number; + $legal_deal_send->create_time = time(); + $legal_deal_send->save(); + DB::commit(); + return $this->success('发布成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + + + } + + public function sellerInfo(Request $request) + { + $id = $request->get('id', null); + $type = $request->get('type',null); + $was_done = $request->get('was_done','false'); + $limit = $request->get('limit', 10); + + if (empty($id)) return $this->error('参数错误'); + $seller = Users::find($id); + if (empty($seller)) return $this->error('无此用户'); + $beforeThirtyDays = Carbon::today()->subDay(30)->timestamp; + $results = Users::withCount(['legalDeal as total', 'legalDeal as done' => function ($query) { + $query->where('is_sure', 1); + }, 'legalDeal as thirtyDays' => function ($query) use ($beforeThirtyDays) { + $query->where('is_sure', 1)->where('update_time', '>=', $beforeThirtyDays); + }])->find($id); + $lists = C2cDealSend::where('seller_id', $id); + + if($was_done == 'true'){ + $lists = $lists->where('is_done','=','1'); + }elseif($was_done == 'false'){ + $lists = $lists->where('is_done','=','0'); + } + + if($type == 'buy'){ + $type = 'buy'; + $lists = $lists->where('type',$type); + }elseif($type == 'sell'){ + $type = 'sell'; + $lists = $lists->where('type',$type); + } + + $lists = $lists->orderBy('id', 'desc')->paginate($limit); + $results->lists = array('data' => $lists->items(), 'page' => $lists->currentPage(), 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($results); + } + + + public function tradeList(Request $request) + { + $currency_id = $request->get('currency_id',null); + $type = $request->get('type',null); + + $limit = $request->get('limit', 10); + $id = Users::getUserId(); + $user=Users::find($id); + // $seller = Seller::where('user_id', $id)->first(); + + if (empty($user)) { + return $this->error('用户不存在'); + } + $lists = C2cDealSend::where('seller_id', $id)->where('is_done','<',2); + //是否完成 + // if ($was_done == 'true') { + // $lists = $lists->where('is_done','=','1'); + // } elseif ($was_done == 'false') { + // $lists = $lists->where('is_done','=','0'); + // } + //出售还是购买 + if($type == 'buy') { + $type = 'buy'; + $lists = $lists->where('type', $type); + } elseif ($type == 'sell') { + $type = 'sell'; + $lists = $lists->where('type', $type); + } + if($currency_id){ + $lists = $lists->where('currency_id', $currency_id); + } + $lists = $lists->whereDoesntHave('legalDeal',function($query){ + $query->where('is_sure','=',1); + }); + + $lists = $lists->orderBy('id', 'desc')->paginate($limit); + $result = array('data' => $lists->items(), 'page' => $lists->currentPage(), 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + + + public function legalDealPlatform(Request $request) + { + $limit = $request->get('limit', 10); + $currency_id = $request->get('currency_id', ''); + $type = $request->get('type', 'sell'); + if (empty($currency_id)) return $this->error('参数错误'); + if (empty($type)) return $this->error('参数错误2'); + $currency = Currency::find($currency_id); + if (empty($currency)) return $this->error('无此币种'); + if (empty($currency->is_legal)) return $this->error('该币不是法币'); + + $results = C2cDealSend::where('currency_id', $currency_id)->where('is_done', 0)->where('type', $type)->orderBy('id', 'desc')->paginate($limit); + return $this->pageData($results); + } + public function legalDealSendInfo(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) { + return $this->error('参数错误'); + } + $legal_deal_send = C2cDealSend::find($id); + if (empty($legal_deal_send)) return $this->error('无此记录'); + // $legal_deal_send['sell_cash_info'] = UserCashInfo::where('user_id',$legal_deal_send)->first(); + return $this->success($legal_deal_send); + } + + public function doDeal(Request $request) + { + $deal_send_id = $request->get('id', null); + // $value = $request->get('value', 0); + // $means = $request->get('means', ''); + if (empty($deal_send_id)) { + return $this->error('参数错误'); + } + $user_id = Users::getUserId(); + + $user_real = UserReal::where('user_id', $user_id) + ->where('review_status', 2) + ->first(); + if (!$user_real) { + return response()->json(['type'=>'998','message'=>$this->returnStr('您还没有通过实名认证')]); + } + + $user_cash_info = UserCashInfo::where('user_id', $user_id)->first(); + if (!$user_cash_info) { + return response()->json(['type'=>'997','message'=>$this->returnStr('您还没有设置收款信息')]); + } + + DB::beginTransaction(); + try { + + $legal_deal_send = C2cDealSend::lockForUpdate()->find($deal_send_id); + if (empty($legal_deal_send)) { + DB::rollback(); + return $this->error('无此记录'); + } + if (!empty($legal_deal_send->is_done)) { + DB::rollback(); + return $this->error('此条交易已完成'); + } + $money = bc_mul($legal_deal_send->total_number, $legal_deal_send->price, 6); + $number=$legal_deal_send->total_number; + $seller =Users::find($legal_deal_send->seller_id); + if (empty($seller)) { + DB::rollback(); + return $this->error('未找到该发布用户'); + } + if ($user_id == $seller->id) { + DB::rollback(); + return $this->error('不能操作自己的'); + } + $users_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $legal_deal_send->currency_id)->first(); + if (empty($users_wallet)) { + DB::rollback(); + return $this->error('您无此钱包账号'); + } + if (!empty($users_wallet->status)) { + DB::rollback(); + return $this->error('您的钱包已被锁定,请联系管理员'); + } + $hasNonDone = C2cDeal::where([ + ['user_id' , '=' , $user_id], + ])->whereIn('is_sure', [0,3])->first(); + if(!empty($hasNonDone)){ + DB::rollBack(); + return $this->error('检测有未完成交易,请完成后再来!'); + } + if ($legal_deal_send->type == 'buy') { //求购 + // do something + if ($users_wallet->legal_balance < $number) { + DB::rollback(); + return $this->error('您的余额不足'); + } + if ($users_wallet->lock_legal_balance < 0) { + DB::rollback(); + return $this->error('您的法币锁定资金异常,请查看您是否有正在进行的挂单'); + } + $legal_deal_send->is_done = 1; + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $users_wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $users_wallet->legal_balance, + 'change' => -$number, + 'after' => bc_sub($users_wallet->legal_balance, $number, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 2, + 'wallet_id' => $users_wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $users_wallet->lock_legal_balance, + 'change' => $number, + 'after' => bc_add($users_wallet->lock_legal_balance, $number, 5), + ]; +// $users_wallet->legal_balance -= $number; + $users_wallet->legal_balance = bc_sub($users_wallet->legal_balance,$number,5); +// $users_wallet->lock_legal_balance += $number; + $users_wallet->lock_legal_balance = bc_add($users_wallet->lock_legal_balance,$number,5); + $users_wallet->save(); + $legal_deal_send->save(); + AccountLog::insertLog( + [ + 'user_id' => $user_id, + 'value' => $number * -1, + 'info' => '出售给商家法币,余额减少', + 'type' => AccountLog::C2C_DEAL_USER_SELL, + 'currency' => $legal_deal_send->currency_id + ], + $data_wallet1 + ); + AccountLog::insertLog( + [ + 'user_id' => $user_id, + 'value' => $number, + 'info' => '出售给商家法币,锁定余额增加', + 'type' => AccountLog::C2C_DEAL_USER_SELL, + 'currency' => $legal_deal_send->currency_id + ], + $data_wallet2 + ); + + } elseif ($legal_deal_send->type == 'sell') { + $legal_deal_send->is_done = 1; + $legal_deal_send->save(); + } + + $legal_deal = new C2cDeal(); + $legal_deal->legal_deal_send_id = $deal_send_id; + $legal_deal->user_id = $user_id; + $legal_deal->seller_id = $seller->id; + $legal_deal->number = $number; //交易数量 + $legal_deal->create_time = time(); + $legal_deal->save(); +// var_dump(66666666);die; + if ($legal_deal_send->type == 'buy'){ + Setting::sendSmsForSmsBao($seller->account_number,'您发布的求购信息有用户出售啦,请去 APP 查看吧~'); + }else{ + Setting::sendSmsForSmsBao($seller->account_number,'您发布的出售信息有用户购买啦,请去 APP 查看吧~'); + } +// var_dump(11124);die; + DB::commit(); + return $this->success([ + 'msg' => '操作成功,请联系商家确认订单', + 'data' => $legal_deal, + ]); + + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage() . $this->returnStr(',错误位于第') . $exception->getLine() . $this->returnStr(',行')); + } + } + + /** + * 法币交易商家端列表 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function sellerLegalDealList(Request $request) + { + + //该天总取消次数是否归零 + $user_id = Users::getUserId(); + $user=Users::find($user_id); + $lingchen=strtotime(date('Y-m-d')); +// var_dump($lingchen);die; + if($user->LegalDealCancel_num__update_time<$lingchen) + { + $user->LegalDealCancel_num__update_time=time(); + $user->today_LegalDealCancel_num=0; + $user->save(); + } + + $limit = $request->get('limit', 10); + $type = $request->get('type', ''); + $currency_id = $request->get('currency_id', ''); + + if (empty($currency_id)) { + return $this->error('参数错误'); + } + + $currency = Currency::find($currency_id); + if (empty($currency)) { + return $this->error('无此币种'); + } + if (empty($currency->is_legal)) { + return $this->error('该币不是法币'); + } + $user_id = Users::getUserId(); + $seller=Users::find($user_id); + if(empty($seller)){ + return $this->error('用户信息不正确'); + } + + $results = C2cDeal::where('seller_id', $seller->id); + if (!empty($type)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($type) { + $query->where('type', $type); + }); + } + + if (!empty($currency_id)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }); + } + $results =$results->where('is_sure',1)->orderBy('id', 'desc')->paginate($limit); + return $this->pageData($results); + + } + + /** + * 法币交易用户端列表 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function userLegalDealList(Request $request) + { + $limit = $request->get('limit', 10); + $type = $request->get('type', null); + $currency_id = $request->get('currency_id', ''); + $is_sure = $request->get('is_sure', null); + + if (!empty($currency_id)) { + $currency = Currency::find($currency_id); + if (empty($currency)) return $this->error('无此币种'); + if (empty($currency->is_legal)) return $this->error('该币不是法币'); + } + + $user_id = Users::getUserId(); + + $results = C2cDeal::where('user_id', $user_id)->whereHas('legalDealSend'); + if (!empty($type)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($type) { + $query->where('type', $type); + }); + } + + if (!empty($currency_id)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }); + } + + if (!is_null($is_sure)) { + $results = $results->where('is_sure', $is_sure); + } + $results = $results->orderBy('id', 'desc')->paginate($limit); + return $this->pageData($results); + } + + /** + * 订单详情页 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function legalDealInfo(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) { + return $this->error('参数错误'); + } + $legal_deal = C2cDeal::find($id); + if (empty($legal_deal)) { + return $this->error('无此记录'); + } + return $this->success($legal_deal); + } + + /** + * 用户确认支付 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function userLegalDealPay(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + $legal_deal = C2cDeal::find($id); + if (empty($legal_deal)) { + return $this->error('无此记录'); + } + DB::beginTransaction(); + try { + if ($legal_deal->is_sure > 0) { + DB::rollback(); + return $this->error('该订单已操作过,请勿重复操作'); + } + $user_id = Users::getUserId(); + if ($legal_deal->type == 'sell') { //用户端-购买 + if ($user_id != $legal_deal->user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + } elseif ($legal_deal->type == 'buy') { + //?? + // $seller = Seller::find($legal_deal->seller_id); + // if ($user_id != $seller->user_id) { + // DB::rollback(); + // return $this->error('对不起,您无权操作'); + // } + $seller = Users::find($legal_deal->seller_id); + if ($user_id != $seller->id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + + } + $legal_deal->is_sure = 3; + $legal_deal->save(); + DB::commit(); + return $this->success('操作成功,请联系卖家确认'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + + public function handle() + { + $userLegalDealCancel_time=Setting::getValueByKey("userLegalDealCancel_time")*60; + $result=LegalDeal::where("is_sure",0)->get();//0未确认 1已确认 2已取消 3已付款 + foreach($result as $key=>$value) + { + $time=time(); + $create_time=strtotime($value->create_time); +// var_dump($create_time+$userLegalDealCancel_time); var_dump($time);die; + if(($create_time+$userLegalDealCancel_time)<=$time) + { + $id =$value->id; + DB::beginTransaction(); + try { + LegalDeal::cancelLegalDealById($id); + DB::commit(); + + //取消订单数加一 + $aaaa=Users::find($value->user_id); + $aaaa->today_LegalDealCancel_num=$aaaa->today_LegalDealCancel_num+1; + $aaaa->save(); + + return $this->success('操作成功,订单已取消'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + } + } + + + /** + * 用户取消订单 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function userLegalDealCancel(Request $request) + { + $userLegalDealCancel=Setting::getValueByKey("userLegalDealCancel"); + //获取今天已经取消的次数 + $user_id = Users::getUserId(); + $user=Users::find($user_id); + if($user->today_LegalDealCancel_num>=$userLegalDealCancel) + { + return $this->error($this->returnStr('您今天的取消次数已超出').$userLegalDealCancel.$this->returnStr('次')); + } + else + { + $user->today_LegalDealCancel_num=$user->today_LegalDealCancel_num+1; + $user->save(); + } + + + $id = $request->get('id', null); + if (empty($id)) { + return $this->error('参数错误'); + } + $legal_deal = C2cDeal::find($id); + if (empty($legal_deal)) { + return $this->error('无此记录'); + } + DB::beginTransaction(); + try { + if ($legal_deal->is_sure > 0) { + DB::rollback(); + return $this->error('该订单已操作,请勿取消'); + } + $user_id = Users::getUserId(); + if ($legal_deal->type == 'sell') { //用户端-购买 + if ($user_id != $legal_deal->user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + } elseif ($legal_deal->type == 'buy') {//用户端出售 + + + if ($user_id != $legal_deal->seller_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + + + } + + C2cDeal::cancelLegalDealById($id); + DB::commit(); + return $this->success('操作成功,订单已取消'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + + public function legalDealSellerList(Request $request) + { + $limit = $request->get('limit', 10); + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + $legal_send = C2cDealSend::find($id); + if (empty($legal_send)) { + return $this->error('参数错误2'); + } + $user_id=Users::getUserId(); + if($user_id !=$legal_send->seller_id){ + return $this->error('对不起,这不是您的发布信息'); + } + + $results = C2cDeal::where('legal_deal_send_id', $id) + ->orderBy('id', 'desc') + ->paginate($limit); + return $this->pageData($results); + } + + public function doSure(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + DB::beginTransaction(); + try { + $legal_deal = C2cDeal::find($id); + if (empty($legal_deal)) { + DB::rollback(); + return $this->error('无此记录'); + } + if ($legal_deal->is_sure != 3) { + DB::rollback(); + return $this->error('该订单还未付款或已经操作过'); + } + $user_id=Users::getUserId(); + $user=Users::find($user_id); + if($user_id !=$legal_deal->seller_id){ + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + + $legal_send = C2cDealSend::find($legal_deal->legal_deal_send_id); + if (empty($legal_send)) { + DB::rollback(); + return $this->error('订单异常'); + } + if ($legal_send->type == 'buy') { + DB::rollback(); + return $this->error('您不能确认该订单'); + } + $user_wallet = UsersWallet::where('user_id', $legal_deal->user_id)->where('currency', $legal_send->currency_id)->first(); + if (empty($user_wallet)) { + DB::rollback(); + return $this->error('该用户没有此币种钱包'); + } + $from_wallet = UsersWallet::where('user_id', $legal_deal->seller_id)->where('currency', $legal_send->currency_id)->first(); + if (empty($from_wallet)) { + DB::rollback(); + return $this->error('该用户没有此币种钱包'); + } + + $data_wallet1 = [ + 'balance_type' =>2 , + 'wallet_id' => $from_wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $from_wallet->lock_legal_balance, + 'change' => -$legal_deal->number, + 'after' => bc_sub($from_wallet->lock_legal_balance,$legal_deal->number,5), + ]; + $data_wallet2 = [ + 'balance_type' =>2 , + 'wallet_id' => $user_wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_wallet->legal_balance, + 'change' => $legal_deal->number, + 'after' => bc_add($user_wallet->legal_balance, $legal_deal->number, 5), + ]; + $legal_deal->is_sure = 1; + $legal_deal->update_time = time(); + $from_wallet->lock_legal_balance=bc_sub($from_wallet->lock_legal_balance,$legal_deal->number,5); + $user_wallet->legal_balance = bc_add($user_wallet->legal_balance,$legal_deal->number,5); + AccountLog::insertLog( + [ + 'user_id' => $from_wallet->user_id, + 'value' => $legal_deal->number * (-1), + 'info' => '出售法币成功,扣除锁定余额', + 'type' => AccountLog::C2C_USER_BUY, + 'currency' => $legal_send->currency_id + ], + $data_wallet1 + ); + AccountLog::insertLog( + [ + 'user_id' => $user_wallet->user_id, + 'value' => $legal_deal->number, + 'info' => $this->returnStr('在 ') . $user->account_number . $this->returnStr('购买法币成功,增加法币余额'), + 'type' => AccountLog::C2C_USER_BUY, + 'currency' => $legal_send->currency_id + ], + $data_wallet2 + ); + + $legal_deal->save(); + //$seller->save(); + $from_wallet->save(); + $user_wallet->save(); + DB::commit(); + return $this->success('确认成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + public function userDoSure(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + DB::beginTransaction(); + try { + $legal_deal = C2cDeal::find($id); + if (empty($legal_deal)) { + DB::rollback(); + return $this->error('无此记录'); + } + if ($legal_deal->is_sure != 3) { + DB::rollback(); + return $this->error('该订单还未付款或已经操作过'); + } + $user_id = Users::getUserId(); + $user = Users::find($user_id); + if ($legal_deal->user_id != $user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + $legal_send = C2cDealSend::find($legal_deal->legal_deal_send_id); + if (empty($legal_send)) { + DB::rollback(); + return $this->error('订单异常'); + } + if ($legal_send->type == 'sell') { + DB::rollback(); + return $this->error('您不能确认该订单'); + } + $user_wallet = UsersWallet::where('user_id', $legal_deal->user_id) + ->where('currency', $legal_send->currency_id) + ->first(); + if (empty($user_wallet)) { + DB::rollback(); + return $this->error('该用户没有此币种钱包'); + } + + $seller=Users::find($legal_deal->seller_id); + $seller_wallet = UsersWallet::where('user_id', $legal_deal->seller_id) + ->where('currency', $legal_send->currency_id) + ->first(); + if (empty($seller_wallet)) { + DB::rollback(); + return $this->error('该买家没有此币种钱包'); + } + + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $user_wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_wallet->lock_legal_balance, + 'change' => -$legal_deal->number, + 'after' => bc_sub($user_wallet->lock_legal_balance, $legal_deal->number, 5), + ]; + $data_wallet2 = [ + 'balance_type' =>2, + 'wallet_id' => $seller_wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $seller_wallet->legal_balance, + 'change' => $legal_deal->number, + 'after' => bc_add($seller_wallet->legal_balance,$legal_deal->number,5), + ]; + $legal_deal->is_sure = 1; + $legal_deal->update_time = time(); + + $user_wallet->lock_legal_balance = bc_sub($user_wallet->lock_legal_balance,$legal_deal->number,5); + + $seller_wallet->legal_balance = bc_add($seller_wallet->legal_balance,$legal_deal->number,5); + AccountLog::insertLog( + [ + 'user_id' => $user->id, + 'value' =>-$legal_deal->number, + 'info' => $user->account_number . '卖出法币成功', + 'type' => AccountLog::LEGAL_SELLER_BUY, + 'currency' => $legal_send->currency_id + ], + $data_wallet1 + ); + AccountLog::insertLog( + [ + 'user_id' => $seller->id, + 'value' => $legal_deal->number, + 'info' => $seller->account_number . ' 购买法币成功', + 'type' => AccountLog::LEGAL_SELLER_BUY, + 'currency' => $legal_send->currency_id + ], + $data_wallet2 + ); + + $legal_deal->save(); + $seller_wallet->save(); + $user_wallet->save(); + DB::commit(); + return $this->success('确认成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + public function backSend(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + DB::beginTransaction(); + try { + $legal_send = C2cDealSend::lockForUpdate()->find($id); + if (empty($legal_send)) { + DB::rollback(); + return $this->error('无此记录'); + } + $is_deal = C2cDeal::where('legal_deal_send_id', $id)->where('is_sure','>',2)->first(); + return $is_deal; + if (!empty($is_deal)) { + DB::rollback(); + return $this->error('该发布信息下有交易产生无法删除'); + } + $user_id = Users::getUserId(); + if($user_id !=$legal_send->seller_id){ + DB::rollback(); + return $this->error('对不起,您无权撤销此记录'); + } + + + if ($legal_send->type == 'sell') { + $wallet=UsersWallet::where('user_id',$user_id)->where('currency',$legal_send->currency_id)->first(); + if(empty($wallet)){ + DB::rollback(); + return $this->error('用户钱包不存在'); + + } + if($wallet->lock_legal_balance < $legal_send->total_number){ + DB::rollback(); + return $this->error('对不起,您的账户锁定资金不足'); + } + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $wallet->legal_balance, + 'change' => $legal_send->total_number, + 'after' => bc_add($wallet->legal_balance, $legal_send->total_number, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 2, + 'wallet_id' => $wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $wallet->lock_legal_balance, + 'change' => -$legal_send->total_number, + 'after' => bc_sub($wallet->lock_legal_balance, $legal_send->total_number, 5), + ]; + + $wallet->legal_balance = bc_add($wallet->legal_balance, $legal_send->total_number, 5); + + $wallet->lock_legal_balance = bc_sub($wallet->lock_legal_balance, $legal_send->total_number, 5); + $wallet->save(); + // AccountLog::insertLog(['user_id' => $user_id, 'value' => $total_number * -1, 'info' => '用户发布c2c交易法币出售,扣除法币余额', 'type' => AccountLog::C2C_DEAL_SEND_SELL, 'currency' => $currency_id]); + AccountLog::insertLog( + [ + 'user_id' => $user_id, + 'value' => $legal_send->total_number, + 'info' => '商家撤回发布法币出售', + 'type' => AccountLog::C2C_DEAL_BACK_SEND_SELL, + 'currency' => $legal_send->currency_id + ], + $data_wallet1 + ); + AccountLog::insertLog( + [ + 'user_id' => $user_id, + 'value' => -$legal_send->total_number, + 'info' => '商家撤回发布法币出售', + 'type' => AccountLog::C2C_DEAL_BACK_SEND_SELL, + 'currency' => $legal_send->currency_id + ], + $data_wallet2 + ); + + } + + $legal_send->delete(); + C2cDeal::where('legal_deal_send_id', $id)->delete(); + + DB::commit(); + return $this->success('撤回成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + +} diff --git a/app/Http/Controllers/Api/CandyTransferController.php b/app/Http/Controllers/Api/CandyTransferController.php new file mode 100644 index 0000000..842a90a --- /dev/null +++ b/app/Http/Controllers/Api/CandyTransferController.php @@ -0,0 +1,973 @@ +first()->candy_number; + $result['transfer_candy_rate']=Setting::getValueByKey("transfer_candy_rate"); + return $this->success($result); + } + + public function transfer_candy() + { + $baifen_transfer_candy_rate= Setting::getValueByKey('transfer_candy_rate'); + $transfer_candy_min= Setting::getValueByKey('transfer_candy_min'); + $transfer_candy_max= Setting::getValueByKey('transfer_candy_max'); + $transfer_candy_rate = bc_div($baifen_transfer_candy_rate, 100); + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $candy_number = Input::get('candy_number'); + $account_number = Input::get('mobile'); + $to_user=Users::where("account_number","=",$account_number)->first(); + $transfer_fee=bc_mul($candy_number,$transfer_candy_rate,6);//手续费 + + if (empty($candy_number) || $candy_number <= 0) { + return $this->error('参数错误!'); + } + if (empty($to_user->account_number)) { + return $this->error('转账账户不存在!'); + } + if ($to_user->account_number==$user->account_number) { + return $this->error('不能给自己转账!'); + } + + if ($candy_number > $user->candy_number ) { + return $this->error('转账数量大于剩余数量!'); + } + if ($candy_number > ($user->candy_number+$transfer_fee) ) { + return $this->error('余额不足!'); + } + if ($candy_number < $transfer_candy_min) { + return $this->error($this->returnStr('转账数量不能小于').$transfer_candy_min.'!'); + } + if ($candy_number > $transfer_candy_max) { + return $this->error($this->returnStr('转账数量不能大于').$transfer_candy_max.'!'); + } + DB::beginTransaction(); + try { + $aaa=bc_add($candy_number,$transfer_fee);//转账数量+手续费 + $user->candy_number=bc_sub($user->candy_number,$aaa,4);//减去 + $user->save(); + $to_user->candy_number=bc_add($to_user->candy_number,$candy_number,4);//加 + $to_user->save(); + + //记录转账记录 + $candy_transfer=new CandyTransfer(); + $candy_transfer->from_user_id=$user->id; + $candy_transfer->to_user_id=$to_user->id; + $candy_transfer->transfer_qty=$candy_number; + $candy_transfer->transfer_rate=$baifen_transfer_candy_rate; + $candy_transfer->transfer_fee=$transfer_fee; + $candy_transfer->create_time=time(); + $candy_transfer->save(); + +// var_dump(888888888);die; + + DB::commit(); + return $this->success('通证转账成功!'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function show_transfer_candylist() + { + $limit = Input::get('limit','10'); + $page = Input::get('page','1'); + $type= Input::get('type'); + $user_id = Users::getUserId(); + + if (empty($user_id)) { + return $this->error('参数错误'); + } + if($type=="in") + { + $result=CandyTransfer::where("to_user_id","=",$user_id)->orderBy("create_time","desc")->paginate($limit); + } + elseif(($type=="out")) + { + $result=CandyTransfer::where("from_user_id","=",$user_id)->orderBy("create_time","desc")->paginate($limit); + } +// var_dump($result);die; +// foreach($result as $key=>$value) +// { +// $result[$key]['create_time']=date("Y-m-d H:i:s",$value->create_time); +// } + + return $this->success(array( + "data"=>$result->items(), + "limit"=>$limit, + "page"=>$page, + )); +// return $this->success($result); + } + //设置法币交易账号密码 + public function setAccount() + { + $account = Input::get('account', ''); + $password = Input::get('password', ''); + $repassword = Input::get('repassword', ''); + if (empty($account) || empty($password) || empty($repassword)) { + return $this->error('必填项信息不完整'); + } + if ($password != $repassword) { + return $this->error('两次输入密码不一致'); + } + $user_id = Users::getUserId(); + $user = Users::find($user_id); + if (empty($user)) { + return $this->error('此用户不存在'); + } + if ($user->account_number) { + return $this->error('此交易账号已经设置'); + } + $res = Users::where('account_number', $account)->first(); + if ($res) { + return $this->error('此账号已经存在'); + } + try { + $user->account_number = $account; + $user->pay_password = Users::MakePassword($password, $user->type); + $user->save(); + return $this->success('交易账号设置成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function safeCenter() + { + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $safeInfo = array( + 'mobile' => $user->phone,//如果为空,未绑定 + 'email' => $user->email, + 'gesture_password' => $user->gesture_password, + ); + return $this->success($safeInfo); + } + public function setMobile() + { + $user_id = Users::getUserId(); + $mobile = Input::get('mobile', ''); + $code = Input::get('code', ''); + if (empty($user_id) || empty($mobile) || empty($code)) { + return $this->error('参数错误'); + } + if ($code != session('code')) { + return $this->error('验证码错误'); + } + try { + $user = Users::find($user_id); + $user->phone = $mobile; + $user->save(); + return $this->success('手机绑定成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + public function setEmail() + { + $user_id = Users::getUserId(); + $email = Input::get('email', ''); + $code = Input::get('code', ''); + if (empty($user_id) || empty($email) || empty($code)) { + return $this->error('参数错误'); + } + if ($code != session('code')) { + return $this->error('验证码错误'); + } + try { + $user = Users::find($user_id); + $user->email = $email; + $user->save(); + return $this->success('邮箱绑定成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function gesturePassAdd() + { + $password = Input::get('password', ''); + $re_password = Input::get('re_password', ''); + if (mb_strlen($password) < 6) { + return $this->error('手势密码至少连接6个点'); + } + if ($password != $re_password) { + return $this->error('两次手势密码不相同'); + } + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $user->gesture_password = $password; + try { + $user->save(); + return $this->success('手势密码添加成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function gesturePassDel() + { + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $user->gesture_password = ""; + try { + $user->save(); + return $this->success('取消手势密码成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function updatePayPassword() + { + + $password = Input::get('password', ''); + $re_password = Input::get('re_password', ''); + if (mb_strlen($password) < 6 || mb_strlen($password) > 16) { + return $this->error('密码只能在6-16位之间'); + } + if ($password != $re_password) { + return $this->error('两次密码不一致'); + } + $user_id = Users::getUserId(); + $user = Users::find($user_id); + + $user->pay_password = Users::MakePassword($password, $user->type); + try { + $user->save(); + return $this->success('交易密码设置成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function inviteList() + { + $time = Input::get('time', ''); + if ($time) { + $time = strtotime($time); + } else { + $time = 0; + } + + + $list = AccountLog::has('user') + ->select(DB::raw('sum(value) as total, user_id')) + ->where('type', AccountLog::INVITATION_TO_RETURN) + ->where('created_time', '>=', $time) + ->groupBy('user_id') + ->orderBy('total', 'desc') + + ->limit(20) + ->get() + ->toArray(); + + if (empty($list)) { + return $this->error("暂时还没有邀请排行榜,快去邀请吧"); + } + + + foreach ($list as $key => $val) { + + $user = Users::find($val['user_id']); + + + $list[$key]['account'] = $user->account; + + } + + return $this->success($list); + + + } + + + public function invite() + { + + $user_id = Users::getUserId(); + $user = Users::where("id", $user_id)->first(); + + if (empty($user)) { + return $this->error("会员未找到"); + } + $list = AccountLog::has('user') + ->select(DB::raw('sum(value) as total, user_id')) + ->where('type', AccountLog::INVITATION_TO_RETURN) + + ->groupBy('user_id') + ->orderBy('total', 'desc') + + ->limit(3) + ->get() + ->toArray(); + if (empty($list)) { + $list = []; + } else { + + foreach ($list as $key => $val) { + + $users = Users::find($val['user_id']); + + $list[$key]['account'] = $users->account; + + } + + + } + + $ad = []; + $ad['image'] = "/upload/invite.png"; + + $data = []; + $data['extension_code'] = $user['extension_code']; + $data['ad'] = $ad; + $data['inviteList'] = $list; + $num = Users::where('parent_id', $user_id)->count(); + + if ($num > 0) { + $data['invite_num'] = $num; + $total = AccountLog::where('user_id', $user_id)->where('type', AccountLog::INVITATION_TO_RETURN)->sum('value'); + $data['invite_return_total'] = $total; + } else { + $data['invite_num'] = 0; + $data['invite_return_total'] = 0; + } + + return $this->success($data); + + } + + + + + //钱包地址 + public function walletaddress() + { +// $user_id = Users::getUserId(); + $user_id = Input::get('user_id'); + $wallet_address = Input::get('wallet_address'); + + $usermyself = Users::where("id", $user_id)->first()->toArray(); + $user = Users::where("wallet_address", $wallet_address)->where("id", '!=', $user_id)->first(); + if ($usermyself['wallet_address']) { + return $this->error("你已绑定,不可更改!"); + } elseif (!empty($user)) { + return $this->error("该地址已被绑定,请重新输入"); + } else { + $pdo = new Users(); + $pdo->where("id", "=", $user_id)->update(['wallet_address' => $wallet_address]); + return $this->success('绑定成功!'); + } + } + + + + //我的 + public function info() + { + $user_id = Users::getUserId(); + //$user = Users::where("id",$user_id)->first(['id','phone','email','head_portrait','status']); + $user = Users::where("id", $user_id)->first(); + if (empty($user)) { + return $this->error("会员未找到"); + } + + //用户认证状况 + $res = UserReal::where('user_id', $user_id)->first(); + if (empty($res)) { + $user['review_status'] = 0; + $user['name'] = ''; + } else { + $user['review_status'] = $res['review_status']; + $user['name'] = $res['name']; + } + + return $this->success($user); + + + } + + //身份认证 + public function realName() + { + + $user_id = Users::getUserId(); + $name = Input::get("name", "");//真实姓名 + $card_id = Input::get("card_id", "");//身份证号 + $front_pic = Input::get("front_pic", "");//正面照片 + $reverse_pic = Input::get("reverse_pic", "");//反面照片 + $hand_pic = Input::get("hand_pic", "");//手持身份证照片 + + + + if (empty($name) || empty($card_id) || empty($front_pic) || empty($reverse_pic) || empty($hand_pic)) { + return $this->error("请提交完整的信息"); + } + + //校验 身份证号码合法性 + $idcheck = new IdCardIdentity(); + $res = $idcheck->check_id($card_id); + if (!$res) { + return $this->error("请输入合法的身份证号码"); + } + $user = Users::find($user_id); + + if (empty($user)) { + return $this->error("会员未找到"); + } + + $userreal_number=UserReal::where("card_id",$card_id)->count(); +// var_dump($userreal_number);die; + if($userreal_number>0) + { + return $this->error("该身份证号已实名认证过!"); + } + + $userreal = UserReal::where('user_id', $user_id)->first(); + if (!empty($userreal)) { + return $this->error("您已经申请过了"); + } + + try { + + $userreal = new UserReal(); + + $userreal->user_id = $user_id; + $userreal->name = $name; + $userreal->card_id = $card_id; + $userreal->create_time = time(); + $userreal->front_pic = $front_pic; + $userreal->reverse_pic = $reverse_pic; + $userreal->hand_pic = $hand_pic; + + $userreal->save(); + + return $this->success('提交成功,等待审核'); + } catch (\Exception $e) { + + return $this->error($e->getMessage()); + } + + + } + + + //个人中心 身份认证信息 + public function userCenter() + { + + $user_id = Users::getUserId(); + $user = Users::where("id", $user_id)->first(['id', 'phone', 'email']); + if (empty($user)) { + return $this->error("会员未找到"); + } + $userreal = UserReal::where('user_id', $user_id)->first(); + + if (empty($userreal)) { + $user['review_status'] = 0; + $user['name'] = ''; + $user['card_id'] = ''; + } else { + $user['review_status'] = $userreal['review_status']; + $user['name'] = $userreal['name']; + $user['card_id'] = $userreal['card_id']; + + } + + + + if (!empty($user['card_id'])) { + $user['card_id'] = mb_substr($user['card_id'], 0, 2) . '******' . mb_substr($user['card_id'], -2, 2); + } + return $this->success($user); + + + } + + //专属海报信息 + public function posterBg() + { + $user_id = Users::getUserId(); + $user = Users::where("id", $user_id)->first(['id', 'extension_code']); + if (empty($user)) { + return $this->error("会员未找到"); + } + $pics = InviteBg::all(['id', 'pic'])->toArray(); + + $data['extension_code'] = $user['extension_code']; + $data['share_url'] = Setting::getValueByKey('share_url', ''); + $data['pics'] = $pics; + + return $this->success($data); + + } + + //我的邀请分享 + public function share() + { + $user_id = Users::getUserId(); + $user = Users::where("id", $user_id)->first(['id', 'extension_code']); + if (empty($user)) { + return $this->error("会员未找到"); + } + + $data['share_title'] = Setting::getValueByKey('share_title', ''); + $data['share_content'] = Setting::getValueByKey('share_content', ''); + $data['share_url'] = Setting::getValueByKey('share_url', ''); + $data['extension_code'] = $user['extension_code']; + + return $this->success($data); + + } + + + //退出 + public function logout() + { + + $user_id = Users::getUserId(); + $user = Users::find($user_id); + + if (empty($user)) { + return $this->error("会员未找到"); + } + //清除用户的token session + session(['user_id' => '']); + $token = Token::getToken(); + //删除当前token + Token::deleteToken($user_id, $token); + + return $this->success('退出登录成功'); + + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + public function vip() + { + $user_id = Users::getUserId(Input::get("user_id")); + $password = Input::get('password', ''); + + + if (empty($password)) return $this->error("请输入支付密码"); + + $vip = Input::get("vip"); + if (empty($user_id) || empty($vip)) { + return $this->error("参数错误"); + } + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + if ($user->vip >= $vip) { + return $this->error("无需升级"); + } + if ($vip == "2") { + if ($user->vip == 1) { + $money = 9000; + } else { + $money = 9999; + } + } else { + $money = 999; + } + + $wallet = UsersWallet::where("user_id", $user_id) + ->where("token", Users::TOKEN_DEFAULT) + ->select("id", "user_id", "password", "address", "balance", "lock_balance", "remain_lock_balance", "create_time", "wallet_name", "password_prompt") + ->first(); + if (empty($wallet)) { + return $this->error("暂无钱包"); + } + if ($password != $wallet->password) { + return $this->error("支付密码错误"); + } + if ($wallet->balance < $money) { + return $this->error("余额不足"); + } + + $walletn = UsersWallet::find($wallet->id); + $data_wallet = [ + 'balance_type' => AccountLog::UPDATE_VIP, + 'wallet_id' => $walletn->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $walletn->balance, + 'change' => -$money, + 'after' => bc_sub($walletn->balance, $money, 5), + ]; + $user->vip = $vip; + $walletn->balance = $walletn->balance - $money; + $user->save(); + $walletn->save(); + AccountLog::insertLog( + array( + "user_id" => $user_id, + "value" => -$money, + "type" => AccountLog::UPDATE_VIP, + "info" => "升级会员" + ), + $data_wallet + ); + return $this->success("升级成功"); + } + + public function updateCurrencyAddress() + { + + } + public function updateAddress() + { + $address = Users::getUserId(); + + $eth_address = trim(Input::get('eth_address')); + if (empty($address) || empty($eth_address)) { + return $this->error('参数错误'); + } + $user = Users::find($address); + if (empty($user)) { + return $this->error('没有此用户'); + } + + if ($other = Users::where('eth_address', $eth_address)->first()) { + if ($other->id != $user->id) { + return $this->error('该地址别人已经绑定过了'); + } + } + try { + $user->eth_address = $eth_address; + $user->save(); + return $this->success('更新成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function getUserByAddress() + { + $user_id = Users::getUserId(); + if (empty($user_id)) + return $this->error("参数错误"); + $user = Users::where("id", $user_id)->first(); + if (empty($user)) { + return $this->error("会员未找到"); + } + if (empty($user->extension_code)) { + $user->extension_code = Users::getExtensionCode(); + $user->save(); + } + + $wallet = UsersWallet::where("user_id", $user_id) + ->where("token", Users::TOKEN_DEFAULT) + ->select("id", "user_id", "address", "balance", "lock_balance", "remain_lock_balance", "create_time", "wallet_name", "password_prompt") + ->first(); + $user->wallet = $wallet; + return $this->success($user); + } + public function chatlist() + { + $user_id = Users::getUserId(Input::get('user_id', '')); + if (empty($user_id)) return $this->error("参数错误"); + + $user = Users::find($user_id); + if (empty($user)) return $this->error("用户未找到"); + + $chat_list = UserChat::orderBy('id', 'DESC')->paginate(20); + + $datas = $chat_list->items(); + + krsort($datas); + $return = array(); + foreach ($datas as $d) { + array_push($return, $d); + } + return $this->success(array( + "user" => $user, + "chat_list" => [ + 'total' => $chat_list->total(), + 'per_page' => $chat_list->perPage(), + 'current_page' => $chat_list->currentPage(), + 'last_page' => $chat_list->lastPage(), + 'next_page_url' => $chat_list->nextPageUrl(), + 'prev_page_url' => $chat_list->previousPageUrl(), + 'from' => $chat_list->firstItem(), + 'to' => $chat_list->lastItem(), + 'data' => $return, + ] + )); + } + public function sendchat() + { + $user_id = Users::getUserId(Input::get('user_id', '')); + + $content = Input::get('content', ''); + if (empty($user_id) || empty($content)) return $this->error("参数错误"); + + $user = Users::find($user_id); + if (empty($user)) return $this->error("会员未找到"); + + $data["user_id"] = $user_id; + $data["user_name"] = $user->account_number; + $data["head_portrait"] = $user->head_portrait; + $data["content"] = $content; + $data["type"] = "1"; + + + try { + $res = UserChat::sendChat($data); + if ($res == "ok") { + $user_chat = new UserChat(); + $user_chat->from_user_id = $user_id; + $user_chat->to_user_id = 0; + $user_chat->content = $content; + $user_chat->type = 1; + $user_chat->add_time = time(); + $user_chat->save(); + return $this->success("ok"); + } else { + return $this->error("请重试"); + } + } catch (Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function into_users() + { + $password = Input::get('password', ''); + $account_number = Input::get('account_number', ''); + $pay_password = Input::get('pay_password', ''); + $parent_id = Input::get('parent_id', '');//邀请人账户 + if (empty($parent_id) || empty($pay_password) || empty($password) || empty($password)) { + return $this->error('请把参数填写完整'); + } + //判断用户是否存在 + $user = Users::getByAccountNumber($account_number); + if (!empty($user)) { + return $this->error('用户已存在'); + } + //判断推荐人是否存在 + $invit = Users::getByAccountNumber($parent_id); + if (empty($invit)) { + return $this->error('推荐用户不存在'); + } + + $users = new Users(); + $users->password = Users::MakePassword($password, 1); + $users->pay_password = Users::MakePassword($pay_password, 0); + $users->parent_id = $invit->id; + $users->account_number = $account_number; + $users->type = 1; + $users->head_portrait = URL("mobile/images/user_head.png"); + $users->time = time(); + $users->extension_code = Users::getExtensionCode(); + DB::beginTransaction(); + try { + $users->save();//保存到user表中 + $currency = Currency::all(); + $address_url = config('wallet_api') . $users->id; + $address = RPC::apihttp($address_url); + $address = @json_decode($address, true); + + foreach ($currency as $key => $value) { + $userWallet = new UsersWallet(); + $userWallet->user_id = $users->id; + if ($value->type == 'btc') { + $userWallet->address = $address["contentbtc"]; + } else { + $userWallet->address = $address["content"]; + } + $userWallet->currency = $value->id; + $userWallet->create_time = time(); + $userWallet->save();//默认生成所有币种的钱包 + } + DB::commit(); + return $this->success("注册成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + } + public function into_tra() + { + $account_number = Input::get('account_number', ''); + + $password = Input::get('password', ''); + $number = Input::get('number', ''); + $type = Input::get('type', '1'); + if (empty($account_number)) { + return $this->error('转入账户不能为空'); + } + if (empty($password)) { + return $this->error('密码不能为空'); + } + if (empty($number)) { + return $this->error('转入数量不能为空'); + } + $tra_user = Users::getByAccountNumber($account_number); + if (empty($tra_user)) { + return $this->error('用户未找到'); + } + if ($tra_user->password != Users::MakePassword($password, $tra_user->type)) { + return $this->error('用户密码错误'); + } + $currency = Currency::where('name', 'IMC')->first(); + $waller_info = UsersWallet::where('currency', $currency->id)->where('user_id', $tra_user->id)->first(); + DB::beginTransaction(); + $data_wallet = [ + 'wallet_id' => $waller_info->id, + 'lock_type' => 0, + 'create_time' => time(), + //'before' => 0, + 'change' => $number, + //'after' => 0, + ]; + try { + if ($type == 0) { + $data_wallet['balance_type'] = 1; + $data_wallet['before'] = $waller_info->legal_balance; + $data_wallet['after'] = bc_add($waller_info->legal_balance, $number, 5); + $waller_info->legal_balance = $waller_info->legal_balance + $number; + $info = '美丽链法币交易余额转入'; + $type_info = AccountLog::INTO_TRA_FB; + } else if ($type == 1) { + $data_wallet['balance_type'] = 2; + $data_wallet['before'] = $waller_info->change_balance; + $data_wallet['after'] = bc_add($waller_info->change_balance, $number, 5); + $waller_info->change_balance = $waller_info->change_balance + $number; + $info = '美丽链币币交易余额转入'; + $type_info = AccountLog::INTO_TRA_BB; + } else { + $data_wallet['balance_type'] = 3; + $data_wallet['before'] = $waller_info->lever_balance; + $data_wallet['after'] = bc_add($waller_info->lever_balance, $number, 5); + $waller_info->lever_balance = $waller_info->lever_balance + $number; + $info = '美丽链杠杆交易余额转入'; + $type_info = AccountLog::INTO_TRA_GG; + } + $waller_info->save(); + //锁定余额 + + $waller_info->save(); + AccountLog::insertLog([ + 'user_id' => $tra_user->id, + 'value' => $number, + 'currency' => $currency->id, + 'info' => $info, + 'type' => $type_info, + ], $data_wallet); + DB::commit(); + return $this->success('转入成功'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + + } + public function into_tra_log() + { + $user_id = Users::getUserId(); + $list = AccountLog::whereIn("type", array(65, 66, 67))->where('user_id', $user_id)->orderBy('id', 'desc')->get()->toArray(); + return $this->success($list); + } + public function e_pwd() + { + $account_number = Input::get('account_number', ''); + $password = Input::get('password', ''); + $type = Input::get('type', '1'); ///type:1登录密码,type:2支付密码 + if (empty($account_number)) { + return $this->error('转入账户不能为空'); + } + if (empty($password)) { + return $this->error('密码不能为空'); + } + $tra_user = Users::getByAccountNumber($account_number); + if (empty($tra_user)) { + return $this->error('用户未找到'); + } + DB::beginTransaction(); + try { + if ($type == 1) { + $tra_user->password = Users::MakePassword($password, $tra_user->type); + + } else { + $tra_user->pay_password = Users::MakePassword($password, $tra_user->type); + } + + $tra_user->save(); + DB::commit(); + return $this->success('密码修改成功'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + + } + + +} +?> \ No newline at end of file diff --git a/app/Http/Controllers/Api/ChatController.php b/app/Http/Controllers/Api/ChatController.php new file mode 100644 index 0000000..a88fb6c --- /dev/null +++ b/app/Http/Controllers/Api/ChatController.php @@ -0,0 +1,119 @@ +user_id = Users::getUserId(); + } + + public function bind(Request $request) + { + $client_id = $request->get('client_id', 0); + $uid = $this->user_id; + Gateway::bindUid($client_id, $uid); + return $this->success('绑定成功'); + } + + public function send(Request $request) + { + $uid = $request->get('user_id', 0); + $message = $request->get('message', ''); + $type = $request->get('type', 1); + $trade_id = $request->get('trade_id', 1); + + $user_info = Users::getById($this->user_id); + $send_data = json_encode([ + 'type'=> $type, + 'data'=> $message, + 'user_info' => $user_info, + 'trade_id' => $trade_id, + ]); + Gateway::sendToUid($uid, $send_data); + + $with_user = $uid; + $last_chat_log = ChatLog::where(function ($query)use($with_user){ + $query->where('from_user',$this->user_id)->where('to_user',$with_user); + })->orWhere(function ($query)use($with_user){ + $query->where('from_user',$with_user)->where('to_user',$this->user_id); + })->orderBy('created_at','desc')->first(); + if($last_chat_log){ + $one_hour_ago = Carbon::now()->subHour(); + $last_chat_time = Carbon::parse($last_chat_log['created_at']); + if($last_chat_time->lt($one_hour_ago)){//距离上次聊天已经过去一个小时 + ChatLog::unguard(); + ChatLog::create([ + 'type' => 4, + 'content' => date("m月d日 H:i"), + 'from_user' => $this->user_id, + 'to_user' => $uid, + 'trade_id' => $trade_id, + ]); + ChatLog::reguard(); + } + } + ChatLog::unguard(); + ChatLog::create([ + 'type' => $type, + 'content' => $message, + 'from_user' => $this->user_id, + 'to_user' => $uid, + 'trade_id' => $trade_id, + ]); + ChatLog::reguard(); + return $this->success('发送成功'); + } + + public static function static_send($uid,$message) + { + Gateway::sendToUid($uid, $message); + } + + /** + * 聊天历史纪录 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function getChatLog(Request $request) + { + $with_user = $request->get('user_id',0); + $chat_logs = ChatLog::where(function ($query)use($with_user){ + $query->where('from_user',$this->user_id)->where('to_user',$with_user); + })->orWhere(function ($query)use($with_user){ + $query->where('from_user',$with_user)->where('to_user',$this->user_id); + })->orderBy('created_at')->where('created_at','>',Carbon::now()->subDays(7))->get(); + + ChatLog::where('to_user',$this->user_id)->where('from_user',$with_user)->update(['readed' => 1]);; + return $this->success(['login_user' => $this->user_id,'data' => $chat_logs]); + } + public function getUnreadMsg(Request $request) + { + $trade_id = $request->get('id',0); + $unread_number = self::unreadMsg($this->user_id, $trade_id); + return $this->success($unread_number); + } + + public static function unreadMsg($user_id, $trade_id = 0) + { + $unread_number = ChatLog::where('to_user', $user_id) + ->where('readed',0) + ->where(function ($query) use ($trade_id){ + if($trade_id){ + $query->where('trade_id', $trade_id); + } + })->count(); + return $unread_number; + } +} diff --git a/app/Http/Controllers/Api/CoinTradeController.php b/app/Http/Controllers/Api/CoinTradeController.php new file mode 100644 index 0000000..0911f14 --- /dev/null +++ b/app/Http/Controllers/Api/CoinTradeController.php @@ -0,0 +1,107 @@ +input('legal_id'); + $currency = $request->input('currency_id'); + $target_price = $request->input('target_price'); + $type = $request->input('type'); + $amount = $request->input('amount'); + $match = CurrencyMatch::where([ + 'legal_id' => $legal, + 'currency_id' => $currency, + 'open_coin_trade' => 1 + ])->first(); + if(!$match){ + return $this->error('找不到交易对'); + } + if(!$legal || !$currency || $target_price< 0 || $amount<0){ + return $this->error('参数错误'); + } + + // return $this->error($legal."--".$currency."--".$target_price."--".$amount); + $userId = Users::getUserId(); + try{ + switch ($type){ + case 1: //买 + CoinTradeLogic::userBuyCoint($userId,$currency,$legal,$amount,$target_price); + break; + case 2: //卖 + CoinTradeLogic::userSellCoin($userId,$currency,$legal,$amount,$target_price); + break; + default: + return $this->error('参数错误'); + } + + }catch (\Exception $e){ + return $this->error($e->getMessage()); + } + + return $this->success(''); + } + + public function tradeList(Request $request){ + $limit = $request->get('limit', 20); + $page = $request->get('page', 1); + $user_id = Users::getUserId(); + $currency_id = $request->get('currency_id'); + $legal_id = $request->get('legal_id'); + $status = $request->get('status'); + $where = []; + if($currency_id){ + $where['currency_id'] = $currency_id; + } + if($legal_id){ + $where['legal_id'] = $legal_id; + } + if($status){ + $where['status'] = $status; + } + + $list = CoinTrade::where('u_id',$user_id) + ->where($where) + ->orderBy('id','desc') + ->skip($limit*($page-1))->take($limit)->get(); + foreach($list as &$li){ + $li['symbol'] = Currency::getNameById($li->currency_id).'/'.Currency::getNameById($li->legal_id); + } + return $this->success($list); + } + + public function cancelTrade(Request $request){ + $id = $request->get('id'); + $user_id = Users::getUserId(); + $tradeOrder = CoinTrade::find($id); + + + // file_put_contents('/www/wwwroot/crypto/public/tt1.txt',time().$id.PHP_EOL,FILE_APPEND); + if(!$tradeOrder){ + return $this->error('参数错误'); + } + if($tradeOrder->u_id != $user_id){ + return $this->error('请求异常'); + } + if($tradeOrder->status != 1){ + return $this->error('状态异常'); + } + try{ + $res = CoinTradeLogic::cancelTrade($id); + }catch (\Exception $e){ + return $this->error('取消失败:'.$e->getMessage()); + } + return $this->success('取消成功'); + + } +} diff --git a/app/Http/Controllers/Api/Controller.php b/app/Http/Controllers/Api/Controller.php new file mode 100644 index 0000000..38e1c23 --- /dev/null +++ b/app/Http/Controllers/Api/Controller.php @@ -0,0 +1,110 @@ +user_id = Token::getUserIdByToken($token); + // } + + // header('Content-Type:application/json'); + // header('Access-Control-Allow-Origin:*'); + // header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); + // header('Access-Control-Allow-Headers:x-requested-with,content-type'); + // header('Access-Control-Allow-Headers:x-requested-with,content-type,Authorization'); + + } + + /** + * 返回一个错误响应 + * + * @param string $message + * @return \Illuminate\Http\JsonResponse + */ + public function error($message) + { + /* + header('Content-Type:application/json'); + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); + header('Access-Control-Allow-Headers:x-requested-with,content-type'); + header('Access-Control-Allow-Headers:x-requested-with,content-type,Authorization'); + */ + if (is_string($message)){ + $message=str_replace('massage.', '', __("massage.$message")); + } + return response()->json(['type' => 'error', 'message' => $message]); + } + + /** + * 返回一个成功响应 + * + * @param string $message + * @return \Illuminate\Http\JsonResponse + */ + public function success($message,$type=0) + { + /* + header('Content-Type:application/json'); + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); + header('Access-Control-Allow-Headers:x-requested-with,content-type'); + header('Access-Control-Allow-Headers:x-requested-with,content-type,Authorization'); + */ + if (is_string($message)&&$type==0){ + $message=str_replace('massage.', '', __("massage.$message")); + } + return response()->json(['type' => 'ok', 'message' => $message]); + } + + /** + * 返回一个成功响应 + * + * @param string $message + * @return \Illuminate\Http\JsonResponse + */ + public function success_ceshi($message) + { + /* + header('Content-Type:application/json'); + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); + header('Access-Control-Allow-Headers:x-requested-with,content-type'); + header('Access-Control-Allow-Headers:x-requested-with,content-type,Authorization'); + */ + if (is_string($message)){ + $message=str_replace('massage.', '', __("massage.$message")); + } + return response()->json(['type' => 'ok', 'message' => $message]); + } + + + public function pageData($paginateObj) + { + $results = [ + 'data' => $paginateObj->items(), + 'page' => $paginateObj->currentPage(), + 'pages' => $paginateObj->lastPage(), + 'total' => $paginateObj->total() + ]; + return $this->success($results); + } + + public function returnStr($str){ + $message=str_replace('massage.', '', __("massage.$str")); + return $message; + } +} diff --git a/app/Http/Controllers/Api/CrontabController.php b/app/Http/Controllers/Api/CrontabController.php new file mode 100644 index 0000000..6fb43dc --- /dev/null +++ b/app/Http/Controllers/Api/CrontabController.php @@ -0,0 +1,65 @@ +implementFunc($rate_symbol,$now_time); + } + exit; + } + + private function implementFunc($rate_symbol,$now_time){ + $url = 'https://api.it120.cc/gooking/forex/rate?fromCode='.$rate_symbol.'&toCode=USD'; + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_ENCODING, 'utf-8'); + curl_setopt($ch, CURLOPT_TIMEOUT, 30); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $result = curl_exec($ch); + $result = mb_convert_encoding($result, "utf-8", "gb2312"); + $ip_res = json_decode($result, true); + curl_close ($ch); + $res = null; + $time = time(); + if($ip_res['code']===0){ + if($ip_res['data']['rate']){ + $res = $ip_res['data']['rate']; + } + } + + if($res){ + $rate = Rate::where('currency',$rate_symbol)->first(); + + if($rate){ + DB::table('rate')->where('currency',$rate_symbol)->update(['rate'=>$res,'updated'=>$now_time]); + + }else{ + Rate::create([ + 'currency'=>$rate_symbol, + 'rate'=>$res, + 'updated'=>$now_time, + ]); + } + echo 'success'; + } + + } + +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/CurrencyController.php b/app/Http/Controllers/Api/CurrencyController.php new file mode 100644 index 0000000..15e1f07 --- /dev/null +++ b/app/Http/Controllers/Api/CurrencyController.php @@ -0,0 +1,991 @@ +toArray(); + return $this->success($LHaaruJ); + } + public function rangeNew(){ + $hot = DB::table('currency_quotation') + ->join('currency', 'currency_quotation.currency_id', '=', 'currency.id') + ->where('currency.is_display', 1) + ->where('currency.is_legal', 1) + ->orderBy("currency_quotation.volume","desc") + ///->where('currency_quotation.change','>', 0) + ->limit(100) + ->get(); + + $increase = DB::table('currency_quotation') + ->join('currency', 'currency_quotation.currency_id', '=', 'currency.id') + ->where('currency.is_display', 1) + ->where('currency.is_legal', 1) + //->where('currency_quotation.change','>', 0) + ->orderBy("currency_quotation.change","desc") + ->limit(100) + ->get(); + $currency['hot'] = $hot; + $currency['increase'] = $increase; + return $this->success($currency); + } + + public function bizcate(){ + $data = DB::table('lh_deposit_config')->join('currency','currency.id','=','currency_id') + ->groupBy('currency_id') + ->select(['currency.name as currency_name','currency.logo as currency_logo','lh_deposit_config.*']) + ->get(); + return $this->success($data); + } + + + + public function listsRecharge() + { + + $Key = config('app.udun_apikey'); + + $memberid = config('app.memberid'); + $HttpUrl = config('app.gateway'); + $CallUrl = config('app.callback'); + + $udun_enable = config('app.udun_enable'); + + + $list = Currency::where('is_display', 1)->orderBy('sort', 'asc')->get()->toArray(); + $array = array(); + + if($udun_enable==true) { + + + $list = UdunAddress::where('status', 1)->orderBy('id', 'asc')->get()->toArray(); + + $array = array(); + foreach ($list as $v) { + $walletaddress = $this->xcreateAddress($v['chain_id'],$memberid,$v['name'],$v['contract']); + if (is_array($walletaddress) && isset($walletaddress['data']['address'])) { + $v['address_erc'] = $v['address_omni'] = $walletaddress['data']['address']; + } else { + $v['address_erc'] = $v['address_omni'] = ''; + } + $v['vcode'] = $v['real_name']; + array_push($array, $v); + } + + + }else{ + + foreach ($list as $v) { + if ($v['address_erc'] !='' && $v['address_omni'] !='') { + $a=$v; + $a['name']=$a['name'].'-ERC20'; + array_push($array, $a); + + $b=$v; + $b['name']=$b['name'].'-TRC20'; + $b['address_erc']=$b['address_omni']; + array_push($array, $b); + }else{ + if($v['address_erc'] !=''){ + array_push($array, $v); + } + if($v['address_omni'] !=''){ + + array_push($array, $v); + } + } + + } + + } + + return $this->success(array('currency' => $list, 'udun_enable'=>$udun_enable,'recharge' => $array)); + } + + + public function xcreateAddress(int $coinType,$MerchantId,$CoinName,$contract) + { + + $Key = config('app.udun_apikey'); + $HttpUrl = config('app.gateway'); + $CallUrl = config('app.callback'); + $memberid = config('app.memberid'); + + // if($coinType ==0) $currency_id='BTC'; + // if($coinType ==60) $currency_id='ETH'; + // if($coinType ==195) $currency_id='TRX'; + + + $user_id = Users::getUserId(); + // $map = array('memberid'=>$memberid,'user_id' => $user_id, 'chain_id' => $coinType); + + if(!$user_id) return $this->error("非法用户"); + + + + + if(!WalletAddress::where('memberid',$memberid)->where('user_id',$user_id)->where('chain_id',$coinType)->where('contract',$contract)->where('currency_id',$CoinName)->first()){ + + + + $body = array( + 'merchantId' => $MerchantId, + 'coinType' => $coinType, + 'callUrl' => $CallUrl, + ); + + + + $Timestamp = time(); + $Nonce = rand(100000,999999); + + $body = '['.json_encode($body).']'; + $timestamp = $Timestamp; + $nonce = $Nonce; + + $url = $HttpUrl.'/mch/address/create'; + $key = $Key; + + $sign = md5($body.$key.$nonce.$timestamp); + + $data = array( + 'timestamp' => $timestamp, + 'nonce' => $nonce, + 'sign' => $sign, + 'body' => $body + ); + $data_string = json_encode($data); + + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + 'X-AjaxPro-Method:ShowList', + 'Content-Type: application/json; charset=utf-8', + 'Content-Length: ' . strlen($data_string)) + ); + + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); + $data = curl_exec($ch); + + curl_close($ch); + + if(is_object($data)) { + $data = (array)$data; + } + + $data_array = json_decode($data,true); + + + + if($data_array['code']!=200 ){ + // file_put_contents('/www/wwwroot/crypto/public/walletaddress.txt',time().json_encode($data_array).PHP_EOL,FILE_APPEND); + return $this->error("用户id:".$user_id." chain_id : ".$coinType."地址生成失败"); + + } + + $newdata['memberid'] =$memberid; + + $newdata['chain_id'] = $coinType; + $newdata['contract'] = $contract; + + $newdata['currency_id'] = $CoinName; + + $newdata['user_id'] = $user_id; + + $newdata['address'] = $data_array['data']['address']; + + DB::table('wallet_address')->insert($newdata); + + /* WalletAddress::create([ + 'memberid'=>$memberid, + 'chain_id'=>$coinType, + 'currency_id'=>$currency_id, + 'user_id'=>$user_id, + 'address'=>$data_array['data']['address'], + ]); + + + WalletAddress::create($newdata); + */ + + + Redis::set('address:' . strtolower($data_array['data']['address']),$user_id); + + + + }else{ + + + $data_array['data'] = WalletAddress::where('memberid',$memberid)->where('user_id',$user_id)->where('chain_id',$coinType)->where('contract',$contract)->where('currency_id',$CoinName)->first(); + + } + + return $data_array; + + } + + + + public function createAddress(int $coinType,$MerchantId,$CoinName) + { + + $Key = config('app.udun_apikey'); + $HttpUrl = config('app.gateway'); + $CallUrl = config('app.callback'); + $memberid = config('app.memberid'); + + // if($coinType ==0) $currency_id='BTC'; + // if($coinType ==60) $currency_id='ETH'; + // if($coinType ==195) $currency_id='TRX'; + + + $user_id = Users::getUserId(); + // $map = array('memberid'=>$memberid,'user_id' => $user_id, 'chain_id' => $coinType); + + if(!$user_id) return $this->error("非法用户"); + + + + + if(!WalletAddress::where('memberid',$memberid)->where('user_id',$user_id)->where('chain_id',$coinType)->where('currency_id',$CoinName)->first()){ + + + + $body = array( + 'merchantId' => $MerchantId, + 'coinType' => $coinType, + 'callUrl' => $CallUrl, + ); + + + + $Timestamp = time(); + $Nonce = rand(100000,999999); + + $body = '['.json_encode($body).']'; + $timestamp = $Timestamp; + $nonce = $Nonce; + + $url = $HttpUrl.'/mch/address/create'; + $key = $Key; + + $sign = md5($body.$key.$nonce.$timestamp); + + $data = array( + 'timestamp' => $timestamp, + 'nonce' => $nonce, + 'sign' => $sign, + 'body' => $body + ); + $data_string = json_encode($data); + + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + 'X-AjaxPro-Method:ShowList', + 'Content-Type: application/json; charset=utf-8', + 'Content-Length: ' . strlen($data_string)) + ); + + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); + $data = curl_exec($ch); + + curl_close($ch); + + if(is_object($data)) { + $data = (array)$data; + } + + $data_array = json_decode($data,true); + + + + if($data_array['code']!=200 ){ + // file_put_contents('/www/wwwroot/crypto/public/walletaddress.txt',time().json_encode($data_array).PHP_EOL,FILE_APPEND); + return $this->error("用户id:".$user_id." chain_id : ".$coinType."地址生成失败"); + + } + + $newdata['memberid'] =$memberid; + + $newdata['chain_id'] = $coinType; + + $newdata['currency_id'] = $CoinName; + + $newdata['user_id'] = $user_id; + + $newdata['address'] = $data_array['data']['address']; + + DB::table('wallet_address')->insert($newdata); + + /* WalletAddress::create([ + 'memberid'=>$memberid, + 'chain_id'=>$coinType, + 'currency_id'=>$currency_id, + 'user_id'=>$user_id, + 'address'=>$data_array['data']['address'], + ]); + + + WalletAddress::create($newdata); + */ + + + Redis::set('address:' . strtolower($data_array['data']['address']),$user_id); + + + + }else{ + + $data_array['data'] = WalletAddress::where('memberid',$memberid)->where('user_id',$user_id)->where('chain_id',$coinType)->where('currency_id',$CoinName)->first(); + + } + + return $data_array; + + } + + public function address(int $id): array + { + + $Key = config('app.udun_apikey'); + + $memberid = config('app.memberid'); + $HttpUrl = config('app.gateway'); + $CallUrl = config('app.callback'); + $memberid = config('memberid'); + $user_id = Users::getUserId(); + $map = ['memberid'=>$memberid,'user_id' => $user_id, 'chain_id' => $id]; + if(!WalletAddress::query()->where($map)->exists()){ + $coinType = 0; + + switch ((int)$id){ + case 3: + $coinType = 60; + $currency_id = 2; + break; + case 4: + $coinType = 60; + $currency_id = 2; + break; + case 1: + $coinType = 195; + $currency_id = 10; + break; + case 2: + $coinType = 0; + $currency_id = 1; + break; + case 5: + $coinType = 0; + $currency_id = 1; + break; + } + + $data_array = $this->createAddress($coinType,$memberid);//,$CallUrl,$HttpUrl,$Key + + $data['memberid'] =$memberid; + + $data['chain_id'] = $id; + + $data['currency_id'] = $currency_id; + + $data['user_id'] = $user_id; + + $data['address'] = $data_array['data']['address']; + + // file_put_contents('/www/wwwroot/server/public/t.txt',$memberid."---".json_encode($data_array),FILE_APPEND); + + if($data_array['code']!=200 ){ + return $this->error("用户id:".$user_id." chain_id : ".$coinType."地址生成失败"); + }else{ + WalletAddress::query()->create($data); + Redis::set('address:' . strtolower($data_array['data']['address']),$user_id); + } + + + + $address = $data_array['data']['address']; + }else{ + $address =WalletAddress::query()->where($map)->value('address'); + } + return ['address' => $address]; + } + + public function lists() + { + $CnrtCHJ = Currency::where('is_display', 1)->orderBy('sort', 'asc')->get()->toArray(); + $ZwZsbXQ = array(); + foreach ($CnrtCHJ as $LkZuCYJ) { + if ($LkZuCYJ['is_legal']) { + array_push($ZwZsbXQ, $LkZuCYJ); + } + } + return $this->success(array('currency' => $CnrtCHJ, 'legal' => $ZwZsbXQ)); + } + public function lever() + { + $ORXHJHJ = Currency::where('is_display', 1)->orderBy('sort', 'asc')->get()->toArray(); + $GDKcLQQ = array(); + foreach ($ORXHJHJ as $tvYImDv) { + if ($tvYImDv['is_lever']) { + array_push($GDKcLQQ, $tvYImDv); + } + } + $QQXtbYJ = strtotime(date('Y-m-d')); + foreach ($GDKcLQQ as $lZliuuJ) { + $NCAnfzQ = array(); + foreach ($ORXHJHJ as $wlhJtsJ) { + if ($wlhJtsJ['id'] != $lZliuuJ['id']) { + $kbWrlVv = 0; + $qpXftSJ = 0; + $ilDGdcQ = ''; + $DpAftsJ = ''; + $VVYVhSv = 0.0; + $ilDGdcQ = TransactionComplete::orderBy('create_time', 'desc')->where('currency', $wlhJtsJ['id'])->where('legal', $lZliuuJ['id'])->first(); + $DpAftsJ = TransactionComplete::orderBy('create_time', 'desc')->where('create_time', '<', $QQXtbYJ)->where('currency', $wlhJtsJ['id'])->where('legal', $lZliuuJ['id'])->first(); + !empty($ilDGdcQ) && ($kbWrlVv = $ilDGdcQ->price); + !empty($DpAftsJ) && ($qpXftSJ = $DpAftsJ->price); + if (empty($kbWrlVv)) { + if ($qpXftSJ) { + $VVYVhSv = -100.0; + } + } else { + if ($qpXftSJ) { + $VVYVhSv = ($kbWrlVv - $qpXftSJ) / $qpXftSJ; + } else { + $VVYVhSv = 100.0; + } + } + array_push($NCAnfzQ, array('id' => $wlhJtsJ['id'], 'name' => $wlhJtsJ['name'], 'last_price' => $kbWrlVv, 'proportion' => $VVYVhSv, 'yesterday_last_price' => $qpXftSJ)); + } + } + $lZliuuJ['quotation'] = $NCAnfzQ; + } + return $this->success($GDKcLQQ); + } + public function TradeMarket(Request $request) + { + $quo = Currency::find($request->input('legal_id'))->name; + $base = Currency::find($request->input('currency_id'))->name; + $currencyInfo=Currency::where('id',$request->input('currency_id'))->first(); + $sisValue =$currencyInfo->oncontact; + + $symbol = strtolower($base . $quo); +// var_dump($base,$quo); +// die; + $url = "https://api.huobi.pro/market/history/trade?symbol={$symbol}&size=20"; + $res = json_decode(file_get_contents($url), true); + + + $rsp = []; + if ($res['status']=='ok') { + + foreach ($res['data'] as $val) { + if (count($rsp) >= 20) { + break; + } + array_walk($val['data'], function (&$v) use (& $rsp,$sisValue) { + + $v['time'] = date('H:i:s', intVal($v['ts'] / 1000)); + if (count($rsp) >= 20) { + + } else { + if($sisValue != 0){ + $v['price'] = round($v['price'] + $sisValue,8); + } + + $rsp[] = $v; + } + }); + } + } + +// var_dump($rsp); + return $this->success($rsp); + } + public function quotation_tian() + { + $BrsWBjv = Currency::where('is_display', 1)->orderBy('sort', 'asc')->get()->toArray(); + $mOnknFv = array(); + foreach ($BrsWBjv as $qMSPJTQ) { + if ($qMSPJTQ['is_legal']) { + array_push($mOnknFv, $qMSPJTQ); + } + } + $fjllgVJ = strtotime(date('Y-m-d')); + foreach ($mOnknFv as $zlqdSQv) { + $XSjKELv = array(); + foreach ($BrsWBjv as $NAaKMjv => $UNHGjLv) { + $zlqdSQv['quotation'] = CurrencyQuotation::orderBy('add_time', 'desc')->where('legal_id', $zlqdSQv['id'])->get()->toArray(); + } + } + return $this->success($mOnknFv); + } + + //获取单个行情 2024 + public function exDeal(){ + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + + if (empty($legal_id) || empty($currency_id)) + return $this->error("参数错误"); + + $arr = CurrencyMatch::where("currency_id",$currency_id) + ->where("legal_id",$legal_id) + ->where('is_display', 1)->first(); + + return $this->success($arr); + + } + + + //币种分类 + public function b_class(Request $request){ + + $result =DB::table('currency_class')->where('is_display',1)->orderBy('sort','asc')->get(); + + $data = [ + 'code' => 1, + 'msg' => 'success', + 'data' => $result + ]; + return $data; + // echo json_encode($data); + } + + public function sinatest(){ + $sina = new sina(); + // $currency_list = CurrencyMatch::forward_sj(); + // echo json_encode($currency_list); + // $name = 'JPY'; + // echo json_encode($sina->foreign($name)); + + $name = 'CBK'; + // echo json_encode($sina->real()); + $period='1min'; + echo json_encode($sina->real_gu($name)); + } + + + + + + public function test(){ + $sina = new sina(); + echo $sina->real().'
'; + echo $sina->foreign_real().'
'; + echo $sina->etfreal().'
'; + echo $sina->gpreal().'
'; + /* + $currency_list = CurrencyMatch::forward_sj(); + echo json_encode($currency_list); + $name = 'JPY'; + echo json_encode($sina->foreign($name));*/ + } + + + public function sina_s($name,$period){ + + $sina = new sina(); + $result = $sina->getwaipanKline($name,$period,300); + $result = array_map(function ($value) { + $value['time'] = $value['id']*1000; + $value['volume'] = $value['amount'] ?? 0; + return $value; + }, $result); + + // file_put_contents('/www/wwwroot/crypto/public/t.txt',$period."--".$name); + + $data = [ + 'code' => 1, + 'msg' => 'success', + 'data' => $result + ]; + return $data; + echo json_encode($data); + } + public function foreign($name,$period){ + + + $sina = new sina(); + $result = $sina->getKline($name,$period,300); + $result = array_map(function ($value) { + $value['time'] = $value['id'] * 1000; + $value['volume'] = $value['amount'] ?? 0; + return $value; + }, $result); + + $data = [ + 'code' => 1, + 'msg' => 'success', + 'data' => $result + ]; + return $data; + echo json_encode($data); + } + + public function gp($name,$period){ + + + $sina = new sina(); + $result = $sina->geteftgp($name,$period,300); + $result = array_map(function ($value) { + $value['time'] = $value['id'] * 1000; + $value['volume'] = $value['amount'] ?? 0; + return $value; + }, $result); + + $data = [ + 'code' => 1, + 'msg' => 'success', + 'data' => $result + ]; + return $data; + + } + + + public function newTimeshars(Request $request) + { + + $iriUDGJ = $request->get('symbol'); + $VmCMUNQ = $request->get('period'); + $biRnHJv = $request->get('from', null); + $cAMDfuJ = $request->get('to', null); + $iriUDGJ = strtoupper($iriUDGJ); + $KuPpbTJ = ['1min' => 5, '5min' => 6, '15min' => 1, '30min' => 7, '60min' => 2, '1D' => 4, '1W' => 8, '1M' => 9, '1day' => 4, '1week' => 8, '1mon' => 9, '1year' => 10]; + $lKNcYmQ = array_keys($KuPpbTJ); + $fVvRJYJ = array_values($KuPpbTJ); + if ($biRnHJv == null || $cAMDfuJ == null) { + return ['code' => -1, 'msg' => 'error: start time or end time must be filled in', 'data' => null]; + } + if ($biRnHJv > $cAMDfuJ) { + return ['code' => -1, 'msg' => 'error: start time should not exceed the end time.', 'data' => null]; + } + if ($iriUDGJ == '' || stripos($iriUDGJ, '/') === false) { + return ['code' => -1, 'msg' => 'error: symbol invalid', 'data' => null]; + } + if ($VmCMUNQ == '' || !in_array($VmCMUNQ, $lKNcYmQ)) { + return ['code' => -1, 'msg' => 'error: period invalid', 'data' => null]; + } + $adlYLXQ = strtotime(date('Y-m-d H:i')); + if ($VmCMUNQ == '1min' && $cAMDfuJ >= $adlYLXQ) { + $cAMDfuJ = $adlYLXQ - 1; + } + + + $mjWkkrv = $KuPpbTJ[$VmCMUNQ]; + $iriUDGJ = explode('/', $iriUDGJ); + list($HSQfSkJ, $JnRWhhQ) = $iriUDGJ; + $HSQfSkJ = Currency::where('name', $HSQfSkJ)->where('is_display', 1)->first(); + $JnRWhhQ = Currency::where('name', $JnRWhhQ)->where('is_display', 1)->where('is_legal', 1)->first(); + if (!$HSQfSkJ || !$JnRWhhQ) { + return ['code' => -1, 'msg' => 'error: symbol not exist', 'data' => null]; + } + $jqbYHhJ = $JnRWhhQ->id; + $ElYLALJ = $HSQfSkJ->id; + $fFVCeHJ = MarketHour::orderBy('day_time', 'asc')->where('currency_id', $ElYLALJ)->where('legal_id', $jqbYHhJ)->where('type', $mjWkkrv)->where('day_time', '>=', $biRnHJv)->where('day_time', '<=', $cAMDfuJ)->get(); + $rXDaOwJ = array(); + if ($fFVCeHJ) { + foreach ($fFVCeHJ as $qhNdsMJ => $ncfMSiJ) { + $KuIMXuv = array('open' => $ncfMSiJ->start_price, 'close' => $ncfMSiJ->end_price, 'high' => $ncfMSiJ->highest, 'low' => $ncfMSiJ->mminimum, 'volume' => $ncfMSiJ->number, 'time' => $ncfMSiJ->day_time * 1000); + array_push($rXDaOwJ, $KuIMXuv); + } + } else { + foreach ($fFVCeHJ as $qhNdsMJ => $ncfMSiJ) { + $KuIMXuv = null; + array_push($rXDaOwJ, $KuIMXuv); + } + } + return ['code' => 1, 'msg' => 'success:)', 'data' => $rXDaOwJ]; + } + + + public function klineMarket(Request $request) + { + +// die('dsa'); + $symbol = $request->input('symbol'); + $period = $request->input('period'); + $from = $request->input('from', null); + $to = $request->input('to', null); + + $str = explode('/',$symbol); + $currency = DB::table('currency')->where('name',$str[0])->first(); + $currency = json_encode($currency); + $currency = json_decode($currency,true); + $currency_matches = DB::table('currency_matches')->where('currency_id',$currency['id'])->first(); + $currency_matches = json_encode($currency_matches); + $currency_matches = json_decode($currency_matches,true); + // $currency_matches['market_from']; + + + if($currency_matches['market_from']==3){///999 + + return $this->sina_s($str[0],$period); + }///999 + + if($currency_matches['market_from']==0){///999 + + return $this->foreign($str[0],$period); + } + + if($currency_matches['market_from']==6 || $currency_matches['market_from']==9){///999 + + return $this->gp($str[0],$period); + } + + + + + + $symbol = strtoupper($symbol); + $result = []; + //类型,1=15分钟,2=1小时,3=4小时,4=一天,5=分时,6=5分钟,7=30分钟,8=一周,9=一月,10=一年 + $period_list = [ + '1min' => '1min', + '5min' => '5min', + '15min' => '15min', + '30min' => '30min', + '60min' => '60min', + '1H' => '60min', + '1D' => '1day', + '1W' => '1week', + '1M' => '1mon', + '1Y' => '1year', + '1day' => '1day', + '1week' => '1week', + '1mon' => '1mon', + '1year' => '1year', + ]; + if ($from == null || $to == null) { + return [ + 'code' => -1, + 'msg' => 'error: from time or to time must be filled in', + 'data' => $result, + ]; + } + if ($from > $to) { + return [ + 'code' => -1, + 'msg' => 'error: from time should not exceed the to time.', + 'data' => $result, + ]; + } + $periods = array_keys($period_list); + if ($period == '' || !in_array($period, $periods)) { + return [ + 'code' => -1, + 'msg' => 'error: period invalid', + 'data' => $result, + ]; + } + if ($symbol == '' || stripos($symbol, '/') === false) { + return [ + 'code' => -1, + 'msg' => 'error: symbol invalid', + 'data' => $result, + ]; + } + $period = $period_list[$period]; + list($base_currency, $quote_currency) = explode('/', $symbol); + $base_currency_model = Currency::where('name', $base_currency) + ->where("is_display", 1) + ->first(); + $quote_currency_model = Currency::where('name', $quote_currency) + ->where("is_display", 1) + ->where("is_legal", 1) + ->first(); + if (!$base_currency_model || !$quote_currency_model) { + return [ + 'code' => -1, + 'msg' => 'error: symbol not exist', + 'data' => null + ]; + } + $result = MarketHour::getEsearchMarket($base_currency, $quote_currency, $period, $from, $to); +// var_dump($result); +// die; + + $result = array_map(function ($value) { + $value['time'] = $value['id'] * 1000; + $value['volume'] = $value['amount'] ?? 0; + return $value; + }, $result); +// $result[10]['low']=$result[10]['low']-1200; +// $result[10]['close']=$result[10]['close']-1000; + + + return [ + 'code' => 1, + 'msg' => 'success', + 'data' => $result + ]; + } + + public function klineMarket111(Request $request) + { + $symbol = $request->input('symbol'); + $period = $request->input('period'); + $from = $request->input('from', null); + $to = $request->input('to', null); + + + $symbol = strtoupper($symbol); + + $array = []; + $data = ['1min' => '1min', '5min' => '5min', '15min' => '15min', '30min' => '30min', '60min' => '60min', '1H' => '60min', '1D' => '1day', '1W' => '1week', '1M' => '1mon', '1Y' => '1year', '1day' => '1day', '1week' => '1week', '1mon' => '1mon', '1year' => '1year']; + if ($from == null || $to == null) { + return ['code' => -1, 'msg' => 'error: from time or to time must be filled in', 'data' => $array]; + } + if ($from > $to) { + return ['code' => -1, 'msg' => 'error: from time should not exceed the to time.', 'data' => $array]; + } + $newdata = array_keys($data); + if ($period == '' || !in_array($period, $newdata)) { + return ['code' => -1, 'msg' => 'error: period invalid', 'data' => $array]; + } + if ($symbol == '' || stripos($symbol, '/') === false) { + return ['code' => -1, 'msg' => 'error: symbol invalid', 'data' => $array]; + } + $period = $data[$period]; + list($is_display, $is_legal) = explode('/', $symbol); + $result = Currency::where('name', $is_display)->where('is_display', 1)->first(); + $results = Currency::where('name', $is_legal)->where('is_display', 1)->where('is_legal', 1)->first(); + if (!$result || !$results) { + return ['code' => -1, 'msg' => 'error: symbol not exist', 'data' => null]; + } + $array = MarketHour::getEsearchMarket($is_display, $is_legal, $period, $from, $to); + $array = array_map(function ($value) { + $value['time'] = $value['id'] * 1000; + $value['volume'] = $value['amount'] ?? 0; + return $value; + }, $array); + return ['code' => 1, 'msg' => 'success', 'data' => $array]; + } + + + public function huangnewQuotation() + { + $is_class = Input::get('is_class', 0); + $list = Currency::with(["quotation"=>function($query) use ($is_class){ + $query->where('is_display', 1)->where('market_from', $is_class)->where('id', '<>',4)->orderBy('sort','asc'); + }])->whereHas('quotation', function ($query) { + $query->where('is_display', 1); + })->where('is_display', 1)->where('is_legal', 1)->orderBy('sort','asc')->get(); + + return $this->success($list); + } + public function newQuotation() + { + $BmnYXrJ = Currency::with('quotation')->whereHas('quotation', function ($query) { + $query->where('is_display', 1); + })->where('is_display', 1)->where('is_legal', 1)->orderBy('sort','asc')->get(); + return $this->success($BmnYXrJ); + } + + + public function optionalQuotation() + { + $BmnYXrJ = Currency::with(["quotation"=>function($query){ + $query->where('is_display', 1)->where('id', '<>',4)->orderBy('sort','asc'); + }])->whereHas('quotation', function ($query) { + $query->where('is_display', 1); + })->where('is_display', 1)->where('is_legal', 1)->orderBy('sort','asc')->get(); + return $this->success($BmnYXrJ); + } + public function dealInfo() + { + $TAXjNyv = Input::get('legal_id'); + $XhwvDSQ = Input::get('currency_id'); + if (empty($TAXjNyv) || empty($XhwvDSQ)) { + return $this->error('参数错误'); + } + $bltKpAQ = Currency::where('is_display', 1)->where('id', $TAXjNyv)->where('is_legal', 1)->first(); + $AmPMnfQ = Currency::where('is_display', 1)->where('id', $XhwvDSQ)->first(); + if (empty($bltKpAQ) || empty($AmPMnfQ)) { + return $this->error('币未找到'); + } + $gEUGyVJ = Input::get('type', '1'); + $PWRLYvQ = 60; + switch ($gEUGyVJ) { + case 2: + $PWRLYvQ = 900; + break 1; + case 3: + $PWRLYvQ = 3600; + break 1; + case 4: + $PWRLYvQ = 14400; + break 1; + case 5: + $PWRLYvQ = 86400; + break 1; + default: + $PWRLYvQ = 60; + } + $GlYqXKv = time(); + $qTstiMQ = 0; + $dViLeaQ = TransactionComplete::orderBy('create_time', 'desc')->where('currency', $XhwvDSQ)->where('legal', $TAXjNyv)->first(); + $dViLeaQ && ($qTstiMQ = $dViLeaQ->price); + $aRpAMwv = TransactionComplete::getQuotation($TAXjNyv, $XhwvDSQ, $GlYqXKv - $PWRLYvQ, $GlYqXKv); + $vaTCiiv = array(); + for ($LVnvAcQ = 0; $LVnvAcQ < 10; $LVnvAcQ++) { + $KXhrmpJ = $GlYqXKv - $LVnvAcQ * $PWRLYvQ; + $yrQDxmQ = $KXhrmpJ - $PWRLYvQ; + $PtbcDYQ = array(); + $PtbcDYQ = $aRpAMwv = TransactionComplete::getQuotation($TAXjNyv, $XhwvDSQ, $yrQDxmQ, $KXhrmpJ); + array_push($vaTCiiv, $PtbcDYQ); + } + return $this->success(array('legal' => $bltKpAQ, 'currency' => $AmPMnfQ, 'last_price' => $qTstiMQ, 'now_quotation' => $aRpAMwv, 'quotation' => $vaTCiiv)); + } + public function userCurrencyList() + { + $user_id = Users::getUserId(); + $XOylMHJ = Currency::where('is_display', 1)->orderBy('sort', 'desc')->get(); + $XOylMHJ = $XOylMHJ->filter(function ($item, $key) { + $fRtZmfQ = array_sum([$item->is_legal, $item->is_lever, $item->is_match, $item->is_micro]); + return $fRtZmfQ > 1; + })->values(); + $XOylMHJ->transform(function ($item, $key) use($user_id) { + $VxDXWbJ = UsersWallet::where('user_id', $user_id)->where('currency', $item->id)->first(); + $item->setVisible(['id', 'name', 'is_legal', 'is_lever', 'is_match', 'is_micro', 'wallet']); + return $item->setAttribute('wallet', $VxDXWbJ); + }); + return $this->success($XOylMHJ); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/CurrencyDepositController.php b/app/Http/Controllers/Api/CurrencyDepositController.php new file mode 100644 index 0000000..484ac21 --- /dev/null +++ b/app/Http/Controllers/Api/CurrencyDepositController.php @@ -0,0 +1,118 @@ + 1, + ])->where('start_at','<',date("Y-m-d")) + ->where('last_settle_time','<',date("Y-m-d")) + ->orWhere('last_settle_time',null) + ->take(20) ->get(); + foreach($res as $order){ + CurrencyDepositOrder::dispatchInterest($order->id); + if($order->end_at < date('Y-m-d')){ + //todo 时间到了 释放存款 + CurrencyDepositOrder::where('id',$order->id)->update(['status' => 2]); + } + } + } + + public function configList(Request $request){ + $currencyId = $request->input('currency_id'); + if(!$currencyId){ + return $this->error('require param currency_id'); + } + $list = DB::table('currency_deposit')->where('currency_id',$currencyId)->orderBy('day','asc')->get(); + return $this->success($list); + } + + public function orderList(Request $request){ + $currencyId = $request->input('currency_id'); + $limit = $request->get('limit', 20); + $page = $request->get('page', 1); + $where = []; + if($currencyId){ + $where['currency_id'] = $currencyId; + } + $uid = Users::getUserId(); + $list = CurrencyDepositOrder::join('currency','currency.id','=','currency_id')->where('u_id',$uid)->where($where)->orderBy('end_at','asc') + ->skip($limit*($page-1))->take($limit)->select(['currency_deposit_order.*','currency.name'])->get(); + return $this->success([ + 'list' => $list + ]); + } + + + + public function deposit(Request $request){ + $uid = Users::getUserId(); + $currencyId = $request->input('currency_id'); + if(!$currencyId){ + return $this->error('require param currency_id'); + } + $configId = $request->input('config_id'); + $config = DB::table('currency_deposit')->find($configId); + if(!$config || $config->currency_id != $currencyId){ + return $this->error('config error'); + } + $amount = Input::get('amount',''); + if($amount < 0 || ($amount < $config->save_min)){ + return $this->error('amount error'); + } + $legal = UsersWallet::where("user_id", $uid) + ->where("currency", $currencyId) //usdt + ->lockForUpdate() + ->first(); + if (!$legal) { + return $this->error("钱包未找到,请先添加钱包"); + } + if($legal->change_balance < $amount){ + return $this->error('资金钱包余额不足'); + } + DB::beginTransaction(); + try{ + //先扣费 + $result = change_wallet_balance( + $legal, + 2, + -$amount, + AccountLog::LH_LOAN, + '质押挖矿', + false, + 0, + 0, + serialize([]) + ); + $model = new CurrencyDepositOrder(); + $model->u_id = $uid; + $model->currency_id = $currencyId; + $model->amount = $amount; + $model->total_rate = $config->total_interest_rate; + $model->day_rate = bc_div($config->total_interest_rate,$config->day,4); + $model->start_at = date("Y-m-d",strtotime("+1 day")); + $day = $config->day+1; + $model->end_at = date("Y-m-d",strtotime("+$day day")); + $model->save(); + Db::commit(); + }catch (\Exception $e){ + Db::rollBack(); + return $this->error($e->getMessage()); + } + return $this->success('success'); + + } +} diff --git a/app/Http/Controllers/Api/CurrencyProjectController.php b/app/Http/Controllers/Api/CurrencyProjectController.php new file mode 100644 index 0000000..9af7e61 --- /dev/null +++ b/app/Http/Controllers/Api/CurrencyProjectController.php @@ -0,0 +1,514 @@ +where('type',1) + ->where('end_at','<',date("Y-m-d H:i:s")) + ->take(10)->get(); + //认购单派钱 + foreach($list as $v){ + DB::beginTransaction(); + try{ + $op_wallet = UsersWallet::where('user_id',$v->u_id) + ->where('currency',$v->currency_id) + ->first(); + if(!$op_wallet){ + throw new \Execption('wallet not found'); + } + $result = change_wallet_balance($op_wallet, + 4, + $v->coin_amount, + AccountLog::IEO_OPERATION, + 'ieo order'); + CurrencyProjectOrder::where('id',$v->id)->update([ + 'status' => 3 + ]); + DB::commit(); + }catch(\Execption $e){ + DB::rollBack(); + continue ; + } + } + + $list2 = CurrencyProjectOrder::join('users_wallet','users_wallet.id','=','currency_project_order.pay_wallet_id') + ->where('currency_project_order.status',1)->where('type',2)->where('users_wallet.micro_balance','>','currency_project_order.total_price') + ->where('end_at','<',date("Y-m-d H:i:s")) + ->take(10)->select(['currency_project_order.*'])->get(); + // var_dump($list2);exit; + foreach($list2 as $item){ + DB::beginTransaction(); + try{ + $wallet = UsersWallet::where("user_id", $item->u_id) + ->where("currency", $item->pay_currency_id) + ->lockForUpdate() + ->first(); + if(!$wallet){ + throw new \Execption('wallet not found'); + } + $op_wallet = UsersWallet::where('user_id',$item->u_id) + ->where('currency',$item->currency_id) + ->first(); + if(!$op_wallet){ + throw new \Execption('wallet not found'); + } + //扣款 + $result = change_wallet_balance($wallet, + 4, + -$item->total_price, + AccountLog::IEO_OPERATION, + 'ieo order'); + if ($result !== true) { + throw new \Exception($result); + } + //发币 + $result = change_wallet_balance($op_wallet, + 2, + $item->coin_amount, + AccountLog::IEO_OPERATION, + 'ieo order'); + + CurrencyProjectOrder::where('id',$item->id)->update([ + 'status' => 3 + ]); + DB::commit(); + }catch(\Execption $e){ + DB::rollBack(); + continue ; + } + } + } + + + public function projectList(Request $request){ + $limit = $request->get('limit', 20); + $page = $request->get('page', 1); +// $model = new CurrencyProject(); + + $list = CurrencyProject::where('status',1) + ->skip($limit*($page-1))->take($limit) + ->select(['title','summary','amount','total_sell','start_at','end_at','logo','id','currency_id','pay_currency_id']) + ->orderBy('start_at','desc') + ->get(); +// bc_sub($project->amount,$project->total_sell) + foreach ($list as &$item) { + $total_sell = $item->total_sell; + if (empty($total_sell)){ + $total_sell = 0; + } + if ($total_sell<=0){ + $percentage = 100; + }else{ + $percentage = (bc_sub($item->amount,$total_sell) / $item->amount) * 100; + if (number_format($percentage,2) == 100){ // 卖出去就是99.99 + $percentage = '99.99'; + } + } + $item->percentage = number_format($percentage,2); + + $day = strtotime($item->end_at) - strtotime($item->start_at); + $day = intval($day / 24 / 3600); + $item->day = $day > 0 ? $day : 1; + } + unset($item); + +// foreach($list as &$v){ +// $v['time_status'] +// } + return $this->success(['list' => $list]); + } + + + + public function projectDetail(Request $request){ + $userId = Users::getUserId(); + $id = $request->get('project_id'); + $project = CurrencyProject::find($id); + if(!$project){ + return $this->error('project not found'); + } + if($project->status != 1){ + return $this->error('project status error'); + } + + + + $total_sell = $project->total_sell; + if (empty($total_sell)){ + $total_sell = 0; + } + if ($total_sell<=0){ + $percentage = 100; + }else{ + $percentage = (bc_sub($project->amount,$total_sell) / $project->amount) * 100; + if (number_format($percentage,2) == 100){ // 卖出去就是99.99 + $percentage = '99.99'; + } + } + $project->percentage = number_format($percentage,2); + + $day = strtotime($project->end_at) - strtotime($project->start_at); + $day = intval($day / 24 / 3600); + $project->day = $day > 0 ? $day : 1; + + + + + + $project->pay_currency_id = 3; //dapp项目只有USDT支付 + $wallet = UsersWallet::where("user_id", $userId) + ->where("currency", $project->pay_currency_id) + ->first(); + $hasMoney = $wallet->micro_balance > 0 ? 1 : 0; + if($project->min){ + $hasMoney = $wallet->micro_balance > $project->min ? 1 : 0; + } + $project->user_has_money = 1;//$hasMoney; + $order = CurrencyProjectOrder::where('project_id',$id)->where('type','<',3)->where('u_id',$userId)->first(); + if($order){ + $order->order_no = 1000+$order->id; + }else{ + + $order['coin_amount'] = 0.00; + } + + $sell = CurrencyProjectOrder::where('project_id',$id)->where('type','=',3)->where('u_id',$userId)->first(); + return $this->success([ + 'info' => $project, + 'order_info' => $order, + 'sell_order' => $sell + ]); + } + public function joinLottery(Request $request){ + return $this->error('error'); + $id = $request->get('project_id'); + $amount = $request->get('amount'); + $userId = Users::getUserId(); + $project = CurrencyProject::find($id); + if(!$project){ + return $this->error('找不到项目'); + } + if($project->status != 1){ + return $this->error('项目状态异常'); + } + if($project->time_status != 2){ + return $this->error('项目已结束'); + } + if(bc_sub($project->amount,bc_add($amount,$project->total_sell,8))< 0){ + return $this->error('已售罄'); + } + // $check = CurrencyProjectOrder::where('u_id',$userId)->where('project_id',$project->id)->first(); + // if($check){ + // return $this->error('already apply'); + // } + //new wallet + $payWallet = UsersWallet::where('currency',$project->pay_currency_id)->where('user_id',$userId)->first(); + if(!$payWallet){ + $payWalletId = UsersWallet::insertGetId([ + 'currency' => $project->pay_currency_id, + 'user_id' => $userId, + 'address' => null, + 'create_time' => time() + ]); + }else{ + $payWalletId = $payWallet->id; + } + $wallet = UsersWallet::where('currency',$project->currency_id)->where('user_id',$userId)->first(); + if(!$wallet){ + $walletId = UsersWallet::insertGetId([ + 'currency' => $project->currency_id, + 'user_id' => $userId, + 'address' => null, + 'create_time' => time() + ]); + }else{ + $walletId = $wallet->id; + } + $price = bc_mul($project->price,$amount,8); + $model = new CurrencyProjectOrder(); + $model->u_id = $userId; + $model->project_id = $project->id; + $model->currency_id = $project->currency_id; + $model->pay_currency_id = $project->pay_currency_id; + $model->coin_amount = $amount; + $model->price = $project->price; + $model->total_price = $price; + $model->created_at = date('Y-m-d H:i:s'); + $model->status = 1; + $model->type = 2;//抽奖 + $model->end_at = $project->end_at; + $model->wallet_id = $walletId; + $model->pay_wallet_id = $payWalletId; + $model->save(); + return $this->success('success'); + } + + // 配售 + public function buyOrder(Request $request){ + $id = $request->get('project_id'); + $amount = $request->get('total_price'); + $userId = Users::getUserId(); + $project = CurrencyProject::find($id); + + + + if(!$project){ + return $this->error('找不到项目'); + } + + $project->pay_currency_id =3;//dapp项目只有USDT支付 + if(!$amount){ + return $this->error('参数错误'); + } + if($project->status != 1){ + return $this->error('project status error'); + } + if($project->time_status != 3){ + return $this->error('project not end'); + } + if(!$project->sell_begin || strtotime($project->sell_begin) > time()){ + return $this->error('配售未开始'); + } + $check = CurrencyProjectOrder::where('u_id',$userId)->where('project_id',$project->id)->first(); + if($check){ + return $this->error('IEO项目只可参与一次'); + } + //new wallet + $payWallet = UsersWallet::where('currency',$project->pay_currency_id)->where('user_id',$userId)->first(); + if(!$payWallet){ + $payWalletId = UsersWallet::insertGetId([ + 'currency' => $project->pay_currency_id, + 'user_id' => $userId, + 'address' => null, + 'create_time' => time() + ]); + }else{ + $payWalletId = $payWallet->id; + } + $wallet = UsersWallet::where('currency',$project->currency_id)->where('user_id',$userId)->first(); + if(!$wallet){ + $walletId = UsersWallet::insertGetId([ + 'currency' => $project->currency_id, + 'user_id' => $userId, + 'address' => null, + 'create_time' => time() + ]); + }else{ + $walletId = $wallet->id; + } + $wallet = UsersWallet::where("user_id", $userId) + ->where("currency", $project->pay_currency_id) + ->lockForUpdate() + ->first(); + if(!$wallet){ + return $this->error('wallet not found'); + } + if($amount>$wallet->micro_balance){ + // var_dump([$project->pay_currency_id,$userId]); + return $this->error('钱包余额不足.'); + } + DB::beginTransaction(); + try{ + $result = change_wallet_balance($wallet, + 4, + -$amount, + AccountLog::IEO_OPERATION, + 'ieo order'); + if ($result !== true) { + throw new \Exception($result); + } + + // $result = change_wallet_balance($op_wallet, + // 2, + // $amount, + // AccountLog::IEO_OPERATION, + // 'ieo order'); + + $model = new CurrencyProjectOrder(); + $model->project_id = $project->id; + $model->u_id = $userId; + $model->currency_id = $project->currency_id; + $model->pay_currency_id = $project->pay_currency_id; + $model->coin_amount = null; + $model->price = null; + $model->total_price = $amount; + $model->created_at = date('Y-m-d H:i:s'); + $model->status = 2; + $model->type = 3; + $model->end_at = $project->end_at; + $model->wallet_id = $walletId; + $model->pay_wallet_id = $payWalletId; + $model->save(); + DB::commit(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + } + return $this->success('success'); + + } + + public function postOrder(Request $request){ + $id = $request->get('project_id'); + $amount = $request->get('amount'); + $userId = Users::getUserId(); + $project = CurrencyProject::find($id); + + if(!$project){ + return $this->error('找不到项目'); + } + + $project->pay_currency_id =3;//dapp项目只有USDT支付 + if($project->status != 1){ + return $this->error('状态异常'); + } + + if($amount<=0){ + return $this->error('参数错误'); + } + if($project->time_status != 2){ + return $this->error('项目已结束'); + } + if(bc_sub($project->amount,bc_add($amount,$project->total_sell,8))< 0){ + return $this->error('已售罄'); + } + //new wallet + $payWallet = UsersWallet::where('currency',$project->pay_currency_id)->where('user_id',$userId)->first(); + if(!$payWallet){ + $payWalletId = UsersWallet::insertGetId([ + 'currency' => $project->pay_currency_id, + 'user_id' => $userId, + 'address' => null, + 'create_time' => time() + ]); + }else{ + $payWalletId = $payWallet->id; + } + $wallet = UsersWallet::where('currency',$project->currency_id)->where('user_id',$userId)->first(); + if(!$wallet){ + $walletId = UsersWallet::insertGetId([ + 'currency' => $project->currency_id, + 'user_id' => $userId, + 'address' => null, + 'create_time' => time() + ]); + }else{ + $walletId = $wallet->id; + } + + $wallet = UsersWallet::where("user_id", $userId) + ->where("currency", $project->pay_currency_id) + ->lockForUpdate() + ->first(); + if(!$wallet){ + return $this->error('找不到钱包'); + } + // $check = CurrencyProjectOrder::where('u_id',$userId)->where('project_id',$project->id)->first(); + // if($check){ + // return $this->error('already apply'); + // } + $op_wallet = UsersWallet::where('user_id',$userId) + ->where('currency',$project->currency_id) + ->first(); + if(!$op_wallet){ + return $this->error('找不到钱包'); + } + $price = bc_mul($project->price,$amount,8); + if($price>$wallet->micro_balance){ + // var_dump([$project->pay_currency_id,$userId]); + return $this->error('钱包余额不足'); + } + + DB::beginTransaction(); + try{ + $result = change_wallet_balance($wallet, + 4, + -$price, + AccountLog::IEO_OPERATION, + 'ieo 项目'); + if ($result !== true) { + throw new \Exception($result); + } + + // $result = change_wallet_balance($op_wallet, + // 2, + // $amount, + // AccountLog::IEO_OPERATION, + // 'ieo order'); + + $model = new CurrencyProjectOrder(); + $model->project_id = $project->id; + $model->u_id = $userId; + $model->currency_id = $project->currency_id; + $model->pay_currency_id = $project->pay_currency_id; + $model->coin_amount = $amount; + $model->price = $project->price; + $model->total_price = $price; + $model->created_at = date('Y-m-d H:i:s'); + $model->status = 2; + $model->type = 1; + $model->end_at = $project->end_at; + $model->wallet_id = $walletId; + $model->pay_wallet_id = $payWalletId; + $model->save(); + // 更新一出手 + $project->total_sell += $amount; + $project->save(); + DB::commit(); + }catch (\Exception $e){ + DB::rollBack(); + return $this->error($e->getMessage()); + } + return $this->success('成功'); + + + } + + public function userOrder(Request $request) + { + $user_id = Users::getUserId(); + $page = $request->get('page',1); + $limit = $request->get('limit',10); + $status = $request->get('status',0); //新加的参数区分认购和配售列表 + $lists = DB::table('currency_project_order') + ->join('currency_project', 'currency_project.id', '=', 'currency_project_order.project_id') + ->join('currency', 'currency.id', '=', 'currency_project.currency_id') + ->where('currency_project_order.u_id',$user_id)->where('currency_project_order.status',$status) + ->orderBy('currency_project_order.id', 'desc') + ->select('currency_project_order.created_at', + 'currency.name', + 'currency_project_order.coin_amount', + 'currency_project.sell_begin', + 'currency_project_order.id', + 'currency_project_order.status' + ) + ->paginate($limit); + + foreach ($lists->items() as &$item) { + $item->give_amount = 0; + if ($item->status == 3){ + $item->give_amount = $item->coin_amount; + } + } + unset($item); + + $result = array('data' => $lists->items(), 'page' => $page, 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + +} diff --git a/app/Http/Controllers/Api/DefaultController.php b/app/Http/Controllers/Api/DefaultController.php new file mode 100644 index 0000000..f99321f --- /dev/null +++ b/app/Http/Controllers/Api/DefaultController.php @@ -0,0 +1,417 @@ +", $old_time)->where("time", "<", $time)->sum('price'); + $today = FalseData::where('time', ">", $time)->sum('price'); + + $data = FalseData::orderBy('id', 'DESC')->paginate($limit); + + return $this->success(array( + "data" => $data->items(), + "limit" => $limit, + "page" => $page, + "yesterday" => $yesterday, + "today" => $today + )); + } + + public function quotation() + { + $result = Market::limit(20)->get(); + return $this->success(array( + "coin_list" => $result + )); + } + + public function historicalData() + { + $day = HistoricalData::where("type", "day")->orderBy('id', 'asc')->get(); + $week = HistoricalData::where("type", "week")->orderBy('id', 'asc')->get(); + $month = HistoricalData::where("type", "month")->orderBy('id', 'asc')->get(); + + return $this->success(array( + "day" => $day, + "week" => $week, + "month" => $month + )); + } + + public function quotationInfo() + { + $id = Input::get("id"); + if (empty($id)) + return $this->error("参数错误"); + + // $coin_list = RPC::apihttp("https://api.coinmarketcap.com/v2/ticker/".$id."/"); + $coin_list = Market::find($id); + + // $coin_list = @json_decode($coin_list,true); + + return $this->success($coin_list); + } + + public function dataGraph() + { + $data = Setting::getValueByKey("chart_data"); + if (empty($data)) + return $this->error("暂无数据"); + + $data = json_decode($data, true); + return $this->success(array( + "data" => array( + $data["time_one"], + $data["time_two"], + $data["time_three"], + $data["time_four"], + $data["time_five"], + $data["time_six"], + $data["time_seven"] + ), + "value" => array( + $data["price_one"], + $data["price_two"], + $data["price_three"], + $data["price_four"], + $data["price_five"], + $data["price_six"], + $data["price_seven"] + ), + "all_data" => $data + )); + } + + public function index() + { + $coin_list = RPC::apihttp("https://api.coinmarketcap.com/v2/ticker?limit=10"); + $coin_list = @json_decode($coin_list, true); + + if (! empty($coin_list["data"])) { + foreach ($coin_list["data"] as &$d) { + if ($d["total_supply"] > 10000) { + $d["total_supply"] = substr($d["total_supply"], 0, - 4) . "万"; + } + } + } + return $this->success(array( + "coin_list" => $coin_list["data"] + )); + } + + //上传NFT文件 + public function uploadNFT(Request $request) + { + /* 对图像文件进行严格检测 */ + // $arr = ['image/jpg','image/jpeg','image/png','image/gif']; + // $file = $request->file('file'); + // $imginfo = getimagesize($file->getRealPath()); + // if(empty($imginfo) || empty($imginfo['bits']) || !in_array($imginfo['mime'],$arr)){ + // return $this->error("wrong format"); + // } + + if (! empty($_FILES["file"]["error"])) { + return $this->error($_FILES["file"]["error"]); + } else { + if ($_FILES["file"]["size"] > 10485760) { + return $this->error("文件大小超出"); + } + + $type = strtolower(substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.') + 1)); // 得到文件类型,并且都转化成小写 + $wenjian_name = time() . rand(0, 999999) . "." . $type; + $filename = "./upload_nft/" . $wenjian_name; + // 转码,把utf-8转成gb2312,返回转换后的字符串, 或者在失败时返回 FALSE。 + $filename = iconv("UTF-8", "gb2312", $filename); + // 检查文件或目录是否存在 + if (file_exists($filename)) { + return $this->error("该文件已存在"); + } else { + // var_dump($filename);die; + move_uploaded_file($_FILES["file"]["tmp_name"], $filename); + return $this->success("/upload_nft/" . $wenjian_name); + } + } + } + + public function upload(Request $request) + { + /* 对图像文件进行严格检测 */ + $arr = ['image/jpg','image/jpeg','image/png']; + $file = $request->file('file'); + $imginfo = getimagesize($file->getRealPath()); + if(empty($imginfo) || empty($imginfo['bits']) || !in_array($imginfo['mime'],$arr)){ + return $this->error("wrong format"); + } + + if (! empty($_FILES["file"]["error"])) { + return $this->error($_FILES["file"]["error"]); + } else { + // if($_FILES["file"]["size"] > 204800){ + // return $this->error("文件大小超出"); + // } + if ($_FILES["file"]["size"] > 10485760) { + return $this->error("文件大小超出"); + } + // return $this->success($_FILES["file"]["type"]); + if ($_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/png" || $_FILES["file"]["type"] == "image/jpeg") { + $type = strtolower(substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.') + 1)); // 得到文件类型,并且都转化成小写 + $wenjian_name = time() . rand(0, 999999) . "." . $type; + // 防止文件名重复 + // 超哥写的上传路径 + // $url = config('app.images_url'); + // $url = \think\Env::get('IMAGS_URL','./upload/'); + // $filename = $url.$wenjian_name; + // $filename ="/www/wwwroot/imgs.bitfor-ex.com/upload/".$wenjian_name; + $filename = "./upload/" . $wenjian_name; + // 转码,把utf-8转成gb2312,返回转换后的字符串, 或者在失败时返回 FALSE。 + $filename = iconv("UTF-8", "gb2312", $filename); + // 检查文件或目录是否存在 + if (file_exists($filename)) { + return $this->error("该文件已存在"); + } else { + // var_dump($filename);die; + move_uploaded_file($_FILES["file"]["tmp_name"], $filename); + return $this->success("/upload/" . $wenjian_name); + } + } else { + return $this->error("文件类型不对"); + } + } + } + + public function upload_new(Request $request) + { + // return 2453; + /* 对图像文件进行严格检测 */ + $arr = ['image/jpg','image/jpeg','image/png']; + $file = $request->file('file'); + $imginfo = getimagesize($file->getRealPath()); + if(empty($imginfo) || empty($imginfo['bits']) || !in_array($imginfo['mime'],$arr)){ + return $this->error("wrong format"); + } + + if (! empty($_FILES["file"]["error"])) { + return $this->error($_FILES["file"]["error"]); + } else { + // if($_FILES["file"]["size"] > 204800){ + // return $this->error("文件大小超出"); + // } + if ($_FILES["file"]["size"] > 10485760) { + return $this->error("文件大小超出"); + } + // return $this->success($_FILES["file"]["type"]); + if ($_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/png" || $_FILES["file"]["type"] == "image/jpeg") { + $type = strtolower(substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.') + 1)); // 得到文件类型,并且都转化成小写 + $wenjian_name = time() . rand(0, 999999) . "." . $type; + // 防止文件名重复 + // 超哥写的上传路径 + // $url = config('app.images_url'); + // $url = \think\Env::get('IMAGS_URL','./upload/'); + // $filename = $url.$wenjian_name; + // $filename ="/www/wwwroot/imgs.bitfor-ex.com/upload/".$wenjian_name; + $filename = "./upload/" . $wenjian_name; + // 转码,把utf-8转成gb2312,返回转换后的字符串, 或者在失败时返回 FALSE。 + $filename = iconv("UTF-8", "gb2312", $filename); + // 检查文件或目录是否存在 + if (file_exists($filename)) { + return $this->error("该文件已存在"); + } else { + // var_dump($filename);die; + move_uploaded_file($_FILES["file"]["tmp_name"], $filename); + return $this->success("/upload/" . $wenjian_name); + } + } else { + return $this->error("文件类型不对"); + } + } + + /* 对图像文件进行严格检测 */ + $arr = ['image/jpg','image/jpeg','image/png']; + $file = $request->file('file'); + $imginfo = getimagesize($file->getRealPath()); + if(empty($imginfo) || empty($imginfo['bits']) || !in_array($imginfo['mime'],$arr)){ + return $this->error("wrong format"); + } + + if (! empty($_FILES["file"]["error"])) { + return $this->error($_FILES["file"]["error"]); + } else { + // if($_FILES["file"]["size"] > 204800){ + // return $this->error("文件大小超出"); + // } + if ($_FILES["file"]["size"] > 10485760) { + return $this->error("文件大小超出"); + } + // return $this->success($_FILES["file"]["type"]); + if ($_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/png" || $_FILES["file"]["type"] == "image/jpeg") { + $type = strtolower(substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.') + 1)); // 得到文件类型,并且都转化成小写 + $wenjian_name = time() . rand(0, 999999) . "." . $type; + // 防止文件名重复 + // 超哥写的上传路径 + $url = config('app.images_url'); + // $url = \think\Env::get('IMAGS_URL','./upload/'); + $filename = $url.$wenjian_name; + // $filename ="/www/wwwroot/imgs.bitfor-ex.com/upload/".$wenjian_name; + // $filename = "./upload/" . $wenjian_name; + // 转码,把utf-8转成gb2312,返回转换后的字符串, 或者在失败时返回 FALSE。 + $filename = iconv("UTF-8", "gb2312", $filename); + // 检查文件或目录是否存在 + if (file_exists($filename)) { + return $this->error("该文件已存在"); + } else { + // var_dump($_FILES["file"]["tmp_name"]);die; + move_uploaded_file($_FILES["file"]["tmp_name"], $filename); + return $this->success("/upload/" . $wenjian_name); + } + } else { + return $this->error("文件类型不对"); + } + } + } + + // ios 文件上传 + public function upload2(Request $request) + { + $base64_image_content = $request->input('base64_file', ''); + $res = self::base64_image_content($base64_image_content); + if (! $res) { + return $this->error('上传失败'); + } + + return $this->success($res); + } + + /* base64格式编码转换为图片并保存对应文件夹 */ + public function base64_image_content($base64_image_content) + { + // 匹配出图片的格式 + if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) { + $type = $result[2]; + if (! in_array($type, [ + 'jpg', + 'jpeg', + 'png' + ])) { + return false; + } + // $new_file = $path."/".date('Ymd',time())."/"; + $path = '/upload/' . date('Ymd') . '/'; + $new_file = public_path() . $path; + if (! file_exists($new_file)) { + // 检查是否有该文件夹,如果没有就创建,并给予最高权限 + mkdir($new_file, 0700); + } + $filename = time() . rand(0, 999999) . ".{$type}"; + $full_file = $new_file . $filename; + if (file_put_contents($full_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) { + return url('') . $path . $filename; + } else { + return false; + } + } else { + return false; + } + } + + public function getNode(\Illuminate\Http\Request $request) + { + $user_id = $request->get('user_id', 0); + $show_message["real_teamnumber"] = Users::find($user_id)->real_teamnumber; + $show_message["top_upnumber"] = Users::find($user_id)->top_upnumber; + $show_message["today_real_teamnumber"] = Users::find($user_id)->today_real_teamnumber; + $account_number = $request->get('account_number', null); + if (! empty($account_number)) { + $user_id_search = Users::where('account_number', $account_number)->first(); + if (! empty($user_id_search)) { + $user_id = $user_id_search->id; + } else { + $user_id = 0; + } + } + // if (empty($user_id)){ + $users = Users::where('parent_id', $user_id)->get(); + $results = array(); + foreach ($users as $key => $user) { + $results[$key]['name'] = $user->account_number; + $results[$key]['id'] = $user->id; + $results[$key]['parent_id'] = $user->parent_id; + } + $data["show_message"] = $show_message; + $data["results"] = $results; + return $this->success($data); + } + + public function getVersion() + { + $version = Setting::getValueByKey('version', '1.0'); + return $this->success($version); + } + + public function getBanks() + { + $result = Bank::all(); + return $this->success($result); + } + + public function language(Request $request) + { + $lang = $request->get('lang', 'zh'); + session()->put('lang', $lang); + return $this->success($lang); + } + + public function getMenu() + { + $menu = Menu::where('show', 1)->orderBy('sort','asc')->get(); + return $this->success($menu); + } + + public function getSiteConfig(Request $request) { + // $user_id = Users::getUserId(); + $user_id = $request->get('user_id', 1); + $model = Setting::whereIn('key', ['site_name', 'site_logo','site_pc_logo', 'down_logo','open_url','sharar_radio','reverse_radio','email_radio' + ,'zxkf_radio','zxkf_url','telegram_url','telegram_radio','skype_radio','skype_url','whatsApp_radio','DAPP_DEMO','H5_DEMO','example_radio' + ,'whatsApp_url','line_radio','line_url','jie_radio','jie_url','hk_radio','hk_url','bank_flag','image_server_url','tk_radio','yzm_radio','ios_apk_download_url','apk_download_url','mobile_register','web_mail','facebook','twitter','facebook_url','twitter_url','password_radio' + ])->get(); + $settings = []; + foreach ($model as $setting) { + $settings[$setting->key] = $setting->value; + } + + $settings['code'] = Users::find($user_id)['extension_code']; + return $this->success($settings); + } + public function US(){ + return $this->success('success'); + //$this->success(json_decode(file_get_contents("https://www.mycurrency.net/US.json"),true)); + } + // public function getlanguage(\Request $request) + // { + // $lang=session()->get('lang'); + // return $this->success($lang); + // } +} +?> \ No newline at end of file diff --git a/app/Http/Controllers/Api/DefiController.php b/app/Http/Controllers/Api/DefiController.php new file mode 100644 index 0000000..f765e6c --- /dev/null +++ b/app/Http/Controllers/Api/DefiController.php @@ -0,0 +1,389 @@ +error('error!'); + } + $data['lianghua_amount'] = 0; //货币数量 + $data['todayincome'] = 0; // 今日收益 + $data['totalincome'] = 0; // 总收益 + $data['rate'] = 0.00; // 回报 + $nowday = date('Ymd',time()); + $nowtime = date('Y-m-d H:i:s',time()); + $info['data'] = DualCurrency::where('status',1)->orderBy('days','ASC')->get(); + + // return $this->error($nowday); + + // $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('amount'); + /* + $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('expire','>=',$nowtime)->where('created','<=',$nowtime)->sum('amount'); + $data['todayincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + + $data['totalincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('totalincome'); + */ + $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('status',0)->sum('amount'); + $data['todayincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + + $data['totalincome'] = DualOrder::where('user_id',$user_id)->sum('totalincome'); + + + if($data['lianghua_amount']>0) $data['rate'] = round(bcdiv($data['todayincome'],$data['lianghua_amount'],4)*100,4); // 回报率 + + + + $info = array_merge($info,$data); + + + + + + return $this->success($info); + + } + + // Request $request + public function defiList(Request $request){ + $limit = $request->get('limit', 100); + $user_id = Users::getUserId(); + $data = Defi::where('is_del',0)->orderBy('days', 'asc')->select('id','days','bilv','percent','fwamount')->paginate($limit); + + + + $account = UsersWallet::where('user_id',$user_id)->where('currency',3)->value('change_balance')??"0.00"; //可用USDT + + $amount = DefiOrder::where('user_id',$user_id)->where('review_status',2)->sum('amount')??"0.00"; //已借USDT + $remainamount = DefiOrder::where('user_id',$user_id)->where('review_status',2)->where('status',0)->sum('total')??"0.00"; //已借USDT + + $user['usdt_balance'] = round($account,2);//$userInfo['usdt_balance']; + $user['amount'] = $amount;//$userInfo['usdt_balance']; + $user['percent'] = 0.3; + $user['remainamount'] = $remainamount;//$userInfo['usdt_balance']; + + return $this->success(array( + "data" => $data, + "user" => $user, + )); + + } + + + + + //返回质押列表 + public function orderList(Request $request) + { + $page = $request->get('page', 1); + $limit = $request->get('limit',10); + $status=$request->get('status', 0); + $user_id = Users::getUserId();//66005883; + // $where['review_status'] = ['>', 0]; + // $where['status']= $status; + + + $lists = DefiOrder::where('status',$status) + ->where('user_id',$user_id) + ->paginate($limit); + + + + $result = array('data' => $lists->items(), 'page' => $page, 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + + + //购买 $param + public function Buy(Request $request) + { + $user_id = Users::getUserId(); + // + + // $userInfo['id']=1; + // $param['daysId']=3; + // $request->post('amount'] = 1136.5; + + + + $id = $request->post('daysId'); + $yamount = $request->post('amount'); //验资金额 + $amount = bcmul($yamount,0.30,2);//借币金额 + + + + $info = Defi::find($id); + + + $days = $info['days'];//质押期限 + $lv_perday = $info['bilv'];//日币利息 + + $opayment = 0;//滞纳金 + $opaymentlv = $info['opaymentlv'];//滞纳金百分比 + $fwamount = $info['fwamount'];//总服务费 + + + $lixi = bcmul($amount*$days,$lv_perday/100,2); //利息 + + $total = $amount+$fwamount+$lixi; //本金+利息 + $review_status =1; + // $account = $userInfo['account']; + $account = UsersWallet::where('user_id',$user_id)->where('currency',3)->value('change_balance')??"0.00"; //可用USDT + + //return Response::fail($account); + + + + // return Response::fail($yamount); + if ($account < $yamount) { + return $this->error('Insufficient Balance'); + } + + $currentTime = date('Y-m-d H:i:s',time()); + $orderData['htcode'] = 'Y' . date('YmdHis') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT); + $orderData['user_id'] = $user_id; + $orderData['amount'] = $amount; + $orderData['yamount'] = $yamount; + $orderData['fwamount'] = $fwamount; + $orderData['lixi'] = $lixi; + $orderData['total'] = $total; + $orderData['days'] = $days; + $orderData['create_time'] = $currentTime; + $orderData['lv_perday'] = $lv_perday; + $orderData['opaymentlv'] = $opaymentlv; + + $orderData['name'] = $request->post('name'); + $orderData['last'] = $request->post('last'); + + $orderData['address'] = $request->post('address'); + $orderData['mail'] = $request->post('mail'); + $orderData['tel'] = $request->post('tel'); + $orderData['signature'] = $request->post('signature'); + $orderData['signatureUrl'] = $request->post('signatureUrl'); + + + // file_put_contents('/www/wwwroot/nft/public/t.txt',json_encode($orderData)); + + + + DB::beginTransaction(); + try { + $order_id = Db::table('defi_order')->insert($orderData); + + DB::commit(); + return $this->success('success'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + + //质押详情 + public function Detail(Request $request) + { + $id = $request->post('id'); + $info = DefiOrder::where('id',$id)->select('htcode','review_time','end_time','bamount','remainamount','status')->first(); + + return $this->success($info); + } + + //理财撤单 + public function Dualcancle(Request $request){ + $id = $request->post('id'); + + $user_id = Users::getUserId(); + + + if(empty($id) || !is_numeric($id)){ + return $this->error('Parameter error:ID Is NULL'); + } + + $dual_order = DualOrder::where('id',$id)->where('status',0)->first(); + + $amount = $dual_order->amount; + if(empty($amount)){ + return $this->error('Parameter error:amount Is NULL'); + } + $liquidateddamages = $dual_order->liquidateddamages; + $todayincome = $dual_order->todayincome; + $totalincome= $dual_order->totalincome; + + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + + + + $dual_order->status = 1; + $dual_order->amount = 0; + $dual_order->todayincome=0; + $dual_order->totalincome=0; + $amount = $amount - $amount*$liquidateddamages/100; + + + + $result = change_wallet_balance($user_walllet , 4 , $amount , AccountLog::USER_LOAN_ORDER_RETURN,'量化返本'); + if($result){ + $dual_order->save(); + return $this->success('操作成功'); + + } + + } + + + + + + + //购买理财 + public function buyDual(Request $request){ + $id = $request->post('id'); + $num = $request->post('num'); + $user_id = Users::getUserId(); + $num = intval($num); + + if(empty($num) || !is_numeric($num)){ + return $this->error('Parameter error:num '); + } + + if(empty($id) || !is_numeric($id)){ + return $this->error('Parameter error:ID Is NULL'); + } + + $user = Users::where('id', $user_id)->first(); + + + if ($user->frozen_funds == 1 || $user->status == 1) { + return $this->error('こんにちは、アカウントはロックされています。詳細はカスタマーサービスにお問い合わせください。'); + } + + // if(Cache::has("by_dual_order_$user_id")){ + // return $this->error('Do not repeat the operation!'); + // } + // Cache::put("by_dual_order_$user_id", 1, Carbon::now()->addSeconds(5));//禁止重复提交 + + // $count = DualOrder::where('user_id',$user_id)->where('dual_id',$id)->count(); + $dual_currencys = DualCurrency::where('id',$id)->first(); + if($num<$dual_currencys->amount) { + + return $this->error('Parameter error:num amount error'); + } + + if($num>$dual_currencys->amax) { + + return $this->error('Parameter error:num max error'); + } + + if($dual_currencys->status==0){ + + return $this->error('売り切れ'); + } + + if($num<$dual_currencys->amax) { + + $rate = $dual_currencys->rate; + } + + if($num==$dual_currencys->amax) { + + $rate = $dual_currencys->ratemax; + } + + + $expire = time()+$dual_currencys->days*24*60*60; + //if($dual_currencys->end_time <= date('Y-m-d') || $dual_currencys->status == 0){//结束时间等于今天不可购买 + // return $this->error('Project has ended!'); + // } + // if($num > $dual_currencys->remaining_number){//已经卖完 + // return $this->error('Sold out!'); + // } + + // if($count + $num > $dual_currencys->user_limit){ + // return $this->error('Purchase limit exceeded!'); + // } + + + + + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + if($user_walllet->micro_balance < $num){ + return $this->error('Insufficient balance!'); + } + + + DB::beginTransaction(); + try{ + // $d1=strtotime($dual_currencys->end_time); + // $d2 = strtotime(date('Y-m-d')); + // $dayCount=round(($d1- $d2)/3600/24); + $dual_order = new DualOrder(); + $dual_order->user_id = $user_id; + // $dual_order->currency_id = $buy_currency;//用户购买时消耗的币种 + // $dual_order->dual_id = $dual_currencys->id; + + $dual_order->order_rate = $rate; + $dual_order->dual_id = $id; + $dual_order->rate = $dual_currencys->rate."-".$dual_currencys->ratemax; + $dual_order->day = $dual_currencys->days; + $dual_order->amount = $num; + $dual_order->expire = date('Y-m-d H:i:s',$expire); + $dual_order->orderid =date("YmdHis",time()).$expire; + $dual_order->liquidateddamages = $dual_currencys->liquidateddamages; + // $dual_order->price = $now_price; + // $dual_order->total = $total; + $dual_order->startdate =date('Y-m-d H:i:s',time()+86400); + $dual_order->created = date('Y-m-d H:i:s'); + + + // $dual_currencys->refresh(); + // if($num > $dual_currencys->remaining_number || $count + $num > $dual_currencys->user_limit){//已经卖完 + // DB::rollBack(); + // return $this->error('Sold out!'); + // } + + // $dual_currencys->remaining_number = $dual_currencys->remaining_number - $num; + // $dual_currencys->purchased_number = $dual_currencys->purchased_number + $num; + // $dual_currencys->save(); + + $result = change_wallet_balance($user_walllet , 4 , -$num , AccountLog::USER_DUAL_ORDER_BUY,'量化扣除'); + if($result) $dual_order->save(); + + DB::commit(); + return $this->success('Successful'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function getDetail(Request $request){ + $dual_id = $request->get('id'); + $dual = DualCurrency::where('id',$dual_id)->first(); + + return $this->success($dual); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/DualController.php b/app/Http/Controllers/Api/DualController.php new file mode 100644 index 0000000..1430d5a --- /dev/null +++ b/app/Http/Controllers/Api/DualController.php @@ -0,0 +1,330 @@ + 0 ? UserLevelModel::find($user['user_level']) : 'V0'; + $data['lianghua_amount'] = 0; //货币数量 + $data['todayincome'] = 0; // 今日收益 + $data['totalincome'] = 0; // 总收益 + $data['rate'] = 0.00; // 回报 + $nowday = date('Ymd',time()); + $nowtime = date('Y-m-d H:i:s',time()); + $info['data'] = DualCurrency::where('status',1)->select("id","invest","hot","days","ratemax","amount","amax","remaining_number")->orderBy('days','ASC')->get(); + $invest ="BTC+ETH+ATOM+SOL"; + $invest = explode("+",$invest); + $arr =[]; + foreach ($invest as $k=>$v){ + + $Currencys = Currency::where('name',$v)->first(); + $arr[$k]['name']= $v; + $arr[$k]['logo']= $Currencys->logo; + + // $arr[$k]['change']= CurrencyQuotation::where('currency_id',$Currencys->id)->value('change'); + $arr[$k]['now_price']= CurrencyQuotation::where('currency_id',$Currencys->id)->value('now_price'); + } + // return $this->error($nowday); + + // $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('amount'); + /* + $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('expire','>=',$nowtime)->where('created','<=',$nowtime)->sum('amount'); + $data['todayincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + + $data['totalincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('totalincome'); + */ + if($user_id){ + $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('status',0)->sum('amount'); + $data['todayincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + + $data['totalincome'] = DualOrder::where('user_id',$user_id)->sum('totalincome'); + + + if($data['lianghua_amount']>0) $data['rate'] = round(bcdiv($data['todayincome'],$data['lianghua_amount'],4)*100,4); // 回报率 + } + $data['VIP'] = $user['user_level'] > 0 ?$userLevel['name'] : 'V0'; + + $info = array_merge($info,$data); + + + + + + return $this->success(array("info"=>$info,"currency"=>$arr)); + + } + + //查看我的理财订单 + public function dual_list(Request $request){ + $limit = $request->get('limit', 100); + $status = $request->get('status',0); + + $user_id = Users::getUserId(); + + $user = Users::find($user_id); + + + + $userLevel = $user['user_level'] > 0 ? UserLevelModel::find($user['user_level']) : 'V0'; + // $list = DB::table('dual_order')->select('dual_order.*','dual_currency.name')->join('dual_currency', 'dual_currency.id', '=', 'dual_order.dual_id')->where('dual_order.user_id', $user_id)->where('dual_order.status', $status)->orderBy('dual_order.id', 'desc')->paginate($limit); + + $list = DualOrder::where('user_id', $user_id)->where('status', $status)->select('id','name','amount','totalincome','invest','startdate','expire','status')->orderBy('id', 'desc')->paginate($limit); + + return $this->success(array( + "list" => $list->items(), + "limit" => $limit, + 'VIP'=> $user['user_level'] > 0 ?$userLevel['name'] : 'V0' + )); + } + + + //理财撤单 + public function Dualcancle(Request $request){ + $id = $request->post('id'); + + $user_id = Users::getUserId(); + + + if(empty($id) || !is_numeric($id)){ + return $this->error('Parameter error:ID Is NULL'); + } + + $dual_order = DualOrder::where('id',$id)->where('status',0)->first(); + + $amount = $dual_order->amount; + if(empty($amount)){ + return $this->error('Parameter error:amount Is NULL'); + } + $liquidateddamages = $dual_order->liquidateddamages; + $todayincome = $dual_order->todayincome; + $totalincome= $dual_order->totalincome; + + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + + + // $dual_order->remaining_number = $dual_order->remaining_number +1; + // $dual_order->purchased_number = $dual_order->purchased_number -1; + $dual_order->status = 1; + $dual_order->amount = 0; + $dual_order->todayincome=0; + $dual_order->totalincome=0; + $amount = $amount - $amount*$liquidateddamages/100; + + + + $result = change_wallet_balance($user_walllet , 2 , $amount , AccountLog::USER_LOAN_ORDER_RETURN,'组合投资返本'); + if($result){ + $dual_order->save(); + return $this->success('操作成功'); + + } + + } + + + + + + + //购买理财 + public function buyDual(Request $request){ + $id = $request->post('id'); + $num = $request->post('num'); + $user_id = Users::getUserId(); + $num = intval($num); + + if(empty($num) || !is_numeric($num)){ + return $this->error('Parameter error:num '); + } + + if(empty($id) || !is_numeric($id)){ + return $this->error('Parameter error:ID Is NULL'); + } + + $user = Users::where('id', $user_id)->first(); + + + if ($user->frozen_funds == 1 || $user->status == 1) { + return $this->error('Hello, Account is Locked. Please contact customer service for details.'); + } + + // if(Cache::has("by_dual_order_$user_id")){ + // return $this->error('Do not repeat the operation!'); + // } + // Cache::put("by_dual_order_$user_id", 1, Carbon::now()->addSeconds(5));//禁止重复提交 + + // $count = DualOrder::where('user_id',$user_id)->where('dual_id',$id)->count(); + $dual_currencys = DualCurrency::where('id',$id)->first(); + if($num<$dual_currencys->amount) { + + return $this->error('Parameter error:num amount error'); + } + + if($num>$dual_currencys->amax) { + + return $this->error('Parameter error:num max error'); + } + + if($dual_currencys->status==0){ + + return $this->error('Sold out'); + } + + if($num<$dual_currencys->amax) { + + $rate = $dual_currencys->rate; + } + + if($num==$dual_currencys->amax) { + + $rate = $dual_currencys->ratemax; + } + + + $expire = time()+$dual_currencys->days*24*60*60; + //if($dual_currencys->end_time <= date('Y-m-d') || $dual_currencys->status == 0){//结束时间等于今天不可购买 + // return $this->error('Project has ended!'); + // } + if(1 > $dual_currencys->remaining_number){//已经卖完 + return $this->error('Sold out!'); + } + + // if($count + $num > $dual_currencys->user_limit){ + // return $this->error('Purchase limit exceeded!'); + // } + + $invest = $invest0 = $dual_currencys->invest; + $invest = explode("+",$invest); + $investr =''; + foreach ($invest as $k=>$v){ + $rate = DualOrder::random_float(10.18,25.88); // 生成一个介于0到1之间的随机小数 + $investr .=$v." ".number_format($rate,2).'%'." "; + + } + + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + if($user_walllet->change_balance < $num){ + return $this->error('Insufficient balance!'); + } + + + DB::beginTransaction(); + try{ + // $d1=strtotime($dual_currencys->end_time); + // $d2 = strtotime(date('Y-m-d')); + // $dayCount=round(($d1- $d2)/3600/24); + $dual_order = new DualOrder(); + $dual_order->user_id = $user_id; + // $dual_order->currency_id = $buy_currency;//用户购买时消耗的币种 + // $dual_order->dual_id = $dual_currencys->id; + + $dual_order->order_rate = $rate; + $dual_order->dual_id = $id; + $dual_order->name = $invest0; + $dual_order->invest = $investr; + $dual_order->rate = $dual_currencys->rate."-".$dual_currencys->ratemax; + $dual_order->day = $dual_currencys->days; + $dual_order->amount = $num; + $dual_order->expire = date('Y-m-d H:i:s',$expire); + $dual_order->orderid =date("YmdHis",time()).$expire; + $dual_order->liquidateddamages = $dual_currencys->liquidateddamages; + // $dual_order->price = $now_price; + // $dual_order->total = $total; + $dual_order->startdate =date('Y-m-d H:i:s'); + $dual_order->created = date('Y-m-d H:i:s'); + + + // $dual_currencys->refresh(); + // if($num > $dual_currencys->remaining_number || $count + $num > $dual_currencys->user_limit){//已经卖完 + // DB::rollBack(); + // return $this->error('Sold out!'); + // } + + $dual_currencys->remaining_number = $dual_currencys->remaining_number - 1; + $dual_currencys->purchased_number = $dual_currencys->purchased_number + 1; + $dual_currencys->save(); + + $result = change_wallet_balance($user_walllet , 2 , -$num , AccountLog::USER_DUAL_ORDER_BUY,'组合投资扣除'); + if($result) $dual_order->save(); + + DB::commit(); + return $this->success('Successful'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function getDetail(Request $request){ + $dual_id = $request->get('id'); + $dual = DualCurrency::where('id',$dual_id)->select('id','invest','days','ratemax','amount','amax','commission')->first(); + $invest = explode("+",$dual->invest); + $arr =[]; + foreach ($invest as $k=>$v){ + + $Currencys = Currency::where('name',$v)->first(); + $arr[$k]['name']= $v; + $arr[$k]['logo']= $Currencys->logo; + + $arr[$k]['change']= CurrencyQuotation::where('currency_id',$Currencys->id)->value('change'); + + } + $user_id = Users::getUserId(); + $account = UsersWallet::where('user_id',$user_id)->where('currency',3)->value('change_balance')??"0.00"; //可用USDT + // print_r($arr);exit; + return $this->success(array( + "detail" => $dual, + "Currency" => $arr, + 'balance' => $account, + )); + // return $this->success($dual); + } + + + +public function order_detail(Request $request){ + $id =$request->get('id'); + $dual = DualList::where('order_id',$id)->select('id','amount','addtime')->orderBy('id','ASC')->get(); + $total= DualList::where('order_id',$id)->sum('amount'); + foreach ($dual as $k=>$v){ + $dual[$k]['addtime']= date('Y-m-d H:i:s',$v->addtime); + } + return $this->success(array( + "detail" => $dual, + "total" => $total, + )); + + return $this->success($dual); + } + + +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/FeedBackController.php b/app/Http/Controllers/Api/FeedBackController.php new file mode 100644 index 0000000..1e264b7 --- /dev/null +++ b/app/Http/Controllers/Api/FeedBackController.php @@ -0,0 +1,103 @@ +orderBy('id', 'desc') + ->paginate($limit, ['*'], 'page', $page); + foreach ($feedBackList->items() as &$value) { + unset($value->replay_content); + } + return $this->success(array( + "list" => $feedBackList->items(), 'count' => $feedBackList->total(), + "page" => $page, "limit" => $limit + )); + } + //反馈信息内容,包括回复信息 + public function feedBackDetail(){ + $id = Input::get('id', 10); + $feedBack = FeedBack::find($id); + return $this->success($feedBack); + } + //提交反馈信息 + public function feedBackAdd(){ + $user_id = Users::getUserId(); + $content = Input::get('email', ''); + $content = Input::get('title', ''); + $content = Input::get('content', ''); + if(empty($content)){ + return $this->error('内容不能为空'); + } + $img = Input::get('img', ''); + try{ + $feedBack = new FeedBack(); + $feedBack->user_id = $user_id; + $feedBack->email = $email; + $feedBack->title = $title; + $feedBack->content = $content; + $feedBack->is_reply = 0; + $feedBack->img = $img; + $feedBack->create_time = time(); + $feedBack->save(); + return $this->success('提交成功,我们会尽快给你回复'); + } catch (\Exception $ex) { + return $this->error($ex->getMessage()); + } + } + + public function currencyAdd(){ + $user_id = Users::getUserId(); + $program = Input::get('program', ''); + + $currencyname = Input::get('currencyname', ''); + $currencyinfo = Input::get('currencyinfo', ''); + $contractaddress = Input::get('contractaddress', ''); + $weburl = Input::get('weburl', ''); + $linkname = Input::get('linkname', ''); + $linkemail = Input::get('linkemail', ''); + + if(empty($content)){ + return $this->error('内容不能为空'); + } + $img = Input::get('img', ''); + try{ + $feedBack = new CurrencyApplication(); + $feedBack->user_id = $user_id; + $feedBack->program = $program; + $feedBack->currencyname = $currencyname; + $feedBack->currencyinfo = $currencyinfo; + $feedBack->contractaddress = $contractaddress; + $feedBack->weburl = $weburl; + $feedBack->linkname = $linkname; + $feedBack->linkemail = $linkemail; + + $feedBack->is_reply = 0; + $feedBack->img = $img; + $feedBack->create_time = time(); + $feedBack->save(); + return $this->success('提交成功,我们会尽快给你回复'); + } catch (\Exception $ex) { + return $this->error($ex->getMessage()); + } + } + + +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/FollowController.php b/app/Http/Controllers/Api/FollowController.php new file mode 100644 index 0000000..b3c272d --- /dev/null +++ b/app/Http/Controllers/Api/FollowController.php @@ -0,0 +1,325 @@ +selectRaw('count(t.id) as closed_count') + ->selectRaw('IFNULL(sum(t.fact_profits),0) as total_profits') //总盈亏 + ->selectRaw('users.id,users.nickname,users.head_portrait,users.virtual_follow_num') + ->leftJoin('lever_transaction as t', function ($join) { + $join->on('users.id', '=', 't.user_id') + ->where('t.status', LeverTransaction::CLOSED); + }) + ->where('users.is_trader', 1) + ->groupBy('users.id') + ->orderBy('total_profits', 'desc') + ->paginate(); + + $list = $list->setCollection($list->getCollection()->map(function ($item) use ($user_id) { + //查询已平仓且盈利的总数 + $flat_count = LeverTransaction::query() + ->where([ + 'status' => LeverTransaction::CLOSED, + 'fact_profits' => ['>', 0], + 'user_id' => $item->id + ]) + ->count(); + //总准确率 + $item->correct_rate = $item->closed_count ? round($flat_count / $item->closed_count * 100, 2) : 0.00; + if (!empty($item->virtual_follow_num)) { + //跟随人数,有虚拟数则使用虚拟数 + $item->follow_num = $item->virtual_follow_num; + } else { + $item->follow_num = Follow::query()->where(['follow_user_id' => $item->id, 'status' => 1])->count(); + } + unset($item->virtual_follow_num); + + //查询当前交易员是否已跟随 + $item->is_followed = Follow::query() + ->where(['user_id' => $user_id, 'follow_user_id' => $item->id, 'status' => 1]) + ->exists(); + + return $item; + })); + + return $this->success($list); + } + + //跟随 + public function follow(Request $request) + { + try { + $user_id = Users::getUserId(); + $trader_user_id = $request->trader_user_id; + $type = $request->type; //跟随类型:1固定比例跟随 2固定手数跟随 + $number = $request->number; //跟随数量 + + if (!$trader_user_id) { + return $this->error('请选择交易员'); + } + if (!in_array($type, [1, 2])) { + return $this->error('跟随类型错误'); + } + if ($type == 1 && $number > 5) { + return $this->error('跟随倍数不能超过5倍'); + } + if ($type == 2 && $number > 5) { + return $this->error('跟随手数不能超过5手'); + } + $user = Users::query()->find($user_id); + if ($user->is_trader == 1) { + return $this->error('禁止交易员跟随'); + } + if (Users::where('id', $trader_user_id)->value('is_trader') != 1) { + return $this->error('交易员身份错误'); + } + + //同时最多跟随两个 + if (Follow::where(['user_id' => $user_id, 'status' => 1])->count() >= 2) { + return $this->error('最多跟随2名交易员'); + } + + Follow::updateOrCreate([ + 'user_id' => $user_id, + 'follow_user_id' => $trader_user_id, + ], [ + 'number' => $number, + 'type' => $type, + 'status' => 1 + ]); + + return $this->success('操作成功'); + } catch (\Throwable $ex) { + return $this->error('操作失败'); + } + } + + //取消跟随 + public function cancel(Request $request) + { + try { + $user_id = Users::getUserId(); + $follow = Follow::where(['user_id' => $user_id, 'follow_user_id' => $request->follow_user_id])->first(); + $follow->status = 2; + $follow->save(); + + return $this->success('操作成功'); + } catch (\Throwable $ex) { + return $this->error('操作失败'); + } + } + + + //交易员详情 + public function gdDetail() + { + $user_id = 12458401;//Users::getUserId(); + $trader_user_id = 66725072; + $user = Users::query() + ->where([ + 'id' => $trader_user_id, + 'is_trader' => 1 + ])->first(['id', 'is_trader', 'nickname', 'head_portrait', 'virtual_follow_num']); + if (empty($user)) { + return $this->error('交易员不存在'); + } + $transaction = LeverTransaction::query() + ->selectRaw('count(id) as closed_count') + ->selectRaw('IFNULL(sum(fact_profits),0) as total_profits') //总盈亏 + ->selectRaw('sum(fact_profits) / sum(origin_caution_money) as total_income_rate') //总收益率 + ->selectRaw('count( + CASE + WHEN fact_profits > 0 THEN + fact_profits + END + ) AS profitCount') //盈利订单 + ->selectRaw('count( + CASE + WHEN type = 2 THEN + type + END + ) AS fallCount') //成功做空交易 + ->selectRaw('count( + CASE + WHEN type = 1 THEN + type + END + ) AS riseCount') //成功做多交易 + ->where('status', LeverTransaction::CLOSED) + ->where('user_id', $trader_user_id) + ->first(); + $data['total_profits'] = $transaction['total_profits']; + $data['profitCount'] = $transaction['profitCount']; + $data['fallCount'] = $transaction['fallCount']; + $data['riseCount'] = $transaction['riseCount']; + $data['total_income_rate'] = bc_mul($transaction['total_income_rate'], 100, 2); //总收益率 + //准确率 + $data['correct_rate'] = bc_mul(bc_div($transaction['profitCount'], $transaction['closed_count']), 100, 2); + if (!empty($user->virtual_follow_num)) { + //跟随人数,有虚拟数则使用虚拟数 + $data['follow_num'] = $user->virtual_follow_num; + } else { + $data['follow_num'] = Follow::query()->where(['follow_user_id' => $user->id, 'status' => 1])->count(); + } + $yesterday = Carbon::yesterday(); + $yesterday_data = LeverTransaction::query() + ->selectRaw('sum(fact_profits) / sum(origin_caution_money) as profit') + ->where('status', LeverTransaction::CLOSED) + ->where('user_id', $trader_user_id) + ->where('handle_time', '>=', $yesterday->startOfDay()->timestamp . '.' . $yesterday->startOfDay()->micro) + ->where('handle_time', '<=', $yesterday->endOfDay()->timestamp . '.' . $yesterday->endOfDay()->micro) + ->first(); + $data['yesterday_profits'] = bc_mul($yesterday_data->profit, 100, 2); //昨日交易状况 + $data['position_count'] = LeverTransaction::query() + ->where('status', LeverTransaction::TRANSACTION) + ->where('user_id', $trader_user_id) + ->count(); //当前持仓 + $data['total_count'] = LeverTransaction::query() + ->where('user_id', $trader_user_id) + ->count(); //总订单 + + //查询当前交易员是否已跟随 + $is_followed = Follow::query() + ->where(['user_id' => $user_id, 'follow_user_id' => $trader_user_id, 'status' => 1]) + ->exists(); + + return $this->success([ + 'trader_info' => $user, + 'data' => $data, + 'is_followed' => $is_followed + ]); + } + + + //交易员详情 + public function traderDetail(Request $request) + { + $user_id = Users::getUserId(); + $trader_user_id = $request->trader_user_id; + $user = Users::query() + ->where([ + 'id' => $trader_user_id, + 'is_trader' => 1 + ])->first(['id', 'is_trader', 'nickname', 'head_portrait', 'virtual_follow_num']); + if (empty($user)) { + return $this->error('交易员不存在'); + } + $transaction = LeverTransaction::query() + ->selectRaw('count(id) as closed_count') + ->selectRaw('IFNULL(sum(fact_profits),0) as total_profits') //总盈亏 + ->selectRaw('sum(fact_profits) / sum(origin_caution_money) as total_income_rate') //总收益率 + ->selectRaw('count( + CASE + WHEN fact_profits > 0 THEN + fact_profits + END + ) AS profitCount') //盈利订单 + ->selectRaw('count( + CASE + WHEN type = 2 THEN + type + END + ) AS fallCount') //成功做空交易 + ->selectRaw('count( + CASE + WHEN type = 1 THEN + type + END + ) AS riseCount') //成功做多交易 + ->where('status', LeverTransaction::CLOSED) + ->where('user_id', $trader_user_id) + ->first(); + $data['total_profits'] = $transaction['total_profits']; + $data['profitCount'] = $transaction['profitCount']; + $data['fallCount'] = $transaction['fallCount']; + $data['riseCount'] = $transaction['riseCount']; + $data['total_income_rate'] = bc_mul($transaction['total_income_rate'], 100, 2); //总收益率 + //准确率 + $data['correct_rate'] = bc_mul(bc_div($transaction['profitCount'], $transaction['closed_count']), 100, 2); + if (!empty($user->virtual_follow_num)) { + //跟随人数,有虚拟数则使用虚拟数 + $data['follow_num'] = $user->virtual_follow_num; + } else { + $data['follow_num'] = Follow::query()->where(['follow_user_id' => $user->id, 'status' => 1])->count(); + } + $yesterday = Carbon::yesterday(); + $yesterday_data = LeverTransaction::query() + ->selectRaw('sum(fact_profits) / sum(origin_caution_money) as profit') + ->where('status', LeverTransaction::CLOSED) + ->where('user_id', $trader_user_id) + ->where('handle_time', '>=', $yesterday->startOfDay()->timestamp . '.' . $yesterday->startOfDay()->micro) + ->where('handle_time', '<=', $yesterday->endOfDay()->timestamp . '.' . $yesterday->endOfDay()->micro) + ->first(); + $data['yesterday_profits'] = bc_mul($yesterday_data->profit, 100, 2); //昨日交易状况 + $data['position_count'] = LeverTransaction::query() + ->where('status', LeverTransaction::TRANSACTION) + ->where('user_id', $trader_user_id) + ->count(); //当前持仓 + $data['total_count'] = LeverTransaction::query() + ->where('user_id', $trader_user_id) + ->count(); //总订单 + + //查询当前交易员是否已跟随 + $is_followed = Follow::query() + ->where(['user_id' => $user_id, 'follow_user_id' => $trader_user_id, 'status' => 1]) + ->exists(); + + return $this->success([ + 'trader_info' => $user, + 'data' => $data, + 'is_followed' => $is_followed + ]); + } + + //转自持 + public function selfHolding(Request $request) + { + try { + $user_id = Users::getUserId(); + $transaction_id = $request->transaction_id; + $transaction = LeverTransaction::query()->where([ + 'id' => $transaction_id, + 'user_id' => $user_id, + 'status' => LeverTransaction::TRANSACTION, + 'order_type' => 2 + ])->first(); + if (empty($transaction)) { + return $this->error('数据未找到'); + } + $transaction->order_type = 1; + $transaction->save(); + + return $this->success('操作成功'); + } catch (\Throwable $ex) { + return $this->error('操作失败'); + } + } + + //历史交易 + public function historyTrade(Request $request) + { + $trader_user_id = $request->trader_user_id; + $list = LeverTransaction::query() + ->where([ + 'user_id' => $trader_user_id, + 'status' => LeverTransaction::CLOSED, + 'order_type' => 1 + ]) + ->orderByDesc('id') + ->paginate(); + + return $this->success($list); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/IndexController.php b/app/Http/Controllers/Api/IndexController.php new file mode 100644 index 0000000..be2bad4 --- /dev/null +++ b/app/Http/Controllers/Api/IndexController.php @@ -0,0 +1,297 @@ + 0 && count(reset($need_param)) > count($param)) { + throw new \Exception('所需参数不匹配'); + } + $diff = array_diff(next($need_param), array_keys($param)); + if (count($diff) > 0) { + throw new \Exception('topic:' . $topic_template . '缺少参数:' . implode(',', $diff)); + } + return preg_replace_callback('/\$([a-zA-Z_]\w*)/', function ($matches) use ($param) { + extract($param); + $value = $matches[1]; + return $$value ?? ''; + }, $topic_template); + } + + public function test() + { + $period = '1min'; + $currency_match = CurrencyMatch::getHuobiMatchs(); + foreach ($currency_match as $key => $value) { + $param = [ + 'symbol' => $value->match_name, + 'period' => $period, + ]; + $topic = $this->makeSubscribeTopic('market.$symbol.kline.$period', $param); + $sub_data = json_encode([ + 'sub' => $topic, + 'id' => $topic, + //'freq-ms' => 5000, //推送频率,实测只能是0和5000,与官网文档不符 + ]); + print_r($sub_data); + } + exit(); + } + + + /** + * app U盾回调 (Request $request) + * @return string + */ + public function CallBack(Request $request) + { + // $request = $this->request->post(); + + $udun_apikey = config('app.udun_apikey'); + + $memberid = config('app.memberid'); + + + + + + //$request =NULL; + + + + + if(empty($request)){ + + + + $result = array("status_code"=>404,"message"=>"404 Not Found"); + + return json_encode($result); + + } + + + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') .json_encode($request) . "\n", FILE_APPEND); + /* + if(empty($request)){ + $body = '{"address":"0x4bc7709daa43fe0d08a5a55a9803fa00b066e4a3","amount":"5900000000","blockHigh":"47063475","coinType":"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t","decimals":"6","fee":"0","mainCoinType":"195","memo":"","status":3,"tradeId":"1055873104265670656","tradeType":1,"txId":"9769f20e483cecf5e51507589f70f849bdf55d202e44842eae6e02d4a13c2e60"}'; + $request = array('timestamp'=>'1671582782904','nonce'=>'EDVaD6','sign'=>'20bd4d025c6324bb0325d40957e19ca6','body'=>$body); + $account = 1; + if($account == 1){$sign='987425f704f48c8cd7c0c12ca6829055';} + } + + if(empty($request)){ + +$body = '{"address":"TLng7RobC5jcNtw1XPxoyMiiifEksYEosp","amount":"5000000","blockHigh":"60241722","coinType":"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t","decimals":"6","fee":"0","mainCoinType":"195","memo":"","status":3,"tradeId":"1221904373466329088","tradeType":1,"txId":"9f6d367313e4194e68cee9f1c7ff0b7bdfdab5ad1fbe4746a3760b36e4cd20c3"}'; + + $request = array('timestamp'=>'1711366306497','nonce'=>'5LtilG','sign'=>'c857c2755bf18c63823e7b7e048c8840','body'=>$body); + $account = 1; + if($account == 1){$sign='987425f704f48c8cd7c0c12ca6829055';} + + } + */ + //回调示例 + $call_back_data = array( + 'timestamp' => $request['timestamp'], + 'nonce' => $request['nonce'], + 'sign' => $request['sign'], + 'body' => $request['body'], + ); + + + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" .json_encode($call_back_data) . "\n", FILE_APPEND); + + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" .'body: ' . $call_back_data['body'] . "\n", FILE_APPEND); + + $sign = md5($call_back_data['body'] . $udun_apikey . $call_back_data['nonce'] . $call_back_data['timestamp']); + + + + // file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') .'nonce:'. $call_back_data['nonce']."-sign:".$call_back_data['sign']."--------".$sign ."--timestamp:".$request['timestamp']. "\n", FILE_APPEND); + + + + if ($call_back_data['sign'] == $sign) { + $time = date("Y-m-d H:i:s",time()); + $body = json_decode($call_back_data['body']); + + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . $body->address.": 验证签名成功" . "\n", FILE_APPEND); + + //$body->tradeType 1充币回调 2提币回调 + if ($body->tradeType == 1) { + + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "充币回调成功" . "\n", FILE_APPEND); + + //$body->status 0待审核 1审核成功 2审核驳回 3交易成功 4交易失败 + if ($body->status == 3) { + + //验证是否重复调用 + $RechargesInfo =ChargeReq::where(["txid"=>$body->txId])->exists(); + if ($RechargesInfo){ + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt","\n" .date('Y-m-d H:i:s') . "U盾已结充值过". "\n", FILE_APPEND); + die; + } + + + $moeny = $body->amount/pow(10,$body->decimals); + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "交易成功". "\n", FILE_APPEND); + + //业务处理 + + $map = ['memberid'=>$memberid,'address' => $body->address]; + + $address = WalletAddress::where($map)->value('address'); + if(!$address){ + + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s')."流水号".$body->tradeId ."充币地址" .$body->address ."未找到该地址". "\n", FILE_APPEND); + }else{ + + + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "获取用户地址成功". "\n", FILE_APPEND); + } + + + + + $address = $body->address; + $k = 'address:' . strtolower($address); + $user_id = Redis::get($k); + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "获取用户成功:".$user_id. "\n", FILE_APPEND); + // $user_id = 1086179; + $user = Users::find($user_id); + + // file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "获取用户:".json_encode($user). "\n", FILE_APPEND); + $nick_name = ''; + if (empty($user['email'])){ + $nick_name = $user['phone']; + }else{ + $nick_name = $user['email']; + } + + $account = $user_id; + + // file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "获取用户昵称:".$nick_name. "\n", FILE_APPEND); + $type =0; + $sub_type = 'USDC'; + $currency_id =3; + if($body->mainCoinType == 60) {$sub_type = 'ETH';$currency_id =2;} + if($body->mainCoinType == 195 && $body->coinType == 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t') $sub_type = 'USDT-TRC20'; + if($body->mainCoinType == 60 && $body->coinType == '0xdac17f958d2ee523a2206206994597c13d831ec7') $sub_type = 'USDT-ERC20'; + if($body->mainCoinType == 195 && $body->coinType == 'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8') $sub_type = 'USDC-TRC20'; + if($body->mainCoinType == 60 && $body->coinType == '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48') $sub_type = 'USDC-ERC20'; + if($body->mainCoinType == 195 && $body->coinType == '195') {$sub_type = 'TRX';$currency_id =19;} + if($body->mainCoinType == 0) {$sub_type = 'BTC';$currency_id =1;} + + // file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "获取币种:".$sub_type. "\n", FILE_APPEND); + $userLevel = $user['user_level'] > 0 ? UserLevelModel::find($user['user_level']) : null; + + $give = $userLevel ? round(($moeny * $userLevel['give'] / 100),8) : 0; + $give_rate = $userLevel ? $userLevel['give'] : 0; + // file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "奖励:".$give. "\n", FILE_APPEND); + //日志 + $data = [ + 'type'=>$type, + 'uid' => $user_id, + 'currency_id' => $currency_id, + 'amount' => $moeny, + 'price' => $moeny, + 'give' => $give, + 'account_name' => $nick_name, + 'give_rate' => $give_rate, + 'user_account' => $account, + 'currency_name' => 'Udun Pay', + 'sub_type' => $sub_type, + 'address' => $address, + 'status' => 2, + 'txid' => $body->txId, + 'created_at' => date('Y-m-d H:i:s') + ]; + + $md = Db::table('charge_req')->insert($data); + if($md){ + //加分 + try { + DB::beginTransaction(); + $user_wallet = UsersWallet::where('user_id', $user_id) + ->lockForUpdate() + ->where('currency', $currency_id) + ->first(); + + + // $user_wallet->change_balance = $user_wallet->change_balance+$moeny+$give; + + // $save_result = $user_wallet->save(); + + // Db::table('users_wallet')->where('currency',3)->where('user_id',$user_id)->update($data); + $change_result = change_wallet_balance($user_wallet, 2, $moeny+$give, AccountLog::ETH_EXCHANGE, '链上充币增加'); + + + DB::commit(); + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt","\n" ."用户:".$user_id." address:".$address.",U盾充值:".$moeny. "\n", FILE_APPEND); + } catch (\Exception $e) { + DB::rollBack(); + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt","\n" ."用户U盾充值失败:currency_id:".$currency_id.",amount:".$moeny. "\n", FILE_APPEND); + } + }else{ + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt","\n" ."用户U盾充值失败:currency_id:".$currency_id.",amount:".$moeny. "\n", FILE_APPEND); + } + + + + // file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . json_encode($transaction) . "用户数据". "\n", FILE_APPEND); + + + + + } + + return "success"; + + }elseif($body->tradeType == 2) { + + // U盾提现业务处理 + return "success"; + } + + + + } + else + { + file_put_contents("/www/wwwroot/crypto/public/recharge_data.txt", "\n" . date('Y-m-d H:i:s') . "签名验证失败". "\n", FILE_APPEND); + } + + } + +} +?> \ No newline at end of file diff --git a/app/Http/Controllers/Api/InsuranceController.php b/app/Http/Controllers/Api/InsuranceController.php new file mode 100644 index 0000000..f6fecb9 --- /dev/null +++ b/app/Http/Controllers/Api/InsuranceController.php @@ -0,0 +1,400 @@ +error('非法参数'); + } + if($currency->insurancable == 0){ + return $this->error('该币种不支持购买保险'); + } + $insurance_types = InsuranceType::where('status', 1) + ->where('currency_id', $currency_id)->get()->toArray(); + return $this->success($insurance_types); + } + + + /** + * 获取用户币种的保险 + */ + public function getUserCurrencyInsurance() + { + $user_id = Users::getUserId(); + $currency_id = request('currency_id',0); + $user_insurance = UsersInsurance::where('user_id', $user_id) + ->whereHas('insurance_type', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }) + ->where('status', 1) + ->first(); + + + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $currency_id) + ->first(); + + return $this->success([ + 'user_insurance' => $user_insurance, + 'user_wallet' => $user_wallet, + ]); + } + /** + * 购买保险 + */ + public function buyInsurance() + { + $user_id = Users::getUserId(); + $amount = request('amount', 0); + $insurance_type_id = request('type_id', 0); + + if (!is_numeric($amount) or $amount <= 0) { + return $this->error('错误的金额!'); + } + $insurance_type = InsuranceType::find($insurance_type_id); + if(!$insurance_type){ + return $this->error('不存在的险种!'); + } + $currency_id = $insurance_type->currency_id; + $currency = Currency::find($currency_id); + if(!$currency){ + return $this->error('不存在的币种!'); + } + + if($currency->insurancable == 0){ + return $this->error('该币种不支持购买保险'); + } + + if($amount > $insurance_type->max_amount || $amount < $insurance_type->min_amount){ + return $this->error("购买失败,购买金额必须大于{$insurance_type->min_amount}并且小于{$insurance_type->max_amount}"); + } + + $users_insurance = UsersInsurance::where('user_id',$user_id) + ->where('status',1) + ->where('insurance_type_id',$insurance_type_id) + ->first(); + + //该用户存在该币种的险种 + if($users_insurance){ + return $this->error('已经购买了该币种的险种!'); + } + + //保险资产 + $insurance_amount = bcmul($amount, bc_div($insurance_type->insurance_assets, 100),2); + try { + DB::beginTransaction(); + + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $currency_id) + ->lockForUpdate() + ->first(); + + if (bc_comp($user_wallet->micro_balance, ($amount+$insurance_amount)) < 0) { + throw new \Exception('可用余额不足,无法购买!'); + } + + //扣币 + change_wallet_balance($user_wallet, 4, -($amount+$insurance_amount), AccountLog::USER_BUY_INSURANCE, "用户购买保险{$insurance_type->name}", false); + + //生成保险单 + + UsersInsurance::create([ + 'user_id' => $user_id, + 'insurance_type_id' => $insurance_type_id, + 'amount' => $amount, + 'insurance_amount' => $insurance_amount, + 'status' => 1, + 'claim_status' => 0, + ]); + + //用户的受保金额 + $user_wallet->insurance_balance = $amount; + $user_wallet->lock_insurance_balance = $insurance_amount; + $user_wallet->save(); + + DB::commit(); + return $this->success('购买成功!'); + } catch (\Exception $e) { + DB::rollBack(); + return $this->error('购买失败!原因:'.$e->getMessage()); + } + } + + /** + * 索赔 + */ + public function claimApply() + { + $user_id = Users::getUserId(); + $user_insurance_id = request('user_insurance_id',0); + $user_insurance = UsersInsurance::find($user_insurance_id); + + if(!$user_insurance){ + return $this->error('未找到该保险'); + } + + //该保险是否正在处理中? + $user_insurance_claim = InsuranceClaimApply::where('user_id', $user_id) + ->where('apply_status', 0) + ->where('user_insurance_id', $user_insurance_id) + ->first(); + if($user_insurance_claim){ + return $this->error('该保险正在处理中'); + } + + $can_claim = $this->canClaimApply($user_id, $user_insurance); + //dd($can_claim); + if($can_claim !== true){ + return $this->error("申请索赔失败:{$can_claim}"); + } + + $insurance_type = $user_insurance->insurance_type; + try { + DB::beginTransaction(); + + $make_apply = InsuranceClaimApply::create([ + 'user_id' => $user_id, + 'user_insurance_id' => $user_insurance->id, + 'apply_status' => 0, + 'compensate' => bc_mul($user_insurance->amount,bc_div($insurance_type->claim_rate,100)), + 'insurance_type' => $user_insurance->insurance_type_id + ]); + $user_insurance->claim_status = 1; + $user_insurance->save(); + if($insurance_type->auto_claim == 0){ + //不自动处理索赔 + }else{ + //自动处理索赔 + $this->handleClaim($make_apply); + } + DB::commit(); + return $this->success('申请索赔成功!'); + } catch (\Exception $e) { + DB::rollBack(); + return $this->error('申请索赔失败:'.$e->getMessage()); + } + } + + /** + * 是否可以申请索赔 + */ + protected function canClaimApply($user_id, $user_insurance) + { + //$user = Users::getById($user_id); + $insurance_type = $user_insurance->insurance_type; + + //该用户该保险的对应的钱包。 + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $insurance_type->currency_id) + ->first(); + + $today_claim_times = $this->getTodayClaimSuccessCount($user_id, $insurance_type->type); + + //超出今日索赔次数 + if($today_claim_times >= $insurance_type->claims_times_daily){ + return '超出今日索赔次数!'; + } + + //此时间段内是否有未平仓的保险 + $count = MicroOrder::where('user_id', $user_id) + ->where(function($query){ + $query->where('status', 1)->orWhere('status',2); + }) + ->where('currency_id', $insurance_type->currency_id) + ->count(); + if($count > 0){ + return '存在未平仓订单'; + } + switch ($insurance_type->type){ + case 1: + //受保资产为0不允许索赔申请 + if($user_wallet->insurance_balance == 0){ + return '受保资产为零'; + } + //受保金额低于此时可以申请保险索赔。 + $defective_amount = bc_mul($user_insurance->amount ,bc_div($insurance_type->defective_claims_condition, 100)); + + //正向险种,受保资产大于【索赔申请条件1额度】,不允许索赔申请 + if($user_wallet->insurance_balance > $defective_amount){ + return '受保资产不符合可申请索赔条件1'; + } + break; + case 2: + //反向险种,受保资产大于【索赔申请条件2额度】,不允许索赔申请 + if($user_wallet->insurance_balance > $insurance_type->defective_claims_condition2){ + return '受保资产不符合可申请索赔条件2'; + } + break; + default: + return '未知的险种类型'; + } + return true;//可以申请索赔 + } + + /** + * 获取今天用户索赔成功次数 + */ + protected function getTodayClaimSuccessCount($user_id, $insurance_type) + { + $now_date = Carbon::now()->toDateString(); + $today_claim_success_count = InsuranceClaimApply::where('user_id', $user_id) + ->where('insurance_type', $insurance_type) + ->where('apply_status', 1)//已成功赔付的 + ->whereDate('updated_at', $now_date)//今天的 + ->count(); + return $today_claim_success_count; + } + + /** + * 处理索赔 + */ + protected function handleClaim($claim_apply){ + + + $user_insurance = UsersInsurance::where('id', $claim_apply->user_insurance_id)->first(); + //保险类型 + $insurance_type = $user_insurance->insurance_type; + + try { + DB::beginTransaction(); + $user_wallet = UsersWallet::where('user_id', $claim_apply->user_id) + ->where('currency', $insurance_type->currency_id) + ->lockForUpdate() + ->first(); + + + switch ($insurance_type->claim_direction){ + case 1: + //索赔清除用户受保金额 + change_wallet_balance($user_wallet, 5, -$user_wallet->insurance_balance, AccountLog::USER_CLAIM_COMPENSATION, '保险赔偿用户[清除受保金额]', false); + + //将保险受保金额给予用户保险账户 + change_wallet_balance($user_wallet, 5, $claim_apply->compensate, AccountLog::USER_CLAIM_COMPENSATION, '保险赔偿用户[赔偿受保金额]', false); + + break; + case 2: + //索赔清除用户受保金额 + change_wallet_balance($user_wallet, 5, -$user_wallet->insurance_balance, AccountLog::USER_CLAIM_COMPENSATION, '保险赔偿用户[清除受保金额]', false); + + //将保险受保金额给予用户的期权账户 + change_wallet_balance($user_wallet, 4, $claim_apply->compensate, AccountLog::USER_CLAIM_COMPENSATION, '保险赔偿用户[赔偿受保金额]', false); + + change_wallet_balance($user_wallet, 5, -$user_wallet->lock_insurance_balance, + AccountLog::INSURANCE_RESCISSION2, '保险解约,扣除保险金额', true); + + //将用户的保险状态改变 + $user_insurance->status = 0; + $user_insurance->save(); + break; + default: + throw new \Exception('未知受保金额去向状态'); + } + //更改索赔状态 + $user_insurance->claim_status = 0; + $user_insurance->save(); + //更改申请状态 + $claim_apply->apply_status = 1; + $claim_apply->operator = 'auto'; + $claim_apply->save(); + DB::commit(); + return $this->success('处理成功!'); + } catch (\Exception $e) { + DB::rollBack(); + return $this->error('处理失败:'.$e->getMessage()); + } + + } + + + /** + * 手动解约 + */ + public function manualRescission() + { + $user_id = Users::getUserId(); + $user_insurance_id = request('user_insurance_id',0); + $user_insurance = UsersInsurance::find($user_insurance_id); + + if(!$user_insurance){ + return $this->error('未找到该保险'); + } + + if($user_insurance->status == 0){ + return $this->error('该保险已失效'); + } + + if($user_insurance->claim_status == 1){ + return $this->error('该保险正在索赔处理中'); + } + //保险类型 + $insurance_type = $user_insurance->insurance_type; + + //用户钱包 + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $insurance_type->currency_id) + ->first(); + + //此时间段内是否有未平仓的保险 + $count = MicroOrder::where('user_id', $user_id) + ->where(function($query){ + $query->where('status', 1)->orWhere('status',2); + }) + ->where('currency_id', $insurance_type->currency_id) + ->count(); + if($count > 0){ + return '解约失败,存在未平仓订单'; + } + //爆仓盈利条件 + //$rescission_profit = bc_mul($user_insurance->insurance_amount, 1 + bc_div($insurance_type->profit_termination_condition, 100), 2); + $auto = 1; + $return_amount = $user_wallet->insurance_balance; + + try { + DB::beginTransaction(); + + //将用户的保险状态改变 + $user_insurance->status = 0; + $user_insurance->rescinded_at = \Carbon\Carbon::now()->toDateTimeString(); + $user_insurance->rescinded_type = $auto;//解约类型 + $user_insurance->save(); + + //将平仓额度给予用户 + change_wallet_balance($user_wallet, 4, $return_amount, AccountLog::INSURANCE_RESCISSION_ADD, + '保险解约,赔付金额'); + + //扣除用户钱包保险金额 + change_wallet_balance($user_wallet, 5, -$user_wallet->insurance_balance, AccountLog::INSURANCE_RESCISSION1, + '保险解约,扣除受保金额', false); + + change_wallet_balance($user_wallet, 5, -$user_wallet->lock_insurance_balance, + AccountLog::INSURANCE_RESCISSION2, '保险解约,扣除保险金额', true); + DB::commit(); + return $this->success('解约成功!'); + } catch (\Exception $e) { + DB::rollBack(); + return $this->error($this->returnStr('解约失败:').$e->getMessage()); + } + } + +} diff --git a/app/Http/Controllers/Api/LegalDealController.php b/app/Http/Controllers/Api/LegalDealController.php new file mode 100644 index 0000000..2dad583 --- /dev/null +++ b/app/Http/Controllers/Api/LegalDealController.php @@ -0,0 +1,1052 @@ + $v){ + $data[$k] = ['name' => $v , 'rate' => 1]; + } + return $this->success($data); + } + + + + public function handle_one(Request $request) + { + $id = $request->get('id', null); + $userLegalDealCancel_time=Setting::getValueByKey("userLegalDealCancel_time")*60; + $result=LegalDeal::find($id); + + $time=time(); + $create_time=strtotime($result->create_time); + if(($create_time+$userLegalDealCancel_time)<=$time) + { + $id =$result->id; + $ppp=LegalDeal::cancelLegalDealById($id); + $aaaa=Users::find($result->user_id); + $aaaa->today_LegalDealCancel_num=$aaaa->today_LegalDealCancel_num+1; + $aaaa->LegalDealCancel_num__update_time=time(); + $aaaa->save(); + return $this->success('订单取消成功'); + } + + } + + public function postSend(Request $request) + { + $type = $request->get('type', null); + $way = $request->get('way', null); + $price = $request->get('price', null); + $total_number = $request->get('total_number', null); + $min_number = $request->get('min_number', null); + $currency_id = $request->get('currency_id', null); + $max_number=$request->get('max_number', $total_number); + + if (empty($type)) return $this->error('请选择需求类型'); + if (empty($way)) return $this->error('请选择交易方式'); + if (empty($price)) return $this->error('请填写单价'); + if (empty($total_number)) return $this->error('请填写数量'); + if (empty($min_number)) return $this->error('请填写最小交易数量'); + if (empty($currency_id)) return $this->error('请选择币种'); + if ($min_number > $total_number) return $this->error('最小交易数量不能大于总数量'); + + if (empty($max_number)) return $this->error('请填写最大交易量'); + if ($max_number>$total_number || $max_number<=0 || !is_numeric($max_number)){ + return $this->error('请填写正确的最大交易量'); + } + $currency = Currency::where('id',$currency_id)->select(['id'])->first(); + if(empty($currency)){ + return $this->error('币种信息有误'); + } + + DB::BeginTransaction(); + try { + $user_id = Users::getUserId(); + $seller = Seller::lockForUpdate()->where('user_id', $user_id)->where('currency_id', $currency_id)->first(); + if (empty($seller)) { + DB::rollback(); + return $this->error('对不起,您不是该法币的商家'); + } + if ($type == 'sell') { + + if ($seller->legal_balance < $total_number) { + DB::rollback(); + return $this->error('对不起,您的商家账户不足'); + } + + $user_wallet=UsersWallet::lockForUpdate()->where("user_id",$user_id)->where("currency", $currency->id)->first(); + $res1 = change_wallet_balance($user_wallet, 1, $total_number * -1, AccountLog::LEGAL_DEAL_SEND_SELL, '商家发布出售'); + if ($res1 !== true) { + throw new \Exception($res1); + } + + $res2 = change_wallet_balance($user_wallet, 1, $total_number, AccountLog::LEGAL_DEAL_SEND_SELL, '商家发布出售,锁定增加',1); + + if ($res2 !== true) { + throw new \Exception($res2); + } + + $seller->lock_seller_balance = bc_add($seller->lock_seller_balance,$total_number,5); + $seller->save(); + + } + + $legal_deal_send = new LegalDealSend(); + $legal_deal_send->seller_id = $seller->id; + $legal_deal_send->currency_id = $currency_id; + $legal_deal_send->type = $type; + $legal_deal_send->way = $way; + $legal_deal_send->price = $price; + $legal_deal_send->total_number = $total_number; + $legal_deal_send->surplus_number = $total_number; + $legal_deal_send->min_number = $min_number; + $legal_deal_send->max_number = $max_number; + $legal_deal_send->create_time = time(); + $legal_deal_send->money_type = $request->get('money_type')??1; + $legal_deal_send->save(); + DB::commit(); + return $this->success('发布成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + + + } + + + public function sellerInfo(Request $request) + { + $id = $request->get('id', null); + $type = $request->get('type',null); + $was_done = $request->get('was_done','false'); + $limit = $request->get('limit', 10); + + if (empty($id)) return $this->error('参数错误'); + $seller = Seller::find($id); + if (empty($seller)) return $this->error('无此商家'); + $beforeThirtyDays = Carbon::today()->subDay(30)->timestamp; //30天前 + $results = Seller::withCount(['legalDeal as total', 'legalDeal as done' => function ($query) { + $query->where('is_sure', 1); + }, 'legalDeal as thirtyDays' => function ($query) use ($beforeThirtyDays) { + $query->where('is_sure', 1)->where('update_time', '>=', $beforeThirtyDays); + }])->find($id); + $lists = LegalDealSend::where('seller_id', $id); + + if($was_done == 'true'){ + $lists = $lists->where('is_done','=','1'); + }elseif($was_done == 'false'){ + $lists = $lists->where('is_done','=','0'); + } + + if($type == 'buy'){ + $type = 'buy'; + $lists = $lists->where('type',$type); + }elseif($type == 'sell'){ + $type = 'sell'; + $lists = $lists->where('type',$type); + } + + $lists = $lists->orderBy('id', 'desc')->paginate($limit); + $results->lists = array('data' => $lists->items(), 'page' => $lists->currentPage(), 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($results); + } + + + public function tradeList(Request $request) + { + $type = $request->get('type',null); + $was_done = $request->get('was_done',null); + $limit = $request->get('limit', 10); + + $id = $request->get('id',0); + + $seller = Seller::where('id', $id)->first(); + + if (empty($seller)) { + return $this->error('您不是商家'); + } + $lists = LegalDealSend::where('seller_id', $seller->id); + //是否完成 + if ($was_done == 'true') { + //$lists = $lists->where('is_done','=','1'); + $lists = $lists->whereIn('is_done', ['1', '2']); + } elseif ($was_done == 'false') { + $lists = $lists->where('is_done','=','0'); + } + + if($type == 'buy') { + $type = 'buy'; + $lists = $lists->where('type', $type); + } elseif ($type == 'sell') { + $type = 'sell'; + $lists = $lists->where('type', $type); + } + + $lists = $lists->orderBy('id', 'desc')->paginate($limit); + $result = array('data' => $lists->items(), 'page' => $lists->currentPage(), 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + + + + public function legalDealPlatform(Request $request) + { + $limit = $request->get('limit', 10); + $currency_id = $request->get('currency_id', ''); + $type = $request->get('type', 'sell'); + if (empty($currency_id)) return $this->error('参数错误'); + if (empty($type)) return $this->error('参数错误2'); + $currency = Currency::find($currency_id); + if (empty($currency)) return $this->error('无此币种'); + if (empty($currency->is_legal)) return $this->error('该币不是法币'); + if($type=="sell") + { + $results = LegalDealSend::where('currency_id', $currency_id)->where('is_done', 0)->where('is_shelves', 1)->where('type', $type)->orderBy('price', 'asc')->orderBy('id', 'desc')->paginate($limit); + } + else + { + $results = LegalDealSend::where('currency_id', $currency_id)->where('is_done', 0)->where('is_shelves', 1)->where('type', $type)->orderBy('price', 'desc')->orderBy('id', 'desc')->paginate($limit); + } + + return $this->pageData($results); + } + public function legalDealSendInfo(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) { + return $this->error('参数错误'); + } + $legal_deal_send = LegalDealSend::find($id); + + $userWallet=UsersWallet::where('currency',$legal_deal_send->currency_id) + ->where('user_id',Users::getUserId())->first(); + + + $legal_deal_send->user_legal_balance=$userWallet->legal_balance; + + if (empty($legal_deal_send)) return $this->error('无此记录'); + return $this->success($legal_deal_send); + } + + public function doDeal(Request $request) + { + $deal_send_id = $request->get('id', null); + $value = $request->get('value', 0); + $means = $request->get('means', ''); + if (empty($deal_send_id)) { + return $this->error('参数错误'); + } + if (!in_array($means, ['number', 'money'])) { + return $this->error('购买参数错误'); + } + + if (empty($value)) { + return $this->error('请填写购买额'); + } + if (!is_numeric($value)) { + return $this->error('购买额请填写数字'); + } + $user_id = Users::getUserId(); + //实名认证检测 + $user_real = UserReal::where('user_id', $user_id) + ->where('review_status', 2) + ->first(); + if (!$user_real) { + return response()->json(['type'=>'998','message'=>$this->returnStr('您还没有通过实名认证')]); + } + //收款信息检测 + $user_cash_info = UserCashInfo::where('user_id', $user_id)->first(); + if (!$user_cash_info) { + return response()->json(['type'=>'997','message'=>$this->returnStr('您还没有设置收款信息')]); + } + + + //限制未完成单数最多为3单 + $is_morethan=LegalDeal::where("user_id","=",$user_id)->whereIn('is_sure', [0,3])->count(); + if($is_morethan>=3) + { + return $this->error('未完成单子超过3单,请完成后再操作!'); + } + + + try { + DB::beginTransaction(); + $legal_deal_send = LegalDealSend::lockForUpdate()->find($deal_send_id); + + if (empty($legal_deal_send)) { + DB::rollback(); + return $this->error('无此记录'); + } + if ($legal_deal_send->is_shelves != 1 || $legal_deal_send->is_done != 0) { + throw new \Exception('商家挂单状态异常,暂时不能交易'); + } + if($legal_deal_send->surplus_number <= 0){ + throw new \Exception('商家挂单剩余可交易数量不足'); + } + + if (!empty($legal_deal_send->is_done)) { + DB::rollback(); + return $this->error('此条交易已完成'); + } + if ($means == 'money') { + $number = bc_div($value, $legal_deal_send->price, 5); + } else { + $number = $value; + } + if ($number <= 0) { + DB::rollback(); + return $this->error('非法提交,数量必须大于0'); + } + + $money = bc_mul($number, $legal_deal_send->price, 6); + + if (bc_comp($money, $legal_deal_send->limitation['min']) < 0) { + DB::rollback(); + return $this->error('您低于最低限额'); + } + if ($money > $legal_deal_send->limitation['max']) { + DB::rollback(); + return $this->error('您高于最高限额'); + } + if ($number > $legal_deal_send->max_number) { + DB::rollback(); + return $this->error('您高于最大限制数量'); + } + $seller = Seller::find($legal_deal_send->seller_id); + if (empty($seller)) { + DB::rollback(); + return $this->error('未找到该商家'); + } + + if ($user_id == $seller->user_id) { + DB::rollback(); + return $this->error('不能操作自己的'); + } + $users_wallet = UsersWallet::lockForUpdate()->where('user_id', $user_id)->where('currency', $legal_deal_send->currency_id)->first(); + if (empty($users_wallet)) { + DB::rollback(); + return $this->error('您无此钱包账号'); + } + if (!empty($users_wallet->status)) { + DB::rollback(); + return $this->error('您的钱包已被锁定,请联系管理员'); + } + + if ($legal_deal_send->type == 'buy') { //求购 + + if ($users_wallet->legal_balance < $number) { + DB::rollback(); + return $this->error('您的法币余额不足'); + } + if ($users_wallet->lock_legal_balance < 0) { + DB::rollback(); + return $this->error('您的法币锁定资金异常,请查看您是否有正在进行的挂单'); + } + + //检查购买数量是否大于剩余余额 t add + if($number>$legal_deal_send->surplus_number) + { + DB::rollback(); + return $this->error('您出售数量大于商家剩余数量!'); + } + else + { + $legal_deal_send->surplus_number = bc_sub($legal_deal_send->surplus_number,$number,5); + } + + + if ($legal_deal_send->surplus_number <= 0) { + + $legal_deal_send->is_shelves = 2; // 下架交易,防止交易被其他用户再匹配 + } + + + $result = change_wallet_balance($users_wallet, 1, -$number, AccountLog::LEGAL_DEAL_USER_SELL, '出售给商家法币:扣除余额'); + if ($result !== true) { + throw new \Exception($result); + } + $result1 = change_wallet_balance($users_wallet, 1, $number, AccountLog::LEGAL_DEAL_USER_SELL, '出售给商家法币:增加锁定', true); + if ($result1 !== true) { + throw new \Exception($result1); + } + + + } elseif ($legal_deal_send->type == 'sell') { + //出售 + + if($number>$legal_deal_send->surplus_number) + { + DB::rollback(); + return $this->error('您购买数量大于商家剩余数量!'); + } + else + { + $legal_deal_send->surplus_number = bc_sub($legal_deal_send->surplus_number,$number,5); + } + + if ($legal_deal_send->surplus_number <= 0) { + //$legal_deal_send->is_done = 1; + $legal_deal_send->is_shelves = 2; // 下架交易,防止交易被其他用户再匹配 + } + + } + + $legal_deal_send->save(); + + $legal_deal = new LegalDeal(); + $legal_deal->legal_deal_send_id = $deal_send_id; + $legal_deal->user_id = $user_id; + $legal_deal->seller_id = $seller->id; + $legal_deal->number = $number; //交易数量 + $legal_deal->create_time = time(); + $legal_deal->save(); +// var_dump($legal_deal);die; + DB::commit(); + return $this->success([ + 'msg' => $this->returnStr('操作成功,请联系商家确认订单'), + 'data' => $legal_deal, + ]); + + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage() . $this->returnStr(',错误位于第') . $exception->getLine() . $this->returnStr('行')); + } + } + + /** + * 法币交易商家端列表 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function sellerLegalDealList(Request $request) + { + $limit = $request->get('limit', 10); + $type = $request->get('type', 'sell'); + $currency_id = $request->get('currency_id', ''); + + if (empty($currency_id)) { + return $this->error('参数错误'); + } + if (empty($type)) { + return $this->error('参数错误2'); + } + $currency = Currency::find($currency_id); + if (empty($currency)) { + return $this->error('无此币种'); + } + if (empty($currency->is_legal)) { + return $this->error('该币不是法币'); + } + $user_id = Users::getUserId(); + $seller = Seller::where('user_id', $user_id)->where('currency_id', $currency_id)->first(); + if (empty($seller)) { + return $this->error('您不是此币商家'); + } + $results = LegalDeal::where('seller_id', $seller->id) + ->whereHas('legalDealSend', function ($query) use ($type) { + $query->where('type', $type); + })->orderBy('id', 'desc')->paginate($limit); + return $this->pageData($results); + + } + + /** + * 法币交易用户端列表 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function userLegalDealList(Request $request) + { + $limit = $request->get('limit', 10); + $type = $request->get('type', null); + $currency_id = $request->get('currency_id', ''); + $is_sure = $request->get('is_sure', null);//0未确认 1已确认 2已取消 3已付款 + + if (!empty($currency_id)) { + $currency = Currency::find($currency_id); + if (empty($currency)) return $this->error('无此币种'); + if (empty($currency->is_legal)) return $this->error('该币不是法币'); + } + + $user_id = Users::getUserId(); + + $results = LegalDeal::where('user_id', $user_id); + if (!empty($type)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($type) { + $query->where('type', $type); + }); + } + + if (!empty($currency_id)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }); + } + + if (!is_null($is_sure)) { + $results = $results->where('is_sure', $is_sure); + } + $results = $results->orderBy('id', 'desc')->paginate($limit); +// var_dump($results);die; + return $this->pageData($results); + } + + + + /** + * 法币交易用户端列表 作为商家 + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function sellerUserLegalDealList(Request $request) + { +// var_dump(66666);die; + $limit = $request->get('limit', 10); + $type = $request->get('type', null); + $currency_id = $request->get('currency_id', ''); + $is_sure = $request->get('is_sure', null);//0未确认 1已确认 2已取消 3已付款 + + if (!empty($currency_id)) { + $currency = Currency::find($currency_id); + if (empty($currency)) return $this->error('无此币种'); + if (empty($currency->is_legal)) return $this->error('该币不是法币'); + } + + $user_id = Users::getUserId(); + + $my_seller_id=Seller::where("user_id",$user_id)->first()->id; + + $results = LegalDeal::where('seller_id', $my_seller_id); + if (!empty($type)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($type) { + $query->where('type', $type); + }); + } + + if (!empty($currency_id)) { + $results = $results->whereHas('legalDealSend', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }); + } + + if (!is_null($is_sure)) { + $results = $results->where('is_sure', $is_sure); + } + + $results = $results->orderBy('id', 'desc')->paginate($limit); +// var_dump($results);die; +// var_dump($results);die; + return $this->pageData($results); + } + + + public function legalDealInfo(Request $request) + { + $userLegalDealCancel_time=Setting::getValueByKey("userLegalDealCancel_time")*60; + $id = $request->get('id', null); + if (empty($id)) { + return $this->error('参数错误'); + } + $legal_deal = LegalDeal::find($id); + if($legal_deal->is_sure==0)//0未确认 1已确认 2已取消 3已付款 + { +// var_dump(strtotime($legal_deal->create_time));die; + $legal_deal->cancel_time=(strtotime($legal_deal->create_time)+$userLegalDealCancel_time)-time(); + } + + $legal_deal->to_pay_info=Seller::where("id",$legal_deal->seller_id)->first(); + + if (empty($legal_deal)) { + return $this->error('无此记录'); + } + return $this->success($legal_deal); + } + + public function userLegalDealPay(Request $request) + { + $id = $request->get('id', null); + $pay_orders_img = $request->get('pay_orders_img', null); + if (empty($id)) return $this->error('参数错误'); + + $legal_deal = LegalDeal::find($id); + if (empty($legal_deal)) { + return $this->error('无此记录'); + } + DB::beginTransaction(); + try { + if ($legal_deal->is_sure > 0) { + DB::rollback(); + return $this->error('该订单已操作过,请勿重复操作'); + } + $user_id = Users::getUserId(); + if ($legal_deal->type == 'sell') { + if (empty($pay_orders_img)){ + DB::rollback(); + return $this->error('请上传支付凭证'); + } + if ($user_id != $legal_deal->user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + } elseif ($legal_deal->type == 'buy') { + $seller = Seller::find($legal_deal->seller_id); + if ($user_id != $seller->user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + } + $legal_deal->is_sure = 3; + $legal_deal->pay_orders_img = $pay_orders_img; + $legal_deal->save(); + DB::commit(); + return $this->success('操作成功,请联系卖家确认'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + public function userLegalDealCancel(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) { + return $this->error('参数错误'); + } + + + try { + DB::beginTransaction(); + $legal_deal = LegalDeal::lockForUpdate()->find($id); + if (empty($legal_deal)) { + DB::rollback(); + return $this->error('无此记录'); + } + + if ($legal_deal->is_sure > 0) { + DB::rollback(); + return $this->error('该订单已操作,请勿取消'); + } + $user_id = Users::getUserId(); + if ($legal_deal->type == 'sell') { //用户端-购买 + if ($user_id != $legal_deal->user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + } elseif ($legal_deal->type == 'buy') {//用户端出售 + $seller = Seller::find($legal_deal->seller_id); + if ($user_id == $legal_deal->user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + } + + LegalDeal::cancelLegalDealById($id); + DB::commit(); + return $this->success('操作成功,订单已取消'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + public function mySellerList(Request $request) + { + $limit = $request->get('limit', 10); + $user_id = Users::getUserId(); + $user = Users::find($user_id); + if (empty($user->is_seller)) { + return $this->error('对不起您不是商家'); + } + $results = Seller::where('user_id', $user_id)->orderBy('id', 'desc')->paginate($limit); + return $this->pageData($results); + } + + public function legalDealSellerList(Request $request) + { + $limit = $request->get('limit', 10); + $id = $request->get('id', null); + $is_sure = $request->get('is_sure', null); + if (empty($id)) return $this->error('参数错误'); + $legal_send = LegalDealSend::find($id); + if (empty($legal_send)) { + return $this->error('参数错误2'); + } + $seller = Seller::find($legal_send->seller_id); + if (empty($seller->is_myseller)) { + return $this->error('对不起,您不是该商家'); + } + if(!is_null($is_sure)) + { + $results = LegalDeal::where('legal_deal_send_id', $id) + ->where('is_sure', $is_sure) + ->orderBy('id', 'desc') + ->paginate($limit); + }else + { + $results = LegalDeal::where('legal_deal_send_id', $id) + ->orderBy('id', 'desc') + ->paginate($limit); + } + + return $this->pageData($results); + } + + public function doSure(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + DB::beginTransaction(); + try { + $legal_deal = LegalDeal::lockForUpdate()->find($id); + if (empty($legal_deal)) { + DB::rollback(); + return $this->error('无此记录'); + } + if ($legal_deal->is_sure != 3) { + DB::rollback(); + return $this->error('该订单还未付款或已经操作过'); + } + $seller = Seller::lockForUpdate()->find($legal_deal->seller_id); + if (empty($seller->is_myseller)) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + if (bc_comp($seller->lock_seller_balance, $legal_deal->number) < 0) { + throw new \Exception('对不起,您的商家锁定余额不足,当前余额:' . $seller->lock_seller_balance); + } + + $legal_send = LegalDealSend::find($legal_deal->legal_deal_send_id); + if (empty($legal_send)) { + DB::rollback(); + return $this->error('订单异常'); + } + if ($legal_send->type == 'buy') { + DB::rollback(); + return $this->error('您不能确认该订单'); + } + $user_wallet = UsersWallet::where('user_id', $legal_deal->user_id)->where('currency', $legal_send->currency_id)->lockForUpdate()->first(); + if (empty($user_wallet)) { + DB::rollback(); + return $this->error('该用户没有此币种钱包'); + } + // 增加用户法币余额 + $result = change_wallet_balance($user_wallet, 1, $legal_deal->number, AccountLog::LEGAL_USER_BUY, '法币交易:在商家' . $seller->name . ' 购买法币成功'); + if ($result !== true) { + throw new \Exception($result); + } + + //更新交易状态 + $legal_deal->is_sure = 1; + $legal_deal->update_time = time(); + $legal_deal->save(); + + //商家钱包 + + $seller_user_id=$seller->user_id; + $seller_user_wallet = UsersWallet::where('user_id', $seller_user_id) + ->where('currency', $legal_send->currency_id) + ->lockForUpdate() + ->first(); + + //减少商家法币锁定余额 + + $seller->lock_seller_balance = bc_sub($seller->lock_seller_balance,$legal_deal->number,5); + $seller->save(); + + $result = change_wallet_balance($seller_user_wallet, 1, -$legal_deal->number, AccountLog::LEGAL_USER_BUY, '法币交易:卖出成功',true); + if ($result !== true) { + throw new \Exception($result); + } + + DB::commit(); + //限定usdt才累加业绩 + if (strtolower($legal_send->currency_name) == 'usdt') { + event(new RechargeEvent($user_wallet->user_id, AccountLog::LEGAL_USER_BUY, $legal_deal->number)); + } + return $this->success('确认成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + public function userDoSure(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + DB::beginTransaction(); + try { + $legal_deal = LegalDeal::lockForUpdate()->find($id); + if (empty($legal_deal)) { + DB::rollback(); + return $this->error('无此记录'); + } + if ($legal_deal->is_sure != 3) { + DB::rollback(); + return $this->error('该订单还未付款或已经操作过'); + } + $user_id = Users::getUserId(); + $user = Users::find($user_id); + if ($legal_deal->user_id != $user_id) { + DB::rollback(); + return $this->error('对不起,您无权操作'); + } + $legal_send = LegalDealSend::find($legal_deal->legal_deal_send_id); + if (empty($legal_send)) { + DB::rollback(); + return $this->error('订单异常'); + } + if ($legal_send->type == 'sell') { + DB::rollback(); + return $this->error('您不能确认该订单'); + } + + $user_wallet = UsersWallet::where('user_id', $legal_deal->user_id) + ->where('currency', $legal_send->currency_id) + ->lockForUpdate() + ->first(); +// var_dump($user_wallet->toArray());die; + if (empty($user_wallet)) { + DB::rollback(); + return $this->error('该用户没有此币种钱包'); + } + $seller = Seller::lockForUpdate()->find($legal_deal->seller_id); + if (empty($seller)) { + DB::rollback(); + return $this->error('商家不存在'); + } + $result = change_wallet_balance($user_wallet, 1, -$legal_deal->number, AccountLog::LEGAL_SELLER_BUY, '法币交易:用户' . $user->account_number . '向商家出售法币成功', true); + if ($result !== true) { + throw new \Exception($result); + } + + //更新交易状态 + $legal_deal->is_sure = 1; + $legal_deal->update_time = time(); + $legal_deal->save(); + + //商家钱包 + $seller_user_id=$seller->user_id; + $seller_user_wallet = UsersWallet::where('user_id', $seller_user_id) + ->where('currency', $legal_send->currency_id) + ->lockForUpdate() + ->first(); + + //增加商家法币余额 + $result2 = change_wallet_balance($seller_user_wallet, 1, $legal_deal->number, AccountLog::LEGAL_SELLER_BUY, '法币交易:购买成功'); + if ($result2!== true) { + throw new \Exception($result2); + } + + DB::commit(); + return $this->success('确认成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + /** + * 标记交易下架 + * + */ + public function down(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + + try { + DB::beginTransaction(); + + $legal_send = LegalDealSend::lockForUpdate()->find($id); + + if (empty($legal_send)) { + throw new \Exception('无此记录'); + } + if ($legal_send->is_done != 0 || $legal_send->is_shelves != 1) { + throw new \Exception('此状态下无法下架'); + } + $user_id = Users::getUserId(); + $seller = Seller::where('user_id', $user_id) + ->where('currency_id', $legal_send->currency_id) + ->lockForUpdate() + ->first(); + if (empty($seller)) { + throw new \Exception('对不起,您不是该法币的商家'); + } + $legal_send->is_shelves = 2; + $legal_send->save(); + DB::commit(); + return $this->success('发布下架成功,将不会再与新用户匹配'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + + + + //撤回 + public function backSend(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + + try { + DB::beginTransaction(); + $legal_send = LegalDealSend::lockForUpdate()->find($id); + if (empty($legal_send)) { + DB::rollback(); + return $this->error('已撤回发布'); + } + if ($legal_send->is_sendback != 1) { + throw new \Exception('已撤销'); + } + if ($legal_send->is_shelves != 2) { + throw new \Exception('必须下架后才可以撤销'); + } + if ($legal_send->is_done != 0) { + throw new \Exception('当前发布状态无法撤销'); + } + if (bc_comp($legal_send->surplus_number) <= 0) { + throw new \Exception('当前发布剩余数量不足,无法撤销'); + } + if (LegalDealSend::isHasIncompleteness($id)) { + throw new \Exception('该发布信息下有交易正在进行中,请等待交易结束再撤回'); + } + + $user_id = Users::getUserId(); + $seller = Seller::where('user_id', $user_id)->where('currency_id', $legal_send->currency_id)->lockForUpdate()->first(); + if (empty($seller)) { + DB::rollback(); + return $this->error('对不起,您不是该法币的商家'); + } + if ($legal_send->type == 'sell') { //如果商家发布出售信息 + if ($seller->lock_seller_balance < $legal_send->surplus_number){ + DB::rollback(); + return $this->error('对不起,您的商家账户锁定资金不足'); + } + + $user_wallet=UsersWallet::where("user_id",$user_id)->where("currency", $legal_send->currency_id)->lockForUpdate()->first(); + $res1=change_wallet_balance($user_wallet,1,-$legal_send->surplus_number, AccountLog::LEGAL_DEAL_BACK_SEND_SELL, '商家撤回',true); + if ($res1 !== true) { + throw new \Exception('撤回失败:减少锁定资金失败'); + } + $res2=change_wallet_balance($user_wallet,1,$legal_send->surplus_number, AccountLog::LEGAL_DEAL_BACK_SEND_SELL, '商家撤回'); + if ($res2 !== true) { + throw new \Exception('撤回失败:增加余额失败'); + } + + $seller->lock_seller_balance = bc_sub($seller->lock_seller_balance,$legal_send->surplus_number,5); + + $seller->save(); + + + } + $legal_send->is_shelves = 2; + $legal_send->is_sendback=2; + $legal_send->is_done = 2; + $legal_send->save(); + + DB::commit(); + return $this->success('撤回成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } + + + + public function errorSend(Request $request) + { + $id = $request->get('id', null); + if (empty($id)) return $this->error('参数错误'); + + try { + DB::beginTransaction(); + $legal_send = LegalDealSend::lockForUpdate()->find($id); + if (empty($legal_send)) { + DB::rollback(); + return $this->error('无此记录'); + } + $is = LegalDealSend::isHasIncompleteness($id); + if ($is){ + DB::rollback(); + return $this->error('该发布信息下有交易未完成,不能标记为异常'); + } + + if ($legal_send->surplus_number >= $legal_send->min_number){ + DB::rollback(); + return $this->error('该发布信息无异常'); + } + if ($legal_send->surplus_number <= 0){ + DB::rollback(); + return $this->error('该发布剩余数量不足,不法标记异常'); + } + if ($legal_send->is_done != 0) { + throw new \Exception('当前发布状态无法标记异常'); + } + + $user_id = Users::getUserId(); + $seller = Seller::where('user_id', $user_id)->where('currency_id', $legal_send->currency_id)->lockForUpdate()->first(); + if (empty($seller)) { + DB::rollback(); + return $this->error('对不起,您不是该法币的商家'); + } + if ($legal_send->type == 'sell') { //如果商家发布出售信息 + if ($seller->lock_seller_balance < $legal_send->surplus_number){ + DB::rollback(); + return $this->error('对不起,您的商家账户锁定资金不足'); + } + + $user_wallet=UsersWallet::where("user_id",$user_id)->where("currency", $legal_send->currency_id)->lockForUpdate()->first(); + $res1=change_wallet_balance($user_wallet,1,-$legal_send->surplus_number, AccountLog::LEGAL_DEAL_ERROR_SEND_SELL, '商家处理异常',true); + if ($res1 !== true) { + throw new \Exception('处理异常失败:减少锁定资金失败'); + } + $res2=change_wallet_balance($user_wallet,1,$legal_send->surplus_number, AccountLog::LEGAL_DEAL_ERROR_SEND_SELL, '商家处理异常'); + if ($res2 !== true) { + throw new \Exception('处理异常失败:增加余额失败'); + } + + $seller->lock_seller_balance = bc_sub($seller->lock_seller_balance,$legal_send->surplus_number,5); + + $seller->save(); + + } + $legal_send->is_done = 1; + $legal_send->save(); +// $legal_send->delete(); + DB::commit(); + return $this->success('处理成功'); + } catch (\Exception $exception) { + DB::rollback(); + return $this->error($exception->getMessage()); + } + } +} diff --git a/app/Http/Controllers/Api/LeverController -old.php b/app/Http/Controllers/Api/LeverController -old.php new file mode 100644 index 0000000..d9bb79c --- /dev/null +++ b/app/Http/Controllers/Api/LeverController -old.php @@ -0,0 +1,1024 @@ +error("参数错误:("); + } + $lever_share_limit = [ + 'min' => 1, + 'max' => 0, + ]; + $curreny_match = CurrencyMatch::where('legal_id', $legal_id) + ->where('currency_id', $currency_id) + ->first(); + if ($curreny_match) { + $lever_share_limit = array_merge($lever_share_limit, [ + 'min' => $curreny_match->lever_min_share, + 'max' => $curreny_match->lever_max_share, + ]); + } + $my_transaction = LeverTransaction::with('user') + ->orderBy('id', 'desc') + ->where("user_id", $user_id) + ->where("status", LeverTransaction::TRANSACTION) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->orderBy("id", "desc") + ->take(10) + ->get(); + $last_price = LeverTransaction::getLastPrice($legal_id, $currency_id); + $user_lever = 0; + $all_levers = 0; + if (!empty($user_id)) { + $legal = UsersWallet::where("user_id", $user_id)->where("currency", $legal_id)->first(); + if ($legal) { + $user_lever = $legal->lever_balance; + } + $all_levers = LeverTransaction::where("legal", $legal_id) + ->where("currency", $currency_id) + ->where("user_id", $user_id) + ->where("status", LeverTransaction::TRANSACTION) + ->selectRaw('sum(`number` * `price`) as `all_levers`') + ->value('all_levers'); + $all_levers || $all_levers = 0; + } + //$match_transaction = $this->getLastMathTransaction($legal_id, $currency_id); + $lever_transaction = $this->getLastLeverTransaction($legal_id, $currency_id); + $ustd_price = 0; + $last = TransactionComplete::orderBy('id', 'desc') + ->where("currency", $legal_id) + ->where("legal", 3) + ->first(); + if (!empty($last)) { + $ustd_price = $last->price; + } + if ($legal_id == 3) { + $ustd_price = 1; + } + return $this->success([ + //"match_transaction" => $match_transaction, + "lever_transaction" => $lever_transaction, + "my_transaction" => $my_transaction, + "lever_share_limit" => $lever_share_limit, + "multiple" => LeverTransaction::leverMultiple($key = 0,$currency_id), + "last_price" => $last_price, +// "last_price" => 10, + "user_lever" => $user_lever, + "all_levers" => $all_levers, + "ustd_price" => $ustd_price, + "ExRAte" => Setting::getValueByKey('USDTRate', 6.5), + ]); + } + + /** + * 交易列表 + * + * @return \Illuminate\Http\JsonResponse + */ + public function dealAll() + { + $user_id = Users::getUserId(); + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + $status = Input::get('status', LeverTransaction::TRANSACTION); + $limit = Input::get("limit", 10); + $page = Input::get("page", 1); + if (empty($legal_id) || empty($currency_id)) { + return $this->error("参数错误"); + } + $lever_transaction = LeverTransaction::with('user') + ->orderBy('id', 'desc') + ->where("user_id", $user_id) + ->where("status", $status) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->paginate($limit); + $user_wallet = UsersWallet::where('currency', $legal_id)->where('user_id', $user_id)->first(); + $balance = $user_wallet ? $user_wallet->lever_balance : 0; + //取盈亏总额 + list( + 'caution_money_total' => $caution_money_all, + 'origin_caution_money_total' => $origin_caution_money_all, + 'profits_total' => $profits_all + ) = LeverTransaction::getUserProfit($user_id, $legal_id); + //取该交易对盈亏总额 + list( + 'caution_money_total' => $caution_money, + 'origin_caution_money_total' => $origin_caution_money, + 'profits_total' => $profits + ) = LeverTransaction::getUserProfit($user_id, $legal_id, $currency_id); + $total_all_money = bc_add($caution_money_all, $balance); + $hazard_rate = LeverTransaction::getWalletHazardRate($user_wallet); + $data = [ + 'balance' => $balance, + 'hazard_rate' => $hazard_rate,//风险率 + 'caution_money_total' => $caution_money_all, + 'origin_caution_money_total' => $origin_caution_money_all, + 'profits_total' => $profits_all,//持仓总盈亏 + 'caution_money' => $caution_money, + 'origin_caution_money' => $origin_caution_money, + 'profits' => $profits, + 'order' => $lever_transaction, + ]; +// var_dump($lever_transaction->toArray());die; + return $this->success($data); + } + + + public function dataget() + { + $user_id = Users::getUserId(); + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + $user_wallet = UsersWallet::where('currency', $legal_id)->where('user_id', $user_id)->first(); + $data['lever_balance']=$user_wallet ? $user_wallet->lever_balance : 0; + $Marginratio=DB::table('lever_transaction')->where('legal', $legal_id)->where('user_id', $user_id)->where('status',1)->sum('Marginratio'); + $data['fact_profits']=DB::table('lever_transaction')->where('legal', $legal_id)->where('user_id', $user_id)->where('status',1)->sum('fact_profits'); + $data['marginratio']=$Marginratio == 0 ? 0 : ($data['lever_balance']+$Marginratio)/$Marginratio; + return $this->success($data); + } + + /** + * 我的交易 + * + * @return \Illuminate\Http\JsonResponse + */ + public function myTrade() + { + $user_id = Users::getUserId(); + $legal_id = Input::get("legal_id", 0); + $currency_id = Input::get("currency_id", 0); + $status = Input::get("status", -1); + $limit = Input::get("limit", 10); + + //接入风险率和持仓总盈亏 +// if (empty($legal_id) || empty($currency_id)) { +// return $this->error("参数错误"); +// } +// $lever_transaction = LeverTransaction::with('user') +// ->orderBy('id', 'desc') +// ->where("user_id", $user_id) +// ->where("status", LeverTransaction::TRANSACTION) +// ->where("currency", $currency_id) +// ->where("legal", $legal_id) +// ->paginate($limit); +// $user_wallet = UsersWallet::where('currency', $legal_id)->where('user_id', $user_id)->first(); + $user_wallet = UsersWallet::where('currency', 3)->where('user_id', $user_id)->first();//法币只有USDT + $balance = $user_wallet ? $user_wallet->lever_balance : 0; + //取盈亏总额 + list( + 'caution_money_total' => $caution_money_all, + 'origin_caution_money_total' => $origin_caution_money_all, + 'profits_total' => $profits_all + ) = LeverTransaction::getUserProfit($user_id, 3); + //取该交易对盈亏总额 + list( + 'caution_money_total' => $caution_money, + 'origin_caution_money_total' => $origin_caution_money, + 'profits_total' => $profits + ) = LeverTransaction::getUserProfit($user_id, 3, $currency_id); +// $total_all_money = bc_add($caution_money_all, $balance); + $hazard_rate = LeverTransaction::getWalletHazardRate($user_wallet); + $lever_transaction['rate_profits_total'] = [ + 'hazard_rate' => $hazard_rate, + 'profits_total' => $profits_all, + ]; + //接入风险率和持仓总盈亏end + + $param = compact('status', 'legal_id', 'currency_id'); + $lever_transaction['message'] = LeverTransaction::where(function ($query) use ($param) { + extract($param); + $status != -1 && $query->where('status', $status); + $legal_id > 0 && $query->where('legal', $legal_id); + $currency_id > 0 && $query->where('currency', $currency_id); + })->where('user_id', $user_id) + ->orderBy('id', 'desc') + ->paginate($limit); + return $this->success($lever_transaction); + } + + + public function mylsOrder() + { + $user_id = Users::getUserId(); + $legal_id = Input::get("legal_id", 0); + $currency_id = Input::get("currency_id", 0); + $limit = Input::get("limit", 10); + + $param = compact( 'legal_id', 'currency_id'); + $data = DB::table('lever_transaction_log')->where(function ($query) use ($param) { + extract($param); + $legal_id > 0 && $query->where('legal', $legal_id); + $currency_id > 0 && $query->where('currency', $currency_id); + })->where('user_id', $user_id) + ->orderBy('id', 'desc') + ->paginate($limit); + + + foreach ($data as $key =>$v){ + $v->create_time=date('Y-m-d H:i:s',$v->create_time); + $v->transaction_time=date('Y-m-d H:i:s',$v->transaction_time); + $v->update_time=date('Y-m-d H:i:s',$v->update_time); + $v->handle_time=date('Y-m-d H:i:s',$v->handle_time); + $v->complete_time=date('Y-m-d H:i:s',$v->complete_time); + } + return $this->success($data); + } + + + /** + * 提交杆杠交易 + * + * @return void + */ +// public function submit() +// { +// $user_id = Users::getUserId(); +// $share = Input::get("share"); +// $multiple = Input::get("multiple"); +// $type = Input::get("type", "1"); +// $legal_id = Input::get("legal_id"); +// $currency_id = Input::get("currency_id"); +// $status = Input::get('status', LeverTransaction::TRANSACTION); //默认是市价交易,为0则是挂单交易 +// $target_price = Input::get('target_price', 0); //目标价格 +// $now = time(); +// $user_lever = 0; +// +// if (empty($legal_id) || empty($currency_id) || empty($share) || empty($multiple)) { +// return $this->error("缺少参数或传值错误"); +// } +// $currency_match = CurrencyMatch::where('legal_id', $legal_id) +// ->where('currency_id', $currency_id) +// ->first(); +// if (!$currency_match) { +// return $this->error('指定交易对不存在'); +// } +// if ($currency_match->open_lever != 1) { +// return $this->error('您未开通本交易对的交易功能'); +// } +// //手数判断:大于0的整数,且在区间范围内 +// if ($share != intval($share) || !is_numeric($share) || $share <= 0) { +// return $this->error('手数必须是大于0的整数'); +// } +// if (bc_comp($currency_match->lever_min_share, $share) > 0) { +// return $this->error('手数不能低于' . $currency_match->lever_min_share); +// } +// if (bc_comp($currency_match->lever_max_share, $share) < 0 && bc_comp($currency_match->lever_max_share, 0) > 0) { +// return $this->error('手数不能高于' . $currency_match->lever_max_share); +// } +// //倍数判断 +// $multiples = LeverMultiple::where("type", 1)->pluck('value')->all(); +// if (!in_array($multiple, $multiples)) { +// return $this->error('选择倍数不在系统范围'); +// } +// //$lever_min_share->lever_max_share +// $exist_close_trade = LeverTransaction::where('user_id', $user_id)->where('status', LeverTransaction::CLOSING)->count(); +// if ($exist_close_trade > 0) { +// return $this->error('您有正在平仓中的交易,暂不能进行买卖'); +// } +// if (!in_array($status, [LeverTransaction::ENTRUST, LeverTransaction::TRANSACTION])) { +// return $this->error('交易类型错误'); +// } +// if ($status == LeverTransaction::ENTRUST) { +// $open_lever_entrust = Setting::getValueByKey('open_lever_entrust', 0); +// if ($open_lever_entrust <= 0) { +// return $this->error('该功能暂未开放'); +// } +// } +// //判断是否委托交易 (限价交易) +// if ($status == LeverTransaction::ENTRUST && $target_price <= 0) { +// return $this->error('限价交易价格必须大于0'); +// } +// $overnight = $currency_match->overnight ?? 0; +// //优先从行情取最新价格 +// $last_price = LeverTransaction::getLastPrice($legal_id, $currency_id); +// if (empty($last_price)) { +// return $this->error('当前没有获取到行情价格,请稍后重试'); +// } +// //挂单委托(限价交易)价格取用户设置的 +// if ($status == LeverTransaction::ENTRUST) { +// if ($type == LeverTransaction::SELL && $target_price <= $last_price) { +// return $this->error('限价交易卖出不能低于当前价'); +// } elseif ($type == LeverTransaction::BUY && $target_price >= $last_price) { +// return $this->error('限价交易买入价格不能高于当前价'); +// } +// $origin_price = $target_price; +// } else { +// $origin_price = $last_price; +// } +// //交易手数转换 +// $lever_share_num = $currency_match->lever_share_num ?? 1; +// $num = bc_mul($share, $lever_share_num); +// //点差率 +// $spread = $currency_match->spread; +// $spread_price = bc_div(bc_mul($origin_price, $spread), 100); +// $type == LeverTransaction::SELL && $spread_price = bc_mul(-1, $spread_price); //买入应加上点差,卖出就减去点差 +// $fact_price = bc_add($origin_price, $spread_price); //收取点差之后的实际价格 +// $all_money = bc_mul($fact_price, $num, 5); +// //计算手续费 +// $lever_trade_fee_rate = bc_div($currency_match->lever_trade_fee ?? 0, 100); +// $trade_fee = bc_mul($all_money, $lever_trade_fee_rate); +// DB::beginTransaction(); +// try { +// $legal = UsersWallet::where("user_id", $user_id) +// ->where("currency", $legal_id) +// ->lockForUpdate() +// ->first(); +// if (!$legal) { +// throw new \Exception("钱包未找到,请先添加钱包"); +// } +// $user_lever = $legal->lever_balance; +// $caution_money = bc_div($all_money, $multiple); //保证金 +// $shoud_deduct = bc_add($caution_money, $trade_fee); //保证金+手续费 +// if (bc_comp($user_lever, $shoud_deduct) < 0) { +// throw new \Exception($currency_match->legal_name . "余额不足,不能小于" . $shoud_deduct . '(手续费:' . $trade_fee . ')'); +// } +// $lever_transaction = new LeverTransaction(); +// $lever_transaction->user_id = $user_id; +// $lever_transaction->type = $type; +// $lever_transaction->overnight = $overnight; +// $lever_transaction->origin_price = $origin_price; +// $lever_transaction->price = $fact_price; +// $lever_transaction->update_price = $last_price; +// $lever_transaction->share = $share; +// $lever_transaction->number = $num; +// $lever_transaction->origin_caution_money = $caution_money; +// $lever_transaction->caution_money = $caution_money; +// $lever_transaction->currency = $currency_id; +// $lever_transaction->legal = $legal_id; +// $lever_transaction->multiple = $multiple; +// $lever_transaction->trade_fee = $trade_fee; +// $lever_transaction->transaction_time = $now; +// $lever_transaction->create_time = $now; +// $lever_transaction->status = $status; +// $result = $lever_transaction->save(); +// if (!$result) { +// throw new \Exception("提交失败"); +// } +// //扣除保证金 +// $result = change_wallet_balance( +// $legal, +// 3, +// -$caution_money, +// AccountLog::LEVER_TRANSACTION, +// '提交' . $currency_match->symbol . '杠杆交易,价格' . $fact_price . ',扣除保证金', +// false, +// 0, +// 0, +// serialize([ +// 'trade_id' => $lever_transaction->id, +// 'all_money' => $all_money, +// 'multiple' => $multiple, +// ]) +// ); +// if ($result !== true) { +// throw new \Exception('扣除保证金失败:' . $result); +// } +// //扣除手续费 +// $result = change_wallet_balance( +// $legal, +// 3, +// -$trade_fee, +// AccountLog::LEVER_TRANSACTION_FEE, +// '提交' . $currency_match->symbol . '杠杆交易,扣除手续费', +// false, +// 0, +// 0, +// serialize([ +// 'trade_id' => $lever_transaction->id, +// 'all_money' => $all_money, +// 'lever_trade_fee_rate' => $lever_trade_fee_rate, +// ]) +// ); +// if ($result !== true) { +// throw new \Exception('扣除手续费失败:' . $result); +// } +// DB::commit(); +// //推荐奖:手续费结算 +// event(new LeverSubmitOrder($lever_transaction)); +// return $this->success("提交成功"); +// } catch (\Exception $ex) { +// DB::rollBack(); +// return $this->error($ex->getMessage()); +// } +// } + + public function submit() + { + $user_id = Users::getUserId(); + $share = Input::get("share"); + + $multiple=1; + $type = Input::get("type", "1"); + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + $status = Input::get('status', LeverTransaction::TRANSACTION); //默认是市价交易,为0则是挂单交易 + $target_price = Input::get('target_price', 0); //目标价格 + $now = time(); + $user_lever = 0; + // file_put_contents('/www/wwwroot/amex.theice.vip/public/t.txt',date('Y-m-d H:i:s')."--------status:".$status."----------target_price:".$target_price.PHP_EOL,FILE_APPEND); + + // if (empty($legal_id) || empty($currency_id) || empty($share) || empty($multiple)) { + if (empty($legal_id) || empty($currency_id)) { + return $this->error("缺少参数或传值错误"); + } + $currency_match = CurrencyMatch::where('legal_id', $legal_id) + ->where('currency_id', $currency_id) + ->first(); + if (!$currency_match) { + return $this->error('指定交易对不存在'); + } + if ($currency_match->open_lever != 1) { + return $this->error('您未开通本交易对的交易功能'); + } + //手数判断:大于0的整数,且在区间范围内 + if ($share != intval($share) || !is_numeric($share) || $share <= 0) { + return $this->error('手数必须是大于0的整数'); + } + if (bc_comp($currency_match->lever_min_share, $share) > 0) { + return $this->error($this->returnStr('手数不能低于') . $currency_match->lever_min_share); + } + if (bc_comp($currency_match->lever_max_share, $share) < 0 && bc_comp($currency_match->lever_max_share, 0) > 0) { + return $this->error($this->returnStr('手数不能高于') . $currency_match->lever_max_share); + } + //倍数判断 + /* + $multiples = LeverMultiple::where("type", 1)->pluck('value')->all(); + if (!in_array($multiple, $multiples)) { + return $this->error('选择倍数不在系统范围'); + } + */ + //$lever_min_share->lever_max_share + + $last_price = LeverTransaction::getLastPrice($legal_id, $currency_id); + if (bc_comp($last_price, 0) <= 0) { + return $this->error('当前没有获取到行情价格,请稍后重试'); + } + + + //判断是否委托交易 (限价交易) + if ($status == LeverTransaction::ENTRUST && $target_price <= 0) { + return $this->error('限价交易价格必须大于0'); + } +// $overnight = $currency_match->overnight ?? 0; +// //优先从行情取最新价格 + + $last_price = LeverTransaction::getLastPrice($legal_id, $currency_id); + if (bc_comp($last_price, 0) <= 0) { + return $this->error('当前没有获取到行情价格,请稍后重试'); + } + +// //挂单委托(限价交易)价格取用户设置的 + if ($status == LeverTransaction::ENTRUST) { + if ($type == LeverTransaction::SELL && $target_price <= $last_price) { + return $this->error('限价交易卖出不能低于当前价'); + } elseif ($type == LeverTransaction::BUY && $target_price >= $last_price) { + return $this->error('限价交易买入价格不能高于当前价'); + } + $origin_price = $target_price; + } else { + $origin_price = $last_price; + } + + + //交易手数转换 + $lever_share_num = $currency_match->lever_share_num ?? 1; + $num = $all_money = bc_mul($share, $lever_share_num); + + //计算手续费 + $lever_trade_fee_rate = bc_div($currency_match->lever_trade_fee ?? 0, 100); + $trade_fee = bc_mul($all_money, $lever_trade_fee_rate); + + + //初始保证金=手数*1000 + $all_money=bc_mul($share,1000); + //手续费=手数*30 + $trade_fee=bc_mul($share,30); + DB::beginTransaction(); + try { + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", $legal_id) + ->lockForUpdate() + ->first(); + if (!$legal) { + throw new \Exception("钱包未找到,请先添加钱包"); + } + $user_lever = $legal->lever_balance; + + $caution_money = $all_money;//bc_div($all_money, $multiple); //保证金 + + if($type==1){ //强平价格 + $QiangpingPrice =$last_price-$caution_money; + } + if($type==2){ + + $QiangpingPrice =$last_price+$caution_money; + } + + $Marginratio =bc_div(bc_add($user_lever,$caution_money),$caution_money); //保证金率 + + // $QiangpingPrice = $type==1? //需要计算 + + $shoud_deduct = bc_add($caution_money, $trade_fee); //保证金+手续费 + if (bc_comp($user_lever, $shoud_deduct) < 0) { + throw new \Exception($currency_match->legal_name . $this->returnStr('余额不足,不能小于') . $shoud_deduct . $this->returnStr('(手续费:') . $trade_fee . ')'); + } + + $lever_transaction =LeverTransaction::where('user_id',$user_id) + ->where('type',$type) + ->where('currency',$currency_id) + ->where('legal',$legal_id) + ->where('status',1) + ->first(); + if($lever_transaction && $status!=0){ + $update['share']=bcadd($lever_transaction->share,$share); + $update['sheng_share']=bcadd($lever_transaction->sheng_share,$share); + $update['origin_caution_money']=bcadd($lever_transaction->origin_caution_money,$caution_money); + $update['caution_money']=bcadd($lever_transaction->caution_money,$caution_money); + $update['trade_fee']=bcadd($lever_transaction->trade_fee,$trade_fee); + $update['Marginratio']=bc_div(bc_add($user_lever,$caution_money),$caution_money); + // var_dump($update);die; + $result= LeverTransaction::where('user_id',$user_id) + ->where('type',$type) + ->where('id',$lever_transaction->id) + ->where('currency',$currency_id) + ->where('legal',$legal_id)->where('status',1)->update($update); + + + $logdata['user_id']=$lever_transaction->user_id; + $logdata['type']=$lever_transaction->type; + $logdata['origin_price']=$lever_transaction->origin_price; + $logdata['price']=$lever_transaction->price; + $logdata['update_price']=$lever_transaction->update_price; + $logdata['share']=bcadd($lever_transaction->sheng_share,$share); + $logdata['level_transaction_id']=$lever_transaction->id; + $logdata['ping_share']=$share; + $logdata['number']=$lever_transaction->number; + $logdata['origin_caution_money']=bcmul($share,1000); + $logdata['number']=$lever_transaction->caution_money; + $logdata['caution_money']=bcadd($lever_transaction->caution_money,$caution_money);; + $logdata['QiangpingPrice']=$lever_transaction->QiangpingPrice; + $logdata['currency']=$lever_transaction->currency; + $logdata['legal']=$lever_transaction->legal; + $logdata['multiple']=$lever_transaction->multiple; + $logdata['trade_fee']=bcmul($share,30); + $logdata['transaction_time']=time(); + $logdata['create_time']=$lever_transaction->create_time; + $logdata['status']=$lever_transaction->status; + $logdata['orderbuy_type']=0; + DB::table('lever_transaction_log')->insert($logdata); + + + }else{ + + $lever_transaction = new LeverTransaction(); + $lever_transaction->user_id = $user_id; + $lever_transaction->type = $type; + // $lever_transaction->overnight = $overnight; + $lever_transaction->origin_price = $origin_price; + $lever_transaction->price = $origin_price;//$fact_price; + $lever_transaction->update_price = $last_price; + $lever_transaction->share = $share; + $lever_transaction->sheng_share=$share; + $lever_transaction->number = $num; + $lever_transaction->origin_caution_money = $caution_money; + $lever_transaction->caution_money = $caution_money; + $lever_transaction->Marginratio = $Marginratio; + $lever_transaction->QiangpingPrice = $QiangpingPrice>0?$QiangpingPrice:0; + $lever_transaction->currency = $currency_id; + $lever_transaction->legal = $legal_id; + $lever_transaction->multiple = $multiple; + $lever_transaction->trade_fee = $trade_fee; + $lever_transaction->transaction_time = $now; + $lever_transaction->create_time = $now; + $lever_transaction->status = $status; + + //追加用户的代理商关系 + $user=Users::find($user_id); + $lever_transaction->agent_path =$user->agent_path; + + $result = $lever_transaction->save(); + + if($status!=0){ + $logdata['user_id']=$lever_transaction->user_id; + $logdata['type']=$lever_transaction->type; + $logdata['origin_price']=$lever_transaction->origin_price; + $logdata['price']=$lever_transaction->price; + $logdata['update_price']=$lever_transaction->update_price; + $logdata['share']=$lever_transaction->share; + $logdata['level_transaction_id']=$lever_transaction->id; + $logdata['ping_share']=0; + $logdata['number']=$lever_transaction->number; + $logdata['origin_caution_money']=$lever_transaction->origin_caution_money; + $logdata['number']=$lever_transaction->caution_money; + $logdata['caution_money']=$lever_transaction->Marginratio; + $logdata['QiangpingPrice']=$lever_transaction->QiangpingPrice; + $logdata['currency']=$lever_transaction->currency; + $logdata['legal']=$lever_transaction->legal; + $logdata['multiple']=$lever_transaction->multiple; + $logdata['trade_fee']=$lever_transaction->trade_fee; + $logdata['transaction_time']=$lever_transaction->transaction_time; + $logdata['create_time']=$lever_transaction->create_time; + $logdata['status']=$lever_transaction->status; + $logdata['orderbuy_type']=0; + + DB::table('lever_transaction_log')->insert($logdata); + } + + } + if (!$result) { + throw new \Exception("提交失败"); + } + //扣除保证金 + $result = change_wallet_balance( + $legal, + 3, + -$caution_money, + AccountLog::LEVER_TRANSACTION, + '提交' . $currency_match->symbol . '杠杆交易,价格' . $last_price . ',扣除保证金', + false, + 0, + 0, + serialize([ + 'trade_id' => $lever_transaction->id, + 'all_money' => $all_money, + 'multiple' => $multiple, + ]) + ); + if ($result !== true) { + throw new \Exception($this->returnStr('扣除保证金失败:') . $result); + } + //扣除手续费 + $result = change_wallet_balance( + $legal, + 3, + -$trade_fee, + AccountLog::LEVER_TRANSACTION_FEE, + '提交' . $currency_match->symbol . '杠杆交易,扣除手续费', + false, + 0, + 0, + serialize([ + 'trade_id' => $lever_transaction->id, + 'all_money' => $all_money, + 'lever_trade_fee_rate' => $lever_trade_fee_rate, + ]) + ); + if ($result !== true) { + throw new \Exception($this->returnStr('扣除手续费失败:') . $result); + } + DB::commit(); +// var_dump($lever_transaction->toArray()); + //推荐奖:手续费结算 +// $PP=event(new LeverSubmitOrder($lever_transaction)); +// var_dump($PP);die; + return $this->success("提交成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + /** + * 设置止盈止亏 + * + * @return \Illuminate\Http\JsonResponse + */ + public function setStopPrice() + { + $user_set_stopprice = Setting::getValueByKey('user_set_stopprice', 0); + if (!$user_set_stopprice) { + return $this->error('此功能系统未开放'); + } + $id = Input::get('id', 0); + $user_id = Users::getUserId(); + $target_profit_price = Input::get('target_profit_price', 0); + $stop_loss_price = Input::get('stop_loss_price', 0); + if ($target_profit_price <= 0 || $stop_loss_price <= 0) { + return $this->error('止盈止损价格不能为0'); + } + $lever_transaction = LeverTransaction::where('user_id', $user_id) + ->where('status', LeverTransaction::TRANSACTION) + ->find($id); + if (!$lever_transaction) { + return $this->error('找不到该笔交易'); + } + if ($lever_transaction->type == 1) { + //买入 + if ($target_profit_price <= $lever_transaction->price || $target_profit_price <= $lever_transaction->update_price) { + return $this->error('买入(做多)止盈价不能低于开仓价和当前价'); + } + if ($stop_loss_price >= $lever_transaction->price || $stop_loss_price >= $lever_transaction->update_price) { + return $this->error('买入(做多)止亏价不能高于开仓价和当前价'); + } + } else { + //卖出 + if ($target_profit_price >= $lever_transaction->price || $target_profit_price >= $lever_transaction->update_price) { + return $this->error('卖出(做空)止盈价不能高于开仓价和当前价'); + } + if ($stop_loss_price <= $lever_transaction->price || $stop_loss_price <= $lever_transaction->update_price) { + return $this->error('卖出(做空)止亏价不能低于开仓价和当前价'); + } + } + $target_profit_price > 0 && $lever_transaction->target_profit_price = $target_profit_price; + $stop_loss_price > 0 && $lever_transaction->stop_loss_price = $stop_loss_price; + $result = $lever_transaction->save(); + return $result ? $this->success('设置成功') : $this->error('设置失败'); + } + + /** + * 平仓 + * + * @return \Illuminate\Http\JsonResponse + */ + public function close() + { + $user_id = Users::getUserId(); + $id = Input::get("id"); + $ping_share = Input::get("ping_share"); + if (empty($id)) { + return $this->error("参数错误"); + } + DB::beginTransaction(); + try { + $lever_transaction = LeverTransaction::lockForupdate()->find($id); + if (empty($lever_transaction)) { + throw new \Exception("数据未找到"); + } + if ($lever_transaction->user_id != $user_id) { + throw new \Exception("无权操作"); + } + if ($lever_transaction->sheng_share < $ping_share) { + throw new \Exception("平仓数量不能大于持有数量"); + } + if ($lever_transaction->status != LeverTransaction::TRANSACTION) { + throw new \Exception("交易状态异常,请勿重复提交"); + } + + if ($lever_transaction->order_type == 2) { //跟随的订单禁止主动平仓 + throw new \Exception("无权操作"); + } + + $return = LeverTransaction::leverClose($lever_transaction,$ping_share); + if (!$return) { + throw new \Exception("平仓失败,请重试"); + } + if($lever_transaction->origin_price <= 0){ + throw new \Exception("交易异常,无法平仓"); + } + DB::commit(); + return $this->success("操作成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + /** + * 批量平仓(按买卖方向) + * + * @return \Illuminate\Http\JsonResponse + */ + public function batchCloseByType(Request $request) + { + $user_id = Users::getUserId(); + $legal_id = $request->input('legal_id', 0); + $currency_id = $request->input('currency_id', 0); + $type = $request->input('type', 0); //0.所有,1.买入(做多),2.卖出(做空) + if (!in_array($type, [0, 1, 2])) { + return $this->error('买入方向传参错误'); + } + $lever = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->where('user_id', $user_id) + ->where(function ($query) use ($type, $legal_id, $currency_id) { + !empty($legal_id) && $query->where('legal', $legal_id); + !empty($currency_id) && $query->where('currency', $currency_id); + !empty($type) && $query->where('type', $type); + })->get(); + $task_list = $lever->pluck('id')->all(); + $result = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->whereIn('id', $task_list) + ->update([ + 'status' => LeverTransaction::CLOSING, + 'handle_time' => microtime(true), + ]); + if ($result > 0) { + LeverClose::dispatch($task_list, true)->onQueue('lever:close'); + } + return $result > 0 ? $this->success('提交成功,请等待系统处理') : $this->error('未找到需要平仓的交易'); + } + + /** + * 批量平仓(按盈亏) + * + * @return \Illuminate\Http\JsonResponse + */ + public function batchCloseByProfit(Request $request) + { + $user_id = Users::getUserId(); + $type = $request->input('type'); //0.所有,1.盈,2.亏 + $lever = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->where('user_id', $user_id) + ->get(); + switch ($type) { + case 1: + $lever = $lever->where('profits', '>', 0); + break; + case 2: + $lever = $lever->where('profits', '<', 0); + break; + default: + } + $task_list = $lever->pluck('id')->all(); + $result = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->whereIn('id', $task_list) + ->update([ + 'status' => LeverTransaction::CLOSING, + 'handle_time' => microtime(true), + ]); + if ($result > 0) { + LeverClose::dispatch($task_list, true)->onQueue('lever:close'); + } + return $result > 0 ? $this->success('提交成功,请等待系统处理') : $this->error('未找到需要平仓的交易'); + } + + /** + * 取最近几条撮合交易 + * + * @param integer $legal_id 法币id + * @param integer $currency_id 交易币id + * @param integer $limit 限制条数,默认5 + * @return array + */ + public function getLastMathTransaction($legal_id, $currency_id, $limit = 5) + { + $in = TransactionIn::with(['legalcoin', 'currencycoin']) + ->where("number", ">", 0) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->groupBy('currency', 'legal', 'price') + ->orderBy('price', 'desc') + ->select([ + 'currency', + 'legal', + 'price', + ])->selectRaw('sum(`number`) as `number`') + ->limit($limit) + ->get(); + $out = TransactionOut::with(['legalcoin', 'currencycoin']) + ->where("number", ">", 0) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->groupBy('currency', 'legal', 'price') + ->orderBy('price', 'asc') + ->select([ + 'currency', + 'legal', + 'price', + ])->selectRaw('sum(`number`) as `number`') + ->limit($limit) + ->get() + ->sortByDesc('price') + ->values(); + return [ + 'in' => $in, + 'out' => $out, + ]; + } + + /** + * 取最近几条杠杆交易 + * + * @param integer $legal_id 法币id + * @param integer $currency_id 交易币id + * @param integer $limit 限制条数,默认5 + * @return array + */ + public function getLastLeverTransaction($legal_id, $currency_id, $limit = 5) + { + $in = LeverTransaction::with('user') + ->where('legal', $legal_id) + ->where('currency', $currency_id) + ->where('type', LeverTransaction::BUY) + ->where('status', LeverTransaction::TRANSACTION) + ->orderBy('price', 'desc') + ->limit($limit) + ->get(); + $out = LeverTransaction::with('user') + ->where('legal', $legal_id) + ->where('currency', $currency_id) + ->where('type', LeverTransaction::SELL) + ->where('status', LeverTransaction::TRANSACTION) + ->orderBy('price', 'asc') + ->limit($limit) + ->get() + ->sortByDesc('price') + ->values(); + return [ + 'in' => $in, + 'out' => $out, + ]; + } + + /** + * 取消挂单(撤单) + * + * @return boolean + */ + public function cancelTrade(Request $request) + { + $user_id = Users::getUserId(); + $id = $request->input('id'); + try { + //退手续费和保证金 + DB::transaction(function () use ($user_id, $id) { + $lever_trade = LeverTransaction::where('user_id', $user_id) + ->where('status', LeverTransaction::ENTRUST) + ->lockForUpdate() + ->find($id); + if (!$lever_trade) { + throw new \Exception('交易不存在或已撤单,请刷新后重试'); + } + $legal_id = $lever_trade->legal; + $refund_trade_fee = $lever_trade->trade_fee; + $refund_caution_money = $lever_trade->caution_money; + $legal_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $legal_id) + ->first(); + if (!$legal_wallet) { + throw new \Exception('撤单失败:用户钱包不存在'); + } + $result = change_wallet_balance( + $legal_wallet, + 3, + $refund_trade_fee, + AccountLog::LEVER_TRANSACTIO_CANCEL, + '杠杆' . $lever_trade->type_name . '委托撤单,退回手续费', + false, + 0, + 0, + '', + true + ); + if ($result !== true) { + throw new \Exception($this->returnStr('撤单失败:') . $result); + } + $result = change_wallet_balance( + $legal_wallet, + 3, + $refund_caution_money, + AccountLog::LEVER_TRANSACTIO_CANCEL, + '杠杆' . $lever_trade->type_name . '委托撤单,退回保证金', + false, + 0, + 0, + '', + true + ); + if ($result !== true) { + throw new \Exception($this->returnStr('撤单失败:') . $result); + } + $lever_trade->status = LeverTransaction::CANCEL; + $lever_trade->complete_time = time(); + $result = $lever_trade->save(); + if (!$result) { + throw new \Exception('撤单失败:变更状态失败'); + } + }); + return $this->success('撤单成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } +} diff --git a/app/Http/Controllers/Api/LeverController.php b/app/Http/Controllers/Api/LeverController.php new file mode 100644 index 0000000..009bcb7 --- /dev/null +++ b/app/Http/Controllers/Api/LeverController.php @@ -0,0 +1,981 @@ +error("参数错误:("); + } + $lever_share_limit = [ + 'min' => 1, + 'max' => 0, + ]; + $curreny_match = CurrencyMatch::where('legal_id', $legal_id) + ->where('currency_id', $currency_id) + ->first(); + if ($curreny_match) { + $lever_share_limit = array_merge($lever_share_limit, [ + 'min' => $curreny_match->lever_min_share, + 'max' => $curreny_match->lever_max_share, + ]); + } + $my_transaction = LeverTransaction::with('user') + ->orderBy('id', 'desc') + ->where("user_id", $user_id) + ->where("status", LeverTransaction::TRANSACTION) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->orderBy("id", "desc") + ->take(10) + ->get(); + $last_price = LeverTransaction::getLastPrice($legal_id, $currency_id); + $user_lever = 0; + $all_levers = 0; + if (!empty($user_id)) { + $legal = UsersWallet::where("user_id", $user_id)->where("currency", $legal_id)->first(); + if ($legal) { + $user_lever = $legal->lever_balance; + } + $all_levers = LeverTransaction::where("legal", $legal_id) + ->where("currency", $currency_id) + ->where("user_id", $user_id) + ->where("status", LeverTransaction::TRANSACTION) + ->selectRaw('sum(`number` * `price`) as `all_levers`') + ->value('all_levers'); + $all_levers || $all_levers = 0; + } + //$match_transaction = $this->getLastMathTransaction($legal_id, $currency_id); + $lever_transaction = $this->getLastLeverTransaction($legal_id, $currency_id); + $ustd_price = 0; + $last = TransactionComplete::orderBy('id', 'desc') + ->where("currency", $legal_id) + ->where("legal", 3) + ->first(); + if (!empty($last)) { + $ustd_price = $last->price; + } + if ($legal_id == 3) { + $ustd_price = 1; + } + return $this->success([ + //"match_transaction" => $match_transaction, + "lever_transaction" => $lever_transaction, + "my_transaction" => $my_transaction, + "lever_share_limit" => $lever_share_limit, + "multiple" => LeverTransaction::leverMultiple($key = 0,$currency_id), + "last_price" => $last_price, +// "last_price" => 10, + "user_lever" => $user_lever, + "all_levers" => $all_levers, + "ustd_price" => $ustd_price, + "ExRAte" => Setting::getValueByKey('USDTRate', 6.5), + ]); + } + + + public function mylsOrder() + { + $user_id = Users::getUserId(); + $legal_id = Input::get("legal_id", 0); + $currency_id = Input::get("currency_id", 0); + $limit = Input::get("limit", 10); + + $param = compact( 'legal_id', 'currency_id'); + $data = DB::table('lever_transaction_log')->where(function ($query) use ($param) { + extract($param); + $legal_id > 0 && $query->where('legal', $legal_id); + $currency_id > 0 && $query->where('currency', $currency_id); + })->where('user_id', $user_id) + ->orderBy('id', 'desc') + ->paginate($limit); + + + foreach ($data as $key =>$v){ + $v->create_time=date('Y-m-d H:i:s',$v->create_time); + $v->transaction_time=date('Y-m-d H:i:s',$v->transaction_time); + $v->update_time=date('Y-m-d H:i:s',$v->update_time); + $v->handle_time=date('Y-m-d H:i:s',$v->handle_time); + $v->complete_time=date('Y-m-d H:i:s',$v->complete_time); + } + return $this->success($data); + } + + + /** + * 交易列表 + * + * @return \Illuminate\Http\JsonResponse + */ + public function dealAll() + { + $user_id = Users::getUserId(); + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + $status = Input::get('status', LeverTransaction::TRANSACTION); + $limit = Input::get("limit", 10); + $page = Input::get("page", 1); + if (empty($legal_id) || empty($currency_id)) { + return $this->error("参数错误"); + } + $lever_transaction = LeverTransaction::with('user') + ->orderBy('id', 'desc') + ->where("user_id", $user_id) + ->where("status", $status) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->paginate($limit); + $user_wallet = UsersWallet::where('currency', $legal_id)->where('user_id', $user_id)->first(); + $balance = $user_wallet ? $user_wallet->lever_balance : 0; + //取盈亏总额 + list( + 'caution_money_total' => $caution_money_all, + 'origin_caution_money_total' => $origin_caution_money_all, + 'profits_total' => $profits_all + ) = LeverTransaction::getUserProfit($user_id, $legal_id); + //取该交易对盈亏总额 + list( + 'caution_money_total' => $caution_money, + 'origin_caution_money_total' => $origin_caution_money, + 'profits_total' => $profits + ) = LeverTransaction::getUserProfit($user_id, $legal_id, $currency_id); + $total_all_money = bc_add($caution_money_all, $balance); + $hazard_rate = LeverTransaction::getWalletHazardRate($user_wallet); + $data = [ + 'balance' => $balance, + 'hazard_rate' => $hazard_rate,//风险率 + 'caution_money_total' => $caution_money_all, + 'origin_caution_money_total' => $origin_caution_money_all, + 'profits_total' => $profits_all,//持仓总盈亏 + 'caution_money' => $caution_money, + 'origin_caution_money' => $origin_caution_money, + 'profits' => $profits, + 'order' => $lever_transaction, + ]; +// var_dump($lever_transaction->toArray());die; + return $this->success($data); + } + + /** + * 我的交易 + * + * @return \Illuminate\Http\JsonResponse + */ + public function myTrade() + { + $user_id = Users::getUserId(); + $legal_id = Input::get("legal_id", 0); + $currency_id = Input::get("currency_id", 0); + $status = Input::get("status", -1); + $limit = Input::get("limit", 10); + + //接入风险率和持仓总盈亏 +// if (empty($legal_id) || empty($currency_id)) { +// return $this->error("参数错误"); +// } +// $lever_transaction = LeverTransaction::with('user') +// ->orderBy('id', 'desc') +// ->where("user_id", $user_id) +// ->where("status", LeverTransaction::TRANSACTION) +// ->where("currency", $currency_id) +// ->where("legal", $legal_id) +// ->paginate($limit); +// $user_wallet = UsersWallet::where('currency', $legal_id)->where('user_id', $user_id)->first(); + $user_wallet = UsersWallet::where('currency', 3)->where('user_id', $user_id)->first();//法币只有USDT + $balance = $user_wallet ? $user_wallet->lever_balance : 0; + //取盈亏总额 + list( + 'caution_money_total' => $caution_money_all, + 'origin_caution_money_total' => $origin_caution_money_all, + 'profits_total' => $profits_all + ) = LeverTransaction::getUserProfit($user_id, 3); + //取该交易对盈亏总额 + list( + 'caution_money_total' => $caution_money, + 'origin_caution_money_total' => $origin_caution_money, + 'profits_total' => $profits + ) = LeverTransaction::getUserProfit($user_id, 3, $currency_id); +// $total_all_money = bc_add($caution_money_all, $balance); + $hazard_rate = LeverTransaction::getWalletHazardRate($user_wallet); + $lever_transaction['rate_profits_total'] = [ + 'hazard_rate' => $hazard_rate, + 'profits_total' => $profits_all, + ]; + //接入风险率和持仓总盈亏end + + $param = compact('status', 'legal_id', 'currency_id'); + $lever_transaction['message'] = LeverTransaction::where(function ($query) use ($param) { + extract($param); + $status != -1 && $query->where('status', $status); + $legal_id > 0 && $query->where('legal', $legal_id); + $currency_id > 0 && $query->where('currency', $currency_id); + })->where('user_id', $user_id) + ->orderBy('id', 'desc') + ->paginate($limit); + return $this->success($lever_transaction); + } + + /** + * 提交杆杠交易 + * + * @return void + */ +// public function submit() +// { +// $user_id = Users::getUserId(); +// $share = Input::get("share"); +// $multiple = Input::get("multiple"); +// $type = Input::get("type", "1"); +// $legal_id = Input::get("legal_id"); +// $currency_id = Input::get("currency_id"); +// $status = Input::get('status', LeverTransaction::TRANSACTION); //默认是市价交易,为0则是挂单交易 +// $target_price = Input::get('target_price', 0); //目标价格 +// $now = time(); +// $user_lever = 0; +// +// if (empty($legal_id) || empty($currency_id) || empty($share) || empty($multiple)) { +// return $this->error("缺少参数或传值错误"); +// } +// $currency_match = CurrencyMatch::where('legal_id', $legal_id) +// ->where('currency_id', $currency_id) +// ->first(); +// if (!$currency_match) { +// return $this->error('指定交易对不存在'); +// } +// if ($currency_match->open_lever != 1) { +// return $this->error('您未开通本交易对的交易功能'); +// } +// //手数判断:大于0的整数,且在区间范围内 +// if ($share != intval($share) || !is_numeric($share) || $share <= 0) { +// return $this->error('手数必须是大于0的整数'); +// } +// if (bc_comp($currency_match->lever_min_share, $share) > 0) { +// return $this->error('手数不能低于' . $currency_match->lever_min_share); +// } +// if (bc_comp($currency_match->lever_max_share, $share) < 0 && bc_comp($currency_match->lever_max_share, 0) > 0) { +// return $this->error('手数不能高于' . $currency_match->lever_max_share); +// } +// //倍数判断 +// $multiples = LeverMultiple::where("type", 1)->pluck('value')->all(); +// if (!in_array($multiple, $multiples)) { +// return $this->error('选择倍数不在系统范围'); +// } +// //$lever_min_share->lever_max_share +// $exist_close_trade = LeverTransaction::where('user_id', $user_id)->where('status', LeverTransaction::CLOSING)->count(); +// if ($exist_close_trade > 0) { +// return $this->error('您有正在平仓中的交易,暂不能进行买卖'); +// } +// if (!in_array($status, [LeverTransaction::ENTRUST, LeverTransaction::TRANSACTION])) { +// return $this->error('交易类型错误'); +// } +// if ($status == LeverTransaction::ENTRUST) { +// $open_lever_entrust = Setting::getValueByKey('open_lever_entrust', 0); +// if ($open_lever_entrust <= 0) { +// return $this->error('该功能暂未开放'); +// } +// } +// //判断是否委托交易 (限价交易) +// if ($status == LeverTransaction::ENTRUST && $target_price <= 0) { +// return $this->error('限价交易价格必须大于0'); +// } +// $overnight = $currency_match->overnight ?? 0; +// //优先从行情取最新价格 +// $last_price = LeverTransaction::getLastPrice($legal_id, $currency_id); +// if (empty($last_price)) { +// return $this->error('当前没有获取到行情价格,请稍后重试'); +// } +// //挂单委托(限价交易)价格取用户设置的 +// if ($status == LeverTransaction::ENTRUST) { +// if ($type == LeverTransaction::SELL && $target_price <= $last_price) { +// return $this->error('限价交易卖出不能低于当前价'); +// } elseif ($type == LeverTransaction::BUY && $target_price >= $last_price) { +// return $this->error('限价交易买入价格不能高于当前价'); +// } +// $origin_price = $target_price; +// } else { +// $origin_price = $last_price; +// } +// //交易手数转换 +// $lever_share_num = $currency_match->lever_share_num ?? 1; +// $num = bc_mul($share, $lever_share_num); +// //点差率 +// $spread = $currency_match->spread; +// $spread_price = bc_div(bc_mul($origin_price, $spread), 100); +// $type == LeverTransaction::SELL && $spread_price = bc_mul(-1, $spread_price); //买入应加上点差,卖出就减去点差 +// $fact_price = bc_add($origin_price, $spread_price); //收取点差之后的实际价格 +// $all_money = bc_mul($fact_price, $num, 5); +// //计算手续费 +// $lever_trade_fee_rate = bc_div($currency_match->lever_trade_fee ?? 0, 100); +// $trade_fee = bc_mul($all_money, $lever_trade_fee_rate); +// DB::beginTransaction(); +// try { +// $legal = UsersWallet::where("user_id", $user_id) +// ->where("currency", $legal_id) +// ->lockForUpdate() +// ->first(); +// if (!$legal) { +// throw new \Exception("钱包未找到,请先添加钱包"); +// } +// $user_lever = $legal->lever_balance; +// $caution_money = bc_div($all_money, $multiple); //保证金 +// $shoud_deduct = bc_add($caution_money, $trade_fee); //保证金+手续费 +// if (bc_comp($user_lever, $shoud_deduct) < 0) { +// throw new \Exception($currency_match->legal_name . "余额不足,不能小于" . $shoud_deduct . '(手续费:' . $trade_fee . ')'); +// } +// $lever_transaction = new LeverTransaction(); +// $lever_transaction->user_id = $user_id; +// $lever_transaction->type = $type; +// $lever_transaction->overnight = $overnight; +// $lever_transaction->origin_price = $origin_price; +// $lever_transaction->price = $fact_price; +// $lever_transaction->update_price = $last_price; +// $lever_transaction->share = $share; +// $lever_transaction->number = $num; +// $lever_transaction->origin_caution_money = $caution_money; +// $lever_transaction->caution_money = $caution_money; +// $lever_transaction->currency = $currency_id; +// $lever_transaction->legal = $legal_id; +// $lever_transaction->multiple = $multiple; +// $lever_transaction->trade_fee = $trade_fee; +// $lever_transaction->transaction_time = $now; +// $lever_transaction->create_time = $now; +// $lever_transaction->status = $status; +// $result = $lever_transaction->save(); +// if (!$result) { +// throw new \Exception("提交失败"); +// } +// //扣除保证金 +// $result = change_wallet_balance( +// $legal, +// 3, +// -$caution_money, +// AccountLog::LEVER_TRANSACTION, +// '提交' . $currency_match->symbol . '杠杆交易,价格' . $fact_price . ',扣除保证金', +// false, +// 0, +// 0, +// serialize([ +// 'trade_id' => $lever_transaction->id, +// 'all_money' => $all_money, +// 'multiple' => $multiple, +// ]) +// ); +// if ($result !== true) { +// throw new \Exception('扣除保证金失败:' . $result); +// } +// //扣除手续费 +// $result = change_wallet_balance( +// $legal, +// 3, +// -$trade_fee, +// AccountLog::LEVER_TRANSACTION_FEE, +// '提交' . $currency_match->symbol . '杠杆交易,扣除手续费', +// false, +// 0, +// 0, +// serialize([ +// 'trade_id' => $lever_transaction->id, +// 'all_money' => $all_money, +// 'lever_trade_fee_rate' => $lever_trade_fee_rate, +// ]) +// ); +// if ($result !== true) { +// throw new \Exception('扣除手续费失败:' . $result); +// } +// DB::commit(); +// //推荐奖:手续费结算 +// event(new LeverSubmitOrder($lever_transaction)); +// return $this->success("提交成功"); +// } catch (\Exception $ex) { +// DB::rollBack(); +// return $this->error($ex->getMessage()); +// } +// } + + public function submit() + { + $user_id = Users::getUserId(); + $share = Input::get("share"); + $multiple = Input::get("multiple"); + $type = Input::get("type", "1"); + $legal_id = Input::get("legal_id"); + $checkType = Input::get("checkType",0); //开启止盈止损 + + $currency_id = Input::get("currency_id"); + $target_profit_price = Input::get('target_profit_price', 0); + $stop_loss_price = Input::get('stop_loss_price', 0); + $status = Input::get('status', LeverTransaction::TRANSACTION); //默认是市价交易,为0则是挂单交易 + $target_price = Input::get('target_price', 0); //目标价格 + $now = time(); + $user_lever = 0; + + if (empty($legal_id) || empty($currency_id) || empty($share) || empty($multiple)) { + return $this->error("缺少参数或传值错误"); + } + $currency_match = CurrencyMatch::where('legal_id', $legal_id) + ->where('currency_id', $currency_id) + ->first(); + + + if (!$currency_match) { + return $this->error('指定交易对不存在'); + } + if ($currency_match->open_lever != 1) { + return $this->error('您未开通本交易对的交易功能'); + } + + if(!$currency_match->is_open){ + + $message = "休市"; + $message = str_replace('massage.', '', __("massage.$message")); + + return $this->error($message); + } + + + + //手数判断:大于0的整数,且在区间范围内 + if ($share != intval($share) || !is_numeric($share) || $share <= 0) { + return $this->error('手数必须是大于0的整数'); + } + if (bc_comp($currency_match->lever_min_share, $share) > 0) { + return $this->error($this->returnStr('手数不能低于') . $currency_match->lever_min_share); + } + if (bc_comp($currency_match->lever_max_share, $share) < 0 && bc_comp($currency_match->lever_max_share, 0) > 0) { + return $this->error($this->returnStr('手数不能高于') . $currency_match->lever_max_share); + } + + $last_price = LeverTransaction::getLastPrice($legal_id, $currency_id); + + + if (bc_comp($last_price, 0) <= 0) { + return $this->error('当前没有获取到行情价格,请稍后重试'); + } + + + if($checkType){ + + if ($target_profit_price <= 0 || $stop_loss_price <= 0) { + return $this->error('止盈止损价格不能为0'); + } + + + + if ($type == 1) { + //买入 + if ($target_profit_price > 0 && $target_profit_price <= $last_price) { + return $this->error('买入(做多)止盈价不能低于开仓价和当前价'); + } + if ($stop_loss_price > 0 && $stop_loss_price >= $last_price) { + return $this->error('买入(做多)止亏价不能高于开仓价和当前价'); + } + } else { + //卖出 + if ($target_profit_price > 0 && $target_profit_price >= $last_price) { + return $this->error('卖出(做空)止盈价不能高于开仓价和当前价'); + } + if ($stop_loss_price > 0 && $stop_loss_price <= $last_price) { + return $this->error('卖出(做空)止亏价不能低于开仓价和当前价'); + } + } + } + + //倍数判断 + $multiples = LeverMultiple::where("type", 1)->pluck('value')->all(); + if (!in_array($multiple, $multiples)) { + // return $this->error('选择倍数不在系统范围'); dapp不需要 + } + //$lever_min_share->lever_max_share + $exist_close_trade = LeverTransaction::where('user_id', $user_id)->where('status', LeverTransaction::CLOSING)->count(); + if ($exist_close_trade > 0) { + return $this->error('您有正在平仓中的交易,暂不能进行买卖'); + } + if (!in_array($status, [LeverTransaction::ENTRUST, LeverTransaction::TRANSACTION])) { + return $this->error('交易类型错误'); + } + if ($status == LeverTransaction::ENTRUST) { + $open_lever_entrust = Setting::getValueByKey('open_lever_entrust', 0); + if ($open_lever_entrust <= 0) { + return $this->error('该功能暂未开放'); + } + } + //判断是否委托交易 (限价交易) + if ($status == LeverTransaction::ENTRUST && $target_price <= 0) { + return $this->error('限价交易价格必须大于0'); + } + $overnight = $currency_match->overnight ?? 0; + //优先从行情取最新价格 + + //挂单委托(限价交易)价格取用户设置的 + if ($status == LeverTransaction::ENTRUST) { + if ($type == LeverTransaction::SELL && $target_price <= $last_price) { + return $this->error('限价交易卖出不能低于当前价'); + } elseif ($type == LeverTransaction::BUY && $target_price >= $last_price) { + return $this->error('限价交易买入价格不能高于当前价'); + } + $origin_price = $target_price; + } else { + $origin_price = $last_price; + } + //交易手数转换 + $lever_share_num = $currency_match->lever_share_num ?? 1; + $num = bc_mul($share, $lever_share_num); + //点差率 +// $spread = $currency_match->spread; +// $spread_price = bc_div(bc_mul($origin_price, $spread), 100); +// $type == LeverTransaction::SELL && $spread_price = bc_mul(-1, $spread_price); //买入应加上点差,卖出就减去点差 +// $fact_price = bc_add($origin_price, $spread_price); //收取点差之后的实际价格 +// $all_money = bc_mul($fact_price, $num, 5); + + + //点差率 点差变成固定值 by tian + $spread_price = $spread = $currency_match->spread; + $type == LeverTransaction::SELL && $spread_price = bc_mul(-1, $spread_price); //买入应加上点差,卖出就减去点差 + $fact_price = bc_add($origin_price, $spread_price); //收取点差之后的实际价格 + $all_money = bc_mul($fact_price, $num, 5); + + //计算手续费 + $lever_trade_fee_rate = bc_div($currency_match->lever_trade_fee ?? 0, 100); + $trade_fee = bc_mul($all_money, $lever_trade_fee_rate); + DB::beginTransaction(); + try { + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", $legal_id) + ->lockForUpdate() + ->first(); + if (!$legal) { + throw new \Exception("钱包未找到,请先添加钱包"); + } + $user_lever = $legal->lever_balance; + $caution_money = bc_div($all_money, $multiple); //保证金 + + $shoud_deduct = bc_add($caution_money, $trade_fee); //保证金+手续费 + if (bc_comp($user_lever, $shoud_deduct) < 0) { + throw new \Exception($currency_match->legal_name . $this->returnStr('余额不足,不能小于') . $shoud_deduct . $this->returnStr('(手续费:') . $trade_fee . ')'); + } + + $lever_transaction = new LeverTransaction(); + $lever_transaction->user_id = $user_id; + $lever_transaction->type = $type; + $lever_transaction->overnight = $overnight; + $lever_transaction->origin_price = $origin_price; + $lever_transaction->price = $fact_price; + $lever_transaction->update_price = $last_price; + $lever_transaction->share = $share; + $lever_transaction->number = $num; + $lever_transaction->origin_caution_money = $caution_money; + $lever_transaction->caution_money = $caution_money; + $lever_transaction->currency = $currency_id; + $lever_transaction->legal = $legal_id; + $lever_transaction->multiple = $multiple; + $lever_transaction->trade_fee = $trade_fee; + $lever_transaction->transaction_time = $now; + $lever_transaction->create_time = $now; + $lever_transaction->status = $status; + + if($checkType){ + $target_profit_price > 0 && $lever_transaction->target_profit_price = $target_profit_price; + $stop_loss_price > 0 && $lever_transaction->stop_loss_price = $stop_loss_price; + + }else + { + $lever_transaction->target_profit_price = 0; + $lever_transaction->stop_loss_price = 0; + + } + + + //追加用户的代理商关系 + $user=Users::find($user_id); + $lever_transaction->agent_path =$user->agent_path; + + // file_put_contents('/www/wwwroot/crypto/public/tt1.txt',time()."---".json_encode($lever_transaction)); + + $result = $lever_transaction->save(); + if (!$result) { + throw new \Exception("提交失败"); + } + //扣除保证金 + $result = change_wallet_balance( + $legal, + 3, + -$caution_money, + AccountLog::LEVER_TRANSACTION, + '提交' . $currency_match->symbol . '杠杆交易,价格' . $fact_price . ',扣除保证金', + false, + 0, + 0, + serialize([ + 'trade_id' => $lever_transaction->id, + 'all_money' => $all_money, + 'multiple' => $multiple, + ]) + ); + if ($result !== true) { + throw new \Exception($this->returnStr('扣除保证金失败:') . $result); + } + //扣除手续费 + $result = change_wallet_balance( + $legal, + 3, + -$trade_fee, + AccountLog::LEVER_TRANSACTION_FEE, + '提交' . $currency_match->symbol . '杠杆交易,扣除手续费', + false, + 0, + 0, + serialize([ + 'trade_id' => $lever_transaction->id, + 'all_money' => $all_money, + 'lever_trade_fee_rate' => $lever_trade_fee_rate, + ]) + ); + if ($result !== true) { + throw new \Exception($this->returnStr('扣除手续费失败:') . $result); + } + DB::commit(); +// var_dump($lever_transaction->toArray()); + //推荐奖:手续费结算 +// $PP=event(new LeverSubmitOrder($lever_transaction)); +// var_dump($PP);die; + return $this->success("提交成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + /** + * 设置止盈止亏 + * + * @return \Illuminate\Http\JsonResponse + */ + public function setStopPrice() + { + $user_set_stopprice = Setting::getValueByKey('user_set_stopprice', 0); + if (!$user_set_stopprice) { + return $this->error('此功能系统未开放'); + } + $id = Input::get('id', 0); + $user_id = Users::getUserId(); + $target_profit_price = Input::get('target_profit_price', 0); + $stop_loss_price = Input::get('stop_loss_price', 0); + if ($target_profit_price <= 0 || $stop_loss_price <= 0) { + return $this->error('止盈止损价格不能为0'); + } + $lever_transaction = LeverTransaction::where('user_id', $user_id) + ->where('status', LeverTransaction::TRANSACTION) + ->find($id); + if (!$lever_transaction) { + return $this->error('找不到该笔交易'); + } + if ($lever_transaction->type == 1) { + //买入 + if ($target_profit_price <= $lever_transaction->price || $target_profit_price <= $lever_transaction->update_price) { + return $this->error('买入(做多)止盈价不能低于开仓价和当前价'); + } + if ($stop_loss_price >= $lever_transaction->price || $stop_loss_price >= $lever_transaction->update_price) { + return $this->error('买入(做多)止亏价不能高于开仓价和当前价'); + } + } else { + //卖出 + if ($target_profit_price >= $lever_transaction->price || $target_profit_price >= $lever_transaction->update_price) { + return $this->error('卖出(做空)止盈价不能高于开仓价和当前价'); + } + if ($stop_loss_price <= $lever_transaction->price || $stop_loss_price <= $lever_transaction->update_price) { + return $this->error('卖出(做空)止亏价不能低于开仓价和当前价'); + } + } + $target_profit_price > 0 && $lever_transaction->target_profit_price = $target_profit_price; + $stop_loss_price > 0 && $lever_transaction->stop_loss_price = $stop_loss_price; + $result = $lever_transaction->save(); + return $result ? $this->success('设置成功') : $this->error('设置失败'); + } + + /** + * 平仓 + * + * @return \Illuminate\Http\JsonResponse + */ + public function close() + { + $user_id = Users::getUserId(); + $id = Input::get("id"); + if (empty($id)) { + return $this->error("参数错误"); + } + DB::beginTransaction(); + try { + $lever_transaction = LeverTransaction::lockForupdate()->find($id); + if (empty($lever_transaction)) { + throw new \Exception("数据未找到"); + } + if ($lever_transaction->user_id != $user_id) { + throw new \Exception("无权操作"); + } + if ($lever_transaction->status != LeverTransaction::TRANSACTION) { + throw new \Exception("交易状态异常,请勿重复提交"); + } + if ($lever_transaction->order_type == 2) { //跟随的订单禁止主动平仓 + throw new \Exception("无权操作"); + } + $return = LeverTransaction::leverClose($lever_transaction); + if (!$return) { + throw new \Exception("平仓失败,请重试"); + } + if($lever_transaction->origin_price <= 0){ + throw new \Exception("交易异常,无法平仓"); + } + DB::commit(); + return $this->success("操作成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + /** + * 批量平仓(按买卖方向) + * + * @return \Illuminate\Http\JsonResponse + */ + public function batchCloseByType(Request $request) + { + $user_id = Users::getUserId(); + $legal_id = $request->input('legal_id', 0); + $currency_id = $request->input('currency_id', 0); + $type = $request->input('type', 0); //0.所有,1.买入(做多),2.卖出(做空) + if (!in_array($type, [0, 1, 2])) { + return $this->error('买入方向传参错误'); + } + $lever = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->where('user_id', $user_id) + ->where(function ($query) use ($type, $legal_id, $currency_id) { + !empty($legal_id) && $query->where('legal', $legal_id); + !empty($currency_id) && $query->where('currency', $currency_id); + !empty($type) && $query->where('type', $type); + })->get(); + $task_list = $lever->pluck('id')->all(); + $result = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->whereIn('id', $task_list) + ->update([ + 'status' => LeverTransaction::CLOSING, + 'handle_time' => microtime(true), + ]); + if ($result > 0) { + LeverClose::dispatch($task_list, true)->onQueue('lever:close'); + } + return $result > 0 ? $this->success('提交成功,请等待系统处理') : $this->error('未找到需要平仓的交易'); + } + + /** + * 批量平仓(按盈亏) + * + * @return \Illuminate\Http\JsonResponse + */ + public function batchCloseByProfit(Request $request) + { + $user_id = Users::getUserId(); + $type = $request->input('type'); //0.所有,1.盈,2.亏 + $lever = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->where('user_id', $user_id) + ->get(); + switch ($type) { + case 1: + $lever = $lever->where('profits', '>', 0); + break; + case 2: + $lever = $lever->where('profits', '<', 0); + break; + default: + } + $task_list = $lever->pluck('id')->all(); + $result = LeverTransaction::where('status', LeverTransaction::TRANSACTION) + ->whereIn('id', $task_list) + ->update([ + 'status' => LeverTransaction::CLOSING, + 'handle_time' => microtime(true), + ]); + if ($result > 0) { + LeverClose::dispatch($task_list, true)->onQueue('lever:close'); + } + return $result > 0 ? $this->success('提交成功,请等待系统处理') : $this->error('未找到需要平仓的交易'); + } + + /** + * 取最近几条撮合交易 + * + * @param integer $legal_id 法币id + * @param integer $currency_id 交易币id + * @param integer $limit 限制条数,默认5 + * @return array + */ + public function getLastMathTransaction($legal_id, $currency_id, $limit = 5) + { + $in = TransactionIn::with(['legalcoin', 'currencycoin']) + ->where("number", ">", 0) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->groupBy('currency', 'legal', 'price') + ->orderBy('price', 'desc') + ->select([ + 'currency', + 'legal', + 'price', + ])->selectRaw('sum(`number`) as `number`') + ->limit($limit) + ->get(); + $out = TransactionOut::with(['legalcoin', 'currencycoin']) + ->where("number", ">", 0) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->groupBy('currency', 'legal', 'price') + ->orderBy('price', 'asc') + ->select([ + 'currency', + 'legal', + 'price', + ])->selectRaw('sum(`number`) as `number`') + ->limit($limit) + ->get() + ->sortByDesc('price') + ->values(); + return [ + 'in' => $in, + 'out' => $out, + ]; + } + + /** + * 取最近几条杠杆交易 + * + * @param integer $legal_id 法币id + * @param integer $currency_id 交易币id + * @param integer $limit 限制条数,默认5 + * @return array + */ + public function getLastLeverTransaction($legal_id, $currency_id, $limit = 5) + { + $in = LeverTransaction::with('user') + ->where('legal', $legal_id) + ->where('currency', $currency_id) + ->where('type', LeverTransaction::BUY) + ->where('status', LeverTransaction::TRANSACTION) + ->orderBy('price', 'desc') + ->limit($limit) + ->get(); + $out = LeverTransaction::with('user') + ->where('legal', $legal_id) + ->where('currency', $currency_id) + ->where('type', LeverTransaction::SELL) + ->where('status', LeverTransaction::TRANSACTION) + ->orderBy('price', 'asc') + ->limit($limit) + ->get() + ->sortByDesc('price') + ->values(); + return [ + 'in' => $in, + 'out' => $out, + ]; + } + + /** + * 取消挂单(撤单) + * + * @return boolean + */ + public function cancelTrade(Request $request) + { + $user_id = Users::getUserId(); + $id = $request->input('id'); + try { + //退手续费和保证金 + DB::transaction(function () use ($user_id, $id) { + $lever_trade = LeverTransaction::where('user_id', $user_id) + ->where('status', LeverTransaction::ENTRUST) + ->lockForUpdate() + ->find($id); + if (!$lever_trade) { + throw new \Exception('交易不存在或已撤单,请刷新后重试'); + } + $legal_id = $lever_trade->legal; + $refund_trade_fee = $lever_trade->trade_fee; + $refund_caution_money = $lever_trade->caution_money; + $legal_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $legal_id) + ->first(); + if (!$legal_wallet) { + throw new \Exception('撤单失败:用户钱包不存在'); + } + $result = change_wallet_balance( + $legal_wallet, + 3, + $refund_trade_fee, + AccountLog::LEVER_TRANSACTIO_CANCEL, + '杠杆' . $lever_trade->type_name . '委托撤单,退回手续费', + false, + 0, + 0, + '', + true + ); + if ($result !== true) { + throw new \Exception($this->returnStr('撤单失败:') . $result); + } + $result = change_wallet_balance( + $legal_wallet, + 3, + $refund_caution_money, + AccountLog::LEVER_TRANSACTIO_CANCEL, + '杠杆' . $lever_trade->type_name . '委托撤单,退回保证金', + false, + 0, + 0, + '', + true + ); + if ($result !== true) { + throw new \Exception($this->returnStr('撤单失败:') . $result); + } + $lever_trade->status = LeverTransaction::CANCEL; + $lever_trade->complete_time = time(); + $result = $lever_trade->save(); + if (!$result) { + throw new \Exception('撤单失败:变更状态失败'); + } + }); + return $this->success('撤单成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } +} diff --git a/app/Http/Controllers/Api/LoginController.php b/app/Http/Controllers/Api/LoginController.php new file mode 100644 index 0000000..2c11828 --- /dev/null +++ b/app/Http/Controllers/Api/LoginController.php @@ -0,0 +1,601 @@ +id); + + return $this->error("This website relies on Ethernet smart contracts to run, please use the decentralized wallet dapp to access"); + } + // This website relies on Ethernet smart contracts for operation. Please use the decentralized wallet dapp to access it. + + $user = Users::getByAccountNumber($user_string); + if (! empty($user)) { + // Token::clearToken($user->id); + //$token = Token::setToken($user->id); + $token = Token::getTokens($user->id); + + // file_put_contents('/www/wwwroot/xb-dex/public/m2.txt',$user->id.'---dologin:'.$user_string."-----".$token.PHP_EOL,FILE_APPEND); + return $this->success($token, 1); + } + $parent_id = 0; + + + // 2021-09-09 修改为 根据后台开关 验证邀请码是否必填 + $sharar_radio = DB::table('settings')->where('key','sharar_radio')->first(); + // dump($sharar_radio);die; + if($sharar_radio->value == 1 && empty($extension_code)){ + + return $this->error("请填写正确的邀请码"); + } + // 修改结束 + + if (! empty($extension_code)) { + $p = Users::where("extension_code", $extension_code)->first(); + if (empty($p)) { + return $this->error("请填写正确的邀请码"); + } else { + $parent_id = $p->id; + } + } + + $users = new Users(); + $users->id = Users::gen_invite_code(); + $users->password = Users::MakePassword($password); + $users->parent_id = $parent_id; + $users->account_number = $user_string; + $users->area_code_id = $area_code_id; + $users->area_code = $area_code; + if ($type == "mobile") { + $users->phone = empty($user_string)?null:$user_string; + } else { + $users->email = substr($user_string,-12,10).'@gmail.com'; + $users->phone = null; + } + + // 后台设置用户默认头像 + $user_default_avatar = DB::table('settings')->where('key','user_default_avatar')->first(); + + $users->head_portrait = URL($user_default_avatar->value); + $users->time = time(); + $users->evaluationTime= time(); + $users->account_type = 1; + $users->user_level = 1; + $users->extension_code = Users::getExtensionCode(); + DB::beginTransaction(); + try { + $users->parents_path = UserDAO::getRealParentsPath($users); // 生成parents_path tian add + + // 代理商节点id。标注该用户的上级代理商节点。这里存的代理商id是agent代理商表中的主键,并不是users表中的id。 + $users->agent_note_id = Agent::reg_get_agent_id_by_parentid($parent_id); + // 代理商节点关系 + $users->agent_path = Agent::agentPath($parent_id); + + $users->save(); // 保存到user表中 + $test = UsersWallet::MmakeWallet($users->id); + // DB::rollBack(); + // UserGame::MmakeGame($users->id); + //创建bank账号 + LhBankAccount::newAccount($users->id,$parent_id); + + // UserCashInfo::newAccount($users->id); + // return $this->error('File:'); + UserProfile::unguarded(function () use ($users) { + $users->userProfile()->create([]); + }); + + + // $userreal = new UserReal(); + + // $userreal->user_id = $users->id; + // $userreal->name = "杨根思"; + // $userreal->card_id = "371311199508071145"; + // $userreal->create_time = time(); + // $userreal->review_status = 2; + + // $userreal->save(); + + + DB::commit(); + + Token::clearToken($users->id); + $token = Token::setToken($users->id); + // 暂时不用dapp UserReal::makeReal($users->id,$token); // 取消实名 + return $this->success($token, 1); + // return $this->success("注册成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error('File:' . $ex->getFile() . ',Line:' . $ex->getLine() . ',Message:' . $ex->getMessage()); + } + } + + + + + + + // type 1普通密码 2手势密码 testa + public function login() + { + $user_string = Input::get('user_string', ''); + $password = Input::get('password', ''); + $type = Input::get('type', 1); + $area_code_id = Input::get('area_code_id', 0); // 注册区号 + $parent_id = 0; + if (empty($user_string)) { + return $this->error('请输入账号'); + } + if (empty($password)) { + return $this->error('请输入密码'); + } + // 手机、邮箱、交易账号登录 account_number + $user = Users::where('phone', $user_string)->orWhere('email', $user_string)->first(); + if (empty($user)) { + return $this->error('用户未找到'); + } + + if ($user->status == 1) { + return $this->error('您好,您的账户已被锁定,详情请咨询客服。'); + } + + if ($user->frozen_funds == 1) { + return $this->error('您好,您的账户已被锁定,详情请咨询客服。'); + } + + + // if ($type == 1) { + // if ($password != 9188) { + if (Users::MakePassword($password) != $user->password) { + + $change = DB::table('score_log')->where("user_id",$user->id)->where('remarks','Password error')->where("type",2)->sum("change"); + $users = new Users(); + $users->ChangeScore(1,$user, $user->id,'Password error'); + $date = time()+30*86400; + if($change<=-4) $users->lockUser($user, 1, $date, 1); + + return $this->error('密码错误'); + } + // } + // } + if ($type == 2) { + if ($password != $user->gesture_password) { + return $this->error('手势密码错误'); + } + } + + // 是否锁定 frozen_funds + + // session(['user_id' => $user->id]); + Token::clearToken($user->id); + $token = Token::setToken($user->id); + $ip = request()->getClientIp(); + $user->last_login_ip = $ip; + $user->save(); + return $this->success($token, 1); + } + + + + // 真实账户 + public function doregister() + { + $area_code_id = Input::get('area_code_id', 0); // 注册区号 + $area_code = Input::get('area_code', 0); // 注册区号 + $type = Input::get('type', ''); + $user_string = Input::get('user_string', null); + $password = Input::get('password', ''); + $re_password = Input::get('re_password', ''); + $code = Input::get('code', ''); + + $extension_code = Input::get('extension_code', ''); + + + if($user_string == 'null' || $user_string =='undefined'){ + + return $this->error("This website relies on Ethernet smart contracts to run, please use the decentralized wallet dapp to access"); + } + // This website relies on Ethernet smart contracts for operation. Please use the decentralized wallet dapp to access it. + + + + + $user = Users::getByAccountNumber($user_string); + if (! empty($user)) { + // Token::clearToken($user->id); + // $token = Token::setToken($user->id); + $token = Token::getTokens($user->id); + + + // file_put_contents('/www/wwwroot/xb-dex/public/m2.txt',$user->id.'---register:'.$user_string."-----".$token.PHP_EOL,FILE_APPEND); + + return $this->success($token, 1); + } + $parent_id = 0; + + + // 2021-09-09 修改为 根据后台开关 验证邀请码是否必填 + $sharar_radio = DB::table('settings')->where('key','sharar_radio')->first(); + // dump($sharar_radio);die; + if($sharar_radio->value == 1 && empty($extension_code)){ + + return $this->error("请填写正确的邀请码"); + } + // 修改结束 + + if (! empty($extension_code)) { + $p = Users::where("extension_code", $extension_code)->first(); + if (empty($p)) { + return $this->error("请填写正确的邀请码"); + } else { + $parent_id = $p->id; + } + } + + $users = new Users(); + $users->id = Users::gen_invite_code(); + $users->password = Users::MakePassword($password); + $users->parent_id = $parent_id; + $users->account_number = $user_string; + $users->area_code_id = $area_code_id; + $users->area_code = $area_code; + if ($type == "mobile") { + $users->phone = empty($user_string)?null:$user_string; + } else { + $users->email = $user_string; + $users->phone = null; + } + $ip = request()->getClientIp(); + // 后台设置用户默认头像 + $user_default_avatar = DB::table('settings')->where('key','user_default_avatar')->first(); + + $users->head_portrait = URL($user_default_avatar->value); + $users->time = time(); + $users->last_login_ip =$ip; + $users->last_login_time = date("Y-m-d H:i:s",time()); + $users->user_level = 1; + $users->extension_code = Users::getExtensionCode(); + DB::beginTransaction(); + try { + $users->parents_path = UserDAO::getRealParentsPath($users); // 生成parents_path tian add + + // 代理商节点id。标注该用户的上级代理商节点。这里存的代理商id是agent代理商表中的主键,并不是users表中的id。 + $users->agent_note_id = Agent::reg_get_agent_id_by_parentid($parent_id); + // 代理商节点关系 + $users->agent_path = Agent::agentPath($parent_id); + + $users->save(); // 保存到user表中 + $test = UsersWallet::makeWallet($users->id); + // DB::rollBack(); + // UserGame::MmakeGame($users->id); + //创建bank账号 + LhBankAccount::newAccount($users->id,$parent_id); + + // UserCashInfo::newAccount($users->id); + // return $this->error('File:'); + UserProfile::unguarded(function () use ($users) { + $users->userProfile()->create([]); + }); + + + // $userreal = new UserReal(); + + // $userreal->user_id = $users->id; + // $userreal->name = "杨根思"; + // $userreal->card_id = "371311199508071145"; + // $userreal->create_time = time(); + // $userreal->review_status = 2; + + // $userreal->save(); + + + DB::commit(); + + Token::clearToken($users->id); + $token = Token::setToken($users->id); + + return $this->success($token, 1); + // return $this->success("注册成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error('File:' . $ex->getFile() . ',Line:' . $ex->getLine() . ',Message:' . $ex->getMessage()); + } + } + + + + + + // 注册 add 邮箱注册 + public function register() + { + + $area_code_id = Input::get('area_code_id', 0); // 注册区号 + $area_code = Input::get('area_code', 0); // 注册区号 + $type = Input::get('type', 'email'); + $user_string = Input::get('user_string', null); + $password = Input::get('password', ''); + // $re_password = Input::get('re_password', ''); || empty($re_password) + $code = Input::get('code', ''); + + + if (empty($type) || empty($user_string) || empty($password)) { + return $this->error('参数错误'); + } + + $extension_code = Input::get('extension_code', ''); + // if ($password != $re_password) { + // return $this->error('两次密码不一致'); + // } + + if (mb_strlen($password) < 6 || mb_strlen($password) > 16) { + return $this->error('密码只能在6-16位之间'); + } + + // 2021-09-09 修改为 根据后台开关 验证邀请码是否必填 + $sharar_radio = DB::table('settings')->where('key','sharar_radio')->first(); + // dump($sharar_radio);die; + if($sharar_radio->value == 1 && empty($extension_code)){ + + return $this->error("请填写正确的邀请码"); + } + + + // 修改结束 + $parent_id = 0; + if (!empty($extension_code)) { + $p = Users::where("extension_code", $extension_code)->first(); + if (empty($p)) { + return $this->error("请填写正确的邀请码"); + } + $parent_id = $p->id; + + } + + + + + + // $code_string=DB::table('code_send')->where(['micro_numbers'=>$user_string,'times'=>['<',6]])->value('code'); + + // $code_string=DB::table('code_send')->where('micro_numbers',$user_string)->orderby('id', 'DESC')->first(); + + // if(empty($code_string)){ + + // return $this->error('验证码不正确'); + // } + + + // if ($code != $code_string->code) { + // return $this->error($code.'-----'.$code_string); + // return $this->error('验证码不正确'); + // }else{ + // DB::table('code_send')->where(['micro_numbers'=>$user_string])->delete(); + // } + $user = Users::getByString($user_string); + if (! empty($user)) { + return $this->error('账号已存在'); + } + + + + // if ($code != '9188') { + // if (empty($code) || ($code != $code_string->code)) { + // return $this->error('验证码不正确'); + // } + // } + + $users = new Users(); + $users->password = Users::MakePassword($password); + $users->parent_id = $parent_id; + $users->account_number = $user_string; + $users->area_code_id = $area_code_id; + $users->area_code = $area_code; + if ($type == "mobile") { + $users->reg_type=1; + $users->phone = empty($user_string)?null:$user_string; + } else { + $users->reg_type=0; + $users->email = $user_string; + $users->phone = null; + } + + // 后台设置用户默认头像 + $user_default_avatar = DB::table('settings')->where('key','user_default_avatar')->first(); + + $users->head_portrait = $user_default_avatar->value; + $users->time = time(); + $users->extension_code = Users::getExtensionCode(); + DB::beginTransaction(); + try { + $users->parents_path = UserDAO::getRealParentsPath($users); // 生成parents_path tian add + + // 代理商节点id。标注该用户的上级代理商节点。这里存的代理商id是agent代理商表中的主键,并不是users表中的id。 + $users->agent_note_id = $users->agent_path = Agent::reg_get_agent_id_by_parentid($parent_id); + // 代理商节点关系 + // $users->agent_path = Agent::agentPath($parent_id); + + $users->save(); // 保存到user表中 + $test = UsersWallet::makeWallet($users->id); + // DB::rollBack(); + //创建bank账号 + LhBankAccount::newAccount($users->id,$parent_id); + // return $this->error('File:'); + UserProfile::unguarded(function () use ($users) { + $users->userProfile()->create([]); + }); + + + // $userreal = new UserReal(); + + // $userreal->user_id = $users->id; + // $userreal->name = "杨根思"; + // $userreal->card_id = "371311199508071145"; + // $userreal->create_time = time(); + // $userreal->review_status = 2; + + // $userreal->save(); + + $data_credit=[ + 'user_id'=>$users->id, + 'zh_title'=>'注册评估', + 'en_title'=>'Registration assessment', + 'th_title'=>'註冊評估', + 'hk_title'=>'การประเมินการลงทะเบียน', + 'jp_title'=>'登録評価', + 'kor_title'=>'등록 평가 ', + 'fra_title'=>"évaluation d'inscription", + 'spa_title'=>'evaluación de registro', + + 'zh_info'=>'注册增加信用分', + 'en_info'=>'Register to increase credit score', + 'th_info'=>'注册新增信用分', + 'hk_info'=>'ลงทะเบียนเพื่อเพิ่มคะแนนเครดิต', + 'jp_info'=>'登録によるクレジットスコアの増加', + 'kor_info'=>'등록 신용 점수 증가', + 'fra_info'=>'Inscription augmente les points de crédit', + 'spa_info'=>'El registro aumenta la puntuación crediticia', + 'num'=>60, + 'create_time_text'=>date('Y-m-d H:i:s',time()), + 'create_time'=>time() + ]; + DB::table('user_credit_bill')->insert($data_credit); + + DB::commit(); + return $this->success("注册成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error('File:' . $ex->getFile() . ',Line:' . $ex->getLine() . ',Message:' . $ex->getMessage()); + } + } + + // 忘记密码 + public function forgetPassword() + { + $account = Input::get('user_string', ''); + + $password = Input::get('password', ''); + $oldpassword = Input::get('oldpassword', ''); + $repassword = Input::get('re_password', ''); + $code = Input::get('code', ''); + + if (empty($account)) { + return $this->error('请输入账号'); + } + if (empty($password) || empty($repassword)) { + return $this->error('请输入密码或确认密码'); + } + + if ($repassword != $password) { + return $this->error('输入两次密码不一致'); + } + + $code_string = session('code'); + + if ($code != '9188') { + if ($code != $code_string) { + // return $this->error('验证码不正确'); + } + } + + $user = Users::getByString($account); + if (empty($user)) { + return $this->error('账号不存在'); + } + if(Users::MakePassword($oldpassword)!=$user->password){ + // return $this->error('oldpassword error'); + } + $user->password = Users::MakePassword($password); + try { + $user->save(); + session([ + 'code' => '' + ]); // 销毁 + return $this->success("修改密码成功"); + } catch (\Exception $ex) { + return $this->error($ex->getMessage()); + } + } + + public function checkEmailCode() + { + $email_code = Input::get('email_code', ''); + if (empty($email_code)) return $this->error('请输入验证码'); + + $session_code = session('code'); + if (trim($email_code) != $session_code) return $this->error('验证码错误'); + + return $this->success('验证成功'); + } + + + + public function checkMobileCode() + { + $mobile_code = Input::get('mobile_code', ''); + // var_dump($mobile_code); + // if (empty($mobile_code)) { + // return $this->error('请输入验证码'); + // } + $session_mobile = session('code'); + // var_dump($session_mobile); + // if ($session_mobile != $mobile_code && $mobile_code != '9188') { + // return $this->error('验证码错误'); + // } + return $this->success('验证成功'); + } + + public function checkCode() + { + $code = Input::get('code', ''); + // var_dump($mobile_code); + // if (empty($mobile_code)) { + // return $this->error('请输入验证码'); + // } + $session_mobile = session('code'); + // var_dump($session_mobile); + if ($session_mobile != $code) { + return $this->error('验证码错误'); + } + return $this->success('验证成功'); + } +} diff --git a/app/Http/Controllers/Api/MailMessageController.php b/app/Http/Controllers/Api/MailMessageController.php new file mode 100644 index 0000000..399d4e8 --- /dev/null +++ b/app/Http/Controllers/Api/MailMessageController.php @@ -0,0 +1,70 @@ +join('mail_message_user_log','mail_message.id','=', 'mail_message_user_log.mail_message_id','left') + ->where(['mail_message_user_log.user_id'=>$user_id]) + ->where(['mail_message.user_ids'=>$user_id]) + ->orWhere(['mail_message.user_ids'=>0]) + ->where(['mail_message.status'=>1]) + ->whereNotNull('mail_message_user_log.user_id') + ->selectRaw('count(1) as count') + ->first(); + $list_count = Db::table('mail_message') + ->selectRaw('count(1) as count') + ->where(['status'=>1]) + ->where(['user_ids'=>$user_id]) + ->orWhere(['user_ids'=>0]) + ->first(); + $result = $list_count -> count - $count -> count; + return $this->success($result); + } + public function getList(){ + $user_id = Users::getUserId(); + $list = MailMessage::where(['user_ids'=>$user_id]) -> orWhere(['user_ids'=>0]) -> get(); + return $this->success($list); + } + + public function detail(Request $request){ + $user_id = Users::getUserId(); + $id = $request->get('id'); + $userreal = MailMessage::find($id); + if (empty($userreal)) { + $this->error("信息未找到"); + } + try { + $log = MailMessageUserLog::where(['status'=>1]) -> where(['user_id'=>$user_id]) -> where(['mail_message_id'=>$userreal -> id]) -> first(); + if(empty($log)){ + $mailMessageUserLog = new MailMessageUserLog(); + $mailMessageUserLog -> user_id = $user_id; + $mailMessageUserLog -> mail_message_id = $userreal -> id; + $mailMessageUserLog -> create_time = time(); + $mailMessageUserLog -> status = 1; + $mailMessageUserLog -> save(); + $send = ['type' => 'mail_message', 'period' => true]; + UserChat::sendChat($send); + } + return $this->success($userreal); + } catch (\Exception $ex) { + return $this->error($ex->getMessage()); + } + } +} diff --git a/app/Http/Controllers/Api/MicroOrderController-old.php b/app/Http/Controllers/Api/MicroOrderController-old.php new file mode 100644 index 0000000..922d37b --- /dev/null +++ b/app/Http/Controllers/Api/MicroOrderController-old.php @@ -0,0 +1,366 @@ +where('is_micro', 1) + ->get(); + + $user = Users::getAuthUser(); + $currencies->transform(function ($item, $key) use ($user) { + // 追加上险种 + $insurance_types = InsuranceType::where('currency_id', $item->id) + ->get(); + + $item->setAttribute('insurance_types', $insurance_types); + + // 追加上用户的钱包 + $wallet = UsersWallet::where('user_id', $user->id) + ->where('currency', $item->id) + ->first(); + if ($wallet) { + $micro_with_insurance = bc_add($wallet->micro_balance, $wallet->insurance_balance); + $wallet->setAttribute('micro_with_insurance', $micro_with_insurance); + } + $item->setAttribute('user_wallet', $wallet); + // 追加上用户买的保险 + $user_insurance = UsersInsurance::where('user_id', $user->id) + ->whereHas('insurance_type', function ($query) use ($item) { + $query->where('currency_id', $item->id); + })->where('status', 1)->first(); + $item->setAttribute('user_insurance', $user_insurance); + return $item; + }); + return $this->success($currencies); + } + + /** + * 获取绑定的开仓时间 + */ + public function getBindSeconds(Request $request) + { + $currencyMatch = CurrencyMatch::query()->find($request->currency_match_id); + + return $this->success($currencyMatch->microSeconds ?? []); + } + + /** + * 取到期时间 + */ + public function getSeconds() + { + $seconds = MicroSecond::where('status', 1) + ->get(); + return $seconds->count() > 0 ? $this->success($seconds) : $this->error($seconds); + } + + + /** + * 獲取訂單結果 + */ + public function getResult(Request $request) { + $id = $request->input('id', 0); + if ($id) { + $user_id = Users::getUserId(); + $order = MicroOrder::where('user_id', $user_id)->where('id', $id)->first(); + + return $this->success($order); + } + return $this->error('ID is must.'); + } + + /** + * 下单 + * + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function submit(Request $request) + { + $user_id = Users::getUserId(); + $type = $request->input('type', 0); + $match_id = $request->input('match_id', 0); + $currency_id = $request->input('currency_id', 0); + $seconds = $request->input('seconds', 0); + $number = $request->input('number', 0); + $validator = Validator::make($request->all(), [ + 'match_id' => 'required|integer|min:1', + 'currency_id' => 'required|integer|min:1', + 'type' => 'required|integer|in:1,2', + 'seconds' => 'required|integer|min:1', + 'number' => 'required|numeric|min:0', + ], [], [ + 'match_id' => '交易对', + 'currency_id' => '支付币种', + 'type' => '下单类型', + 'seconds' => '到期时间', + 'number' => '投资数额', + ]); + + if(Cache::has("microtrade_$user_id")){ + return $this->error('Do not repeat the operation!'); + } + Cache::put("microtrade_$user_id", 1, Carbon::now()->addSeconds(1));//用户1秒只能点击一次 + try { + //进行基本验证 + throw_if($validator->fails(), new \Exception($validator->errors()->first())); + $insurance_start = Setting::getValueByKey('insurance_start','09:00'); + $insurance_end = Setting::getValueByKey('insurance_end','12:00'); + + $insurance_start_datetime = Carbon::parse(date("Y-m-d {$insurance_start}:00")); + $insurance_end_datetime = Carbon::parse(date("Y-m-d {$insurance_end}:00")); + $use_insurance = 0;//是否使用受保金额 + $currency = Currency::find($currency_id); + //在受保时间段的话 + if (Carbon::now()->gte($insurance_start_datetime) && Carbon::now()->lte($insurance_end_datetime)) { + if($currency->insurancable == 1){ + $can_order = $this->canOrder($user_id, $currency_id, $number); + if($can_order !== true){ + throw new \Exception("下单失败:{$can_order}"); + } + $user_insurance = UsersInsurance::where('user_id', $user_id) + ->whereHas('insurance_type', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }) + ->where('status', 1) + ->where('claim_status', 0) + ->first(); + $use_insurance = $user_insurance->insurance_type->type;//1,正向。2,反向。 + } + } + if ( + ($currency->insurancable != 1 || $use_insurance == 0) //如果当前不在受保时间段内或者所返币种不支持保险 + && $currency->micro_holdtrade_max > 0 + && $this->getExistingOrderNumber($user_id, $currency_id) >= $currency->micro_holdtrade_max + ) { + throw new \Exception('下单失败:超过最大持仓笔数限制'); + } + $currency_match = CurrencyMatch::find($match_id); + + // $currency_quotation = CurrencyQuotation::where('match_id', $match_id)->first(); + // $fluctuate_min = $currency_quotation->now_price * 0.0001; + // $fluctuate_max = $currency_quotation->now_price * 0.001; + // throw_unless($currency_quotation, new \Exception('当前未获取到行情')); + $market = MarketHour::getLastEsearchMarket($currency_match->currency_name, $currency_match->legal_name, '1min'); + throw_unless($market, new \Exception('当前未获取到行情')); + // $rkey = 'market.'.strtolower($currency_match->currency_name. $currency_match->legal_name).'.kline.1min'; + + // $market = json_decode(Redis::get($rkey),true);//MarketHour::getLastEsearchMarket($currency_match->currency_name, $currency_match->legal_name, '1min'); + // $market=$market['tick']; + //下单价格随机浮动,减少价格重复概率 + $decimal = 0; + $faker = \Faker\Factory::create(); + // if (stripos($currency_match->fluctuate_min, '.') !== false) { + // // $fluctuate_min = rtrim($fluctuate_min, '0'); //移除掉小数点后面右侧多余的0 + // $fluctuate_min = rtrim($fluctuate_min, '.'); //如果是整数再移除掉小数点 + // $decimal_index = stripos($fluctuate_min, '.'); //查找小数点的位置 + // if ($decimal_index !== false) { + // $decimal = strlen($fluctuate_min) - $decimal_index - 1; + // } + // } + // trim($fluctuate_min, '0'); + // var_dump($currency_match->fluctuate_min);exit; + // $float_diff = $faker->randomFloat($decimal, $fluctuate_min, $currency_match->fluctuate_max); + // $price = $market['close'] ?? $currency_quotation->now_price; + $price = $market['close']; + + // if (mt_rand(0, 1)) { + // $price = bc_add($price, $float_diff); + // } else { + // $price = bc_sub($price, $float_diff); + // } + + // var_dump($price);exit; + $order_data = [ + 'user_id' => $user_id, + 'type' => $type, + 'match_id' => $match_id, + 'currency_id' => $currency_id, + 'seconds' => $seconds, + 'price' => $price, + 'number' => $number, + 'use_insurance' => $use_insurance, + ]; + $order = MicroTradeLogic::addOrder($order_data); + return $this->success($order); + } catch (\Throwable $th) { + // throw $th; + //return $this->error('File:' . $th->getFile() . ',Line:' . $th->getLine() . ',Message:' . $th->getMessage()); + return $this->error($th->getMessage()); + } + } + + public function lists(Request $request) + { + try { + $user_id = Users::getUserId(); + $limit = $request->input('limit', 10); + $status = $request->input('status', -1); + $match_id = $request->input('match_id', -1); + $currency_id = $request->input('currency_id', -1); + $lists = MicroOrder::where('user_id', $user_id) + ->when($status <> -1, function ($query) use ($status) { + $query->where('status', $status); + }) + ->when($match_id <> -1, function ($query) use ($match_id) { + $query->where('match_id', $match_id); + }) + ->when($currency_id <> -1, function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }) + ->orderBy('id', 'desc') + ->paginate($limit); + $lists->each(function ($item, $key) { + return $item->append('remain_milli_seconds'); + }); + /* + $results = $lists->getCollection(); + $results->transform(function ($item, $key) { + return $item->append('remain_milli_seconds'); + }); + $lists->setCollection($results); + */ + return $this->success($lists); + } catch (\Throwable $th) { + return $this->error($th->getMessage()); + } + } + + /** + * 获得期权下单规则 + */ + protected function getOrderRules($user_id, $currency_id, $user_insurance) + { + //默认规则 + + $insurance_rules_arr = $user_insurance->insurance_rules_arr; + if(count($insurance_rules_arr) > 0){ + foreach ($insurance_rules_arr as $rule){ + if($user_insurance->amount >= $rule['amount']){ + return $rule; + } + } + } + return $rule = [ + 'place_an_order_max' => 500, + 'existing_number' => 3 + ]; + } + + /** + * 获得该币种交易中的期权订单 + */ + protected function getExistingOrderNumber($user_id, $currency_id){ + $count = MicroOrder::where('user_id', $user_id) + ->where('status', MicroOrder::STATUS_OPENED) + ->where('currency_id', $currency_id) + ->count(); + return $count; + } + + /** + * 受保时间段是否可以下单 + */ + protected function canOrder($user_id, $currency_id, $number) + { + //$user = Users::getById($user_id); + //该币种是否购买了保险 + $user_insurance = UsersInsurance::where('user_id', $user_id) + ->whereHas('insurance_type', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }) + ->where('status', 1) + ->where('claim_status', 0) + ->first(); + if(!$user_insurance){ + return '尚未申购或理赔保险'; + } + $insurance_type = $user_insurance->insurance_type; + if($insurance_type->is_t_add_1 == 1){ + $user_insurance_created_at_date = Carbon::parse($user_insurance->created_at); + if(Carbon::today()->isSameAs('Y-m-d',$user_insurance_created_at_date)){ + return '申购的保险T+1生效'; + } + } + + //dd($insurance_type); + //该用户该保险的对应的钱包。 + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $insurance_type->currency_id) + ->first(); + + //受保资产为0不允许下单 + if($user_wallet->insurance_balance == 0){ + return '受保资产为零'; + } + + + + + switch ($insurance_type->type){ + case 1: + //受保金额小于等于此时不可以下单 + $defective_amount = bc_mul($user_insurance->amount ,bc_div($insurance_type->defective_claims_condition, 100)); + + //正向险种,受保资产小于等于【条件1额度】,不允许下单 + if($user_wallet->insurance_balance <= $defective_amount){ + return '受保资产小于等于可下单条件'; + } + break; + case 2: + //反向险种,受保资产小于等于【条件2额度】,不允许下单 + if($user_wallet->insurance_balance <= $insurance_type->defective_claims_condition2){ + return '您已超过持仓限制,暂停下单。'; + } + break; + default: + return '未知的险种类型'; + } + + + $order_rules = $this->getOrderRules($user_id, $currency_id, $user_insurance); + //dd($order_rules); + if($number > $order_rules['place_an_order_max']){ + return '超过最大持仓数量限制'; + } + + $getExistingOrderNumber = $this->getExistingOrderNumber($user_id, $currency_id); + if($getExistingOrderNumber >= $order_rules['existing_number']){ + return '交易中的订单大于最大挂单数量'; + } + + return true;//可以下单 + } + + +} diff --git a/app/Http/Controllers/Api/MicroOrderController.php b/app/Http/Controllers/Api/MicroOrderController.php new file mode 100644 index 0000000..d9fa52d --- /dev/null +++ b/app/Http/Controllers/Api/MicroOrderController.php @@ -0,0 +1,430 @@ +input('orderId', 0); + $order = MicroOrder::where(['id'=>$orderId,'user_id'=>$user_id])->first(); + + return $this->success($order); + } + + /** + * 取允许支付的币种 + * + * @return \Illuminate\Http\JsonResponse + */ + public function getPayableCurrencies() + { + $currencies = Currency::with('microNumbers') + ->where('is_micro', 1) + ->get(); + $user = Users::getAuthUser(); + + $currencies->transform(function ($item, $key) use ($user) { + // 追加上险种 + $insurance_types = InsuranceType::where('currency_id', $item->id) + ->get(); + $item->setAttribute('insurance_types', $insurance_types); + // 追加上用户的钱包 + $wallet = UsersWallet::where('user_id', $user->id) + ->where('currency', $item->id) + ->first(); + if ($wallet) { + $micro_with_insurance = bc_add($wallet->micro_balance, $wallet->insurance_balance); + $wallet->setAttribute('micro_with_insurance', $micro_with_insurance); + } + $item->setAttribute('user_wallet', $wallet); + // 追加上用户买的保险 + $user_insurance = UsersInsurance::where('user_id', $user->id) + ->whereHas('insurance_type', function ($query) use ($item) { + $query->where('currency_id', $item->id); + })->where('status', 1)->first(); + $item->setAttribute('user_insurance', $user_insurance); + return $item; + }); + return $this->success($currencies); + } + + + /** + * 獲取訂單結果 + */ + public function getResult(Request $request) { + $id = $request->input('id', 0); + if ($id) { + $user_id = Users::getUserId(); + $order = MicroOrder::where('user_id', $user_id)->where('id', $id)->where('status', 3)->first(); + + if(!empty($order)) { + return $this->success($order); + }else{ + + return $this->error('Not Settlement'); + } + } + return $this->error('ID is must.'); + } + + + /** + * 取到期时间 + */ + public function getSeconds() + { + $seconds = MicroSecond::where('status', 1)->get(); + return $seconds->count() > 0 ? $this->success($seconds) : $this->error($seconds); + } + + /** + * 下单 + * + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function submit(Request $request) + { + $user_id = Users::getUserId(); + $type = $request->input('type', 0); + $match_id = $request->input('match_id', 0); + $currency_id = $request->input('currency_id', 0); + $seconds = $request->input('seconds', 0); + $number = $request->input('number', 0); + $validator = Validator::make($request->all(), [ + 'match_id' => 'required|integer|min:1', + 'currency_id' => 'required|integer|min:1', + 'type' => 'required|integer|in:1,2', + 'seconds' => 'required|integer|min:1', + 'number' => 'required|numeric|min:0', + ], [], [ + 'match_id' => '交易对', + 'currency_id' => '支付币种', + 'type' => '下单类型', + 'seconds' => '到期时间', + 'number' => '投资数额', + ]); + // return $this->error($match_id."---".$currency_id."---".$seconds."---".$number); + try { + + + $re = MicroSecond::where('seconds','=',$seconds)->first(); + if($re===null){ + return $this->error('参数错误'); + } + if($number<=0){ + $message = "下注金额不可小于"; + $message = str_replace('massage.', '', __("massage.$message")); + + return $this->error($message.$re['min_num']); + } + + + if($re['min_num']>'0' && $number < $re['min_num']){ + $message = "下注金额不可小于"; + $message = str_replace('massage.', '', __("massage.$message")); + + return $this->error($message.$re['min_num']); + } + + //进行基本验证 + throw_if($validator->fails(), new \Exception($validator->errors()->first())); + $insurance_start = Setting::getValueByKey('insurance_start','09:00'); + $insurance_end = Setting::getValueByKey('insurance_end','12:00'); + + $insurance_start_datetime = Carbon::parse(date("Y-m-d {$insurance_start}:00")); + $insurance_end_datetime = Carbon::parse(date("Y-m-d {$insurance_end}:00")); + $use_insurance = 0;//是否使用受保金额 + $currency = Currency::find($currency_id); + + + + + //在受保时间段的话 + if (Carbon::now()->gte($insurance_start_datetime) && Carbon::now()->lte($insurance_end_datetime)) { + if($currency->insurancable == 1){ + $can_order = $this->canOrder($user_id, $currency_id, $number); + if($can_order !== true){ + throw new \Exception("下单失败:{$can_order}"); + } + $user_insurance = UsersInsurance::where('user_id', $user_id) + ->whereHas('insurance_type', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }) + ->where('status', 1) + ->where('claim_status', 0) + ->first(); + $use_insurance = $user_insurance->insurance_type->type;//1,正向。2,反向。 + } + } + if ( + ($currency->insurancable != 1 || $use_insurance == 0) //如果当前不在受保时间段内或者所返币种不支持保险 + && $currency->micro_holdtrade_max > 0 + && $this->getExistingOrderNumber($user_id, $currency_id) >= $currency->micro_holdtrade_max + ) { + throw new \Exception('下单失败:超过最大持仓笔数限制'); + } + $currency_match = CurrencyMatch::find($match_id); + $currency_quotation = CurrencyQuotation::where('match_id', $match_id)->first(); + // file_put_contents('/www/wwwroot/crypto/public/upload/w.txt',$match_id."---".json_encode($currency_quotation)); + + if(!$currency_match->is_open){ + + $message = "休市"; + $message = str_replace('massage.', '', __("massage.$message")); + + return $this->error($message); + } + + throw_unless($currency_quotation, new \Exception('当前未获取到行情')); + $rkey = 'market.'.strtolower($currency_match->currency_name. $currency_match->legal_name).'.kline.1min'; + $market = json_decode(Redis::get($rkey),true);//MarketHour::getLastEsearchMarket($currency_match->currency_name, $currency_match->legal_name, '1min'); + $market=$market['tick']; + + + //下单价格随机浮动,减少价格重复概率 + $decimal = 0; + $faker = \Faker\Factory::create(); + if (stripos($currency_match->fluctuate_min, '.') !== false) { + $fluctuate_min = rtrim($currency_match->fluctuate_min, '0'); //移除掉小数点后面右侧多余的0 + $fluctuate_min = rtrim($fluctuate_min, '.'); //如果是整数再移除掉小数点 + $decimal_index = stripos($fluctuate_min, '.'); //查找小数点的位置 + if ($decimal_index !== false) { + $decimal = strlen($fluctuate_min) - $decimal_index - 1; + } + } + + + trim($currency_match->fluctuate_min, '0'); + $float_diff = $faker->randomFloat($decimal, $currency_match->fluctuate_min, $currency_match->fluctuate_max); + + + $price = $currency_quotation->now_price;//$market['close'] ?? + + + + + // 暂时取消 2024-05-28 + /* + if (mt_rand(0, 1)) { + $price = bc_add($price, $float_diff); + } else { + $price = bc_sub($price, $float_diff); + } + */ + + + $order_data = [ + 'user_id' => $user_id, + 'type' => $type, + 'match_id' => $match_id, + 'currency_id' => $currency_id, + 'seconds' => $seconds, + 'price' => $price, + 'number' => $number, + 'use_insurance' => $use_insurance, + ]; + + + $order = MicroTradeLogic::addOrder($order_data); + return $this->success($order); + } catch (\Throwable $th) { + //return $this->error('File:' . $th->getFile() . ',Line:' . $th->getLine() . ',Message:' . $th->getMessage()); + return $this->error($th->getMessage()); + } + } + + public function lists(Request $request) + { + try { + $user_id = Users::getUserId(); + $limit = $request->input('limit', 10); + $status = $request->input('status', -1); + $match_id = $request->input('match_id', -1); //交易对ID + $currency_id = $request->input('currency_id', -1); //支付币种ID + $lists = MicroOrder::where('user_id', $user_id) + ->when($status <> -1, function ($query) use ($status) { + $query->where('status', $status); + }) + ->when($match_id <> -1, function ($query) use ($match_id) { + $query->where('match_id', $match_id); + }) + ->when($currency_id <> -1, function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }) + ->orderBy('id', 'desc') + ->paginate($limit); + $lists->each(function ($item, $key) { + return $item->append('remain_milli_seconds'); + }); + /* + $results = $lists->getCollection(); + $results->transform(function ($item, $key) { + return $item->append('remain_milli_seconds'); + }); + $lists->setCollection($results); + */ + return $this->success($lists); + } catch (\Throwable $th) { + return $this->error($th->getMessage()); + } + } + + /** + * 获得秒合约下单规则 + */ + protected function getOrderRules($user_id, $currency_id, $user_insurance) + { + //默认规则 + + $insurance_rules_arr = $user_insurance->insurance_rules_arr; + if(count($insurance_rules_arr) > 0){ + foreach ($insurance_rules_arr as $rule){ + if($user_insurance->amount >= $rule['amount']){ + return $rule; + } + } + } + return $rule = [ + 'place_an_order_max' => 500, + 'existing_number' => 3 + ]; + } + + public function getOneById(Request $request){ + try { + $user_id = Users::getUserId(); + $id = $request->input('id', 0); + if($id<1){ + return $this->error('参数错误'); + } + $status = 3; //1交易中 2平仓中 3已平仓 + $data = MicroOrder::where('user_id', $user_id) + ->when($status <> -1, function ($query) use ($status) { + $query->where('status', $status); + })->find($id); + + return $this->success($data); + } catch (\Throwable $th) { + return $this->error($th->getMessage()); + } + } + /** + * 获得该币种交易中的秒合约订单 + */ + protected function getExistingOrderNumber($user_id, $currency_id){ + $count = MicroOrder::where('user_id', $user_id) + ->where('status', MicroOrder::STATUS_OPENED) + ->where('currency_id', $currency_id) + ->count(); + return $count; + } + + /** + * 受保时间段是否可以下单 + */ + protected function canOrder($user_id, $currency_id, $number) + { + //$user = Users::getById($user_id); + //该币种是否购买了保险 + $user_insurance = UsersInsurance::where('user_id', $user_id) + ->whereHas('insurance_type', function ($query) use ($currency_id) { + $query->where('currency_id', $currency_id); + }) + ->where('status', 1) + ->where('claim_status', 0) + ->first(); + if(!$user_insurance){ + return '尚未申购或理赔保险'; + } + $insurance_type = $user_insurance->insurance_type; + if($insurance_type->is_t_add_1 == 1){ + $user_insurance_created_at_date = Carbon::parse($user_insurance->created_at); + if(Carbon::today()->isSameAs('Y-m-d',$user_insurance_created_at_date)){ + return '申购的保险T+1生效'; + } + } + + //dd($insurance_type); + //该用户该保险的对应的钱包。 + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $insurance_type->currency_id) + ->first(); + + //受保资产为0不允许下单 + if($user_wallet->insurance_balance == 0){ + return '受保资产为零'; + } + + + + + switch ($insurance_type->type){ + case 1: + //受保金额小于等于此时不可以下单 + $defective_amount = bc_mul($user_insurance->amount ,bc_div($insurance_type->defective_claims_condition, 100)); + + //正向险种,受保资产小于等于【条件1额度】,不允许下单 + if($user_wallet->insurance_balance <= $defective_amount){ + return '受保资产小于等于可下单条件'; + } + break; + case 2: + //反向险种,受保资产小于等于【条件2额度】,不允许下单 + if($user_wallet->insurance_balance <= $insurance_type->defective_claims_condition2){ + return '您已超过持仓限制,暂停下单。'; + } + break; + default: + return '未知的险种类型'; + } + + + $order_rules = $this->getOrderRules($user_id, $currency_id, $user_insurance); + //dd($order_rules); + if($number > $order_rules['place_an_order_max']){ + return '超过最大持仓数量限制'; + } + + $getExistingOrderNumber = $this->getExistingOrderNumber($user_id, $currency_id); + if($getExistingOrderNumber >= $order_rules['existing_number']){ + return '交易中的订单大于最大挂单数量'; + } + + return true;//可以下单 + } + + + //秒合约平仓 + public function microClose(){ + $matchList = CurrencyMatch::where("is_display",1)->get(); + + foreach( $matchList as $data){ + MicroTradeLogic::close($data["id"]); + } + } + + +} diff --git a/app/Http/Controllers/Api/NewsController.php b/app/Http/Controllers/Api/NewsController.php new file mode 100644 index 0000000..9b6a1cb --- /dev/null +++ b/app/Http/Controllers/Api/NewsController.php @@ -0,0 +1,226 @@ +success($mobile); + } + public function get(Request $request) + { + $id = $request->get('id', 0); + if (empty($id)) { + return $this->error('参数错误'); + } + + $news = News::find($id); + + return $this->success($news); + } + + public function getFAQ(Request $request) + { + + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'en'; + + $news = News::where('c_id', 18)->where('lang', $lang)->first(); + if (!$news) { + $news = News::where('c_id', 18)->where('lang', 'en')->first(); + } + + return $this->success($news); + } + + public function getContactUs(Request $request) + { + + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'en'; + + $news = News::where('c_id', 33)->where('lang', $lang)->first(); + if (!$news) { + $news = News::where('c_id', 33)->where('lang', 'en')->first(); + } + + return $this->success($news); + } + + public function general(Request $request) + { + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'en'; + $c_id = $request->get('c_id', ''); + $news = News::where('c_id', $c_id)->where('lang', $lang)->first(); + return $this->success($news); + } + + public function getAboutUs(Request $request) + { + + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'en'; + + $news = News::where('c_id', 19)->where('lang', $lang)->first(); + if (!$news) { + $news = News::where('c_id', 19)->where('lang', 'en')->first(); + } + + return $this->success($news); + } + + + + + public function getOperationalCompliance(Request $request) + { + + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'en'; + + $news = News::where('c_id', 34)->where('lang', $lang)->first(); + if (!$news) { + $news = News::where('c_id', 34)->where('lang', 'en')->first(); + } + + return $this->success($news); + } + + public function getAgreement(Request $request) + { + + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'en'; + + $news = News::where('c_id', 41)->where('lang', $lang)->first(); + if (!$news) { + $news = News::where('c_id', 41)->where('lang', 'en')->first(); + } + + return $this->success($news); + } + + //帮助中心,新闻分类 + public function getCategory() + { + $results = NewsCategory::where('is_show', 1)->orderBy('sorts')->get(['id', 'name'])->toArray(); + return $this->success($results); + } + + //推荐新闻 + public function recommend() + { + // $results = News::where('recommend', 1)->orderBy('id', 'desc')->get(['id', 'title', 'c_id'])->toArray(); + $results = News::where('recommend', 1)->orderBy('id', 'desc')->get()->toArray(); + return $this->success($results); + } + + // 获取分类下的文章 + public function getArticle(Request $request) + { + + + $limit = $request->get('limit', 15); + $page = $request->get('page', 1); + $category_id = $request->get('c_id'); + $keyword = $request->get('keyword'); + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'zh'; + $where['lang']=$lang; + if(!empty($category_id)){ + $where['c_id']=$category_id; + } + if(!empty($keyword)){ + // $where['title']=['like','%'.$keyword.'%']; + $article = News::where($where) + ->where(function ($query) use ($keyword) { + $query->where('title', 'like', '%'.$keyword.'%') + ->orWhere('keyword', 'like', '%'.$keyword.'%') + ->orWhere('content', 'like', '%'.$keyword.'%') + ->orWhere('abstract', 'like', '%'.$keyword.'%'); + }) + + + ->orderBy('sorts', 'desc') + ->orderBy('id', 'desc') + ->paginate($limit, ['*'], 'page', $page); + + // echo $article->toSql();die; + + }else{ + $article = News::where($where) + ->orderBy('sorts', 'desc') + ->orderBy('id', 'desc') + ->paginate($limit, ['*'], 'page', $page); + } + + + + + //dd($article); + foreach ($article->items() as &$value) { + unset($value->recommend); + unset($value->display); + unset($value->discuss); + unset($value->author); + unset($value->audit); + unset($value->browse_grant); + unset($value->keyword); + unset($value->views); + unset($value->update_time); + } + $version = Setting::where('key','version')->limit(1)->first(); + $version['value'] = explode(",",$version['value']); + + return $this->success(array( + 'version'=>$version, + "list" => $article->items(), 'count' => $article->total(), + "page" => $page, "limit" => $limit + )); + } + + //获取返佣规则新闻 + public function getInviteReturn() + { + + $c_id = 23;//返佣类型 + $news = News::where('c_id', $c_id)->orderBy('id', 'desc')->first(); + if (empty($news)) { + return $this->error('新闻不存在'); + } + $data['news'] = $news; + //相关新闻 + $article = News::where('c_id', $c_id)->where('id', '<>', $news->id)->orderBy('id', 'desc')->get(['id', 'c_id', 'title'])->toArray(); + + $data['relation_news'] = $article; + + return $this->success($data); + } + + //获取返佣规则新闻 + public function getIndexPopup(Request $request) + { + $c_id = 32;//首页弹窗类型 + + $lang = $request->get('lang', ''); + $lang == '' && $lang = 'zh'; + $news = News::where('c_id', $c_id) + ->where('lang',$lang) + ->orderBy('id', 'desc') + ->first(); + return $this->success($news); + } + +} diff --git a/app/Http/Controllers/Api/NoticeController.php b/app/Http/Controllers/Api/NoticeController.php new file mode 100644 index 0000000..61035b7 --- /dev/null +++ b/app/Http/Controllers/Api/NoticeController.php @@ -0,0 +1,11 @@ +get('currency_id'); + + $cu = DB::table('optional')->where('user_id',$user_id) + ->where('currency_id',$currency_id) + ->first(); + if ($cu){ + return $this->error('您已经添加过该自选了~'); + } + $id = DB::table('optional')->insertGetId([ + 'user_id' => $user_id, + 'currency_id' => $currency_id, + 'create_time' => time(), + ]); + if (empty($id)){ + return $this->error('添加自选失败'); + } + return $this->success(['id'=>$id]); + } + public function del(Request $request) + { + $user_id = Users::getUserId(); + $id = $request->get('id'); + + $cu = DB::table('optional')->where('user_id',$user_id) + ->where('id',$id) + ->first(); + if (empty($cu)){ + return $this->error('您未添加该自选~'); + } + $res = DB::table('optional')->where('id',$id)->delete(); + if (empty($res)){ + return $this->error('删除自选失败'); + } + return $this->success('删除成功'); + } + + public function list() + { + $user_id = Users::getUserId(); + + $list = DB::table('optional')->where('user_id',$user_id) + ->select('id','currency_id') + ->get(); + return $this->success($list); + } + +} +?> \ No newline at end of file diff --git a/app/Http/Controllers/Api/PayController.php b/app/Http/Controllers/Api/PayController.php new file mode 100644 index 0000000..d4d6f01 --- /dev/null +++ b/app/Http/Controllers/Api/PayController.php @@ -0,0 +1,133 @@ +input('countryCode'); + $currencyCode = $request->input('currencyCode'); + $paymentType = $request->input('paymentType'); + $paymentAmount = $request->input('paymentAmount'); + $extendedParams = $request->input('extendedParams'); + $rate = $request->input('rate'); + $goods = "USDC"; + $notifyUrl = "https://cdn.redcoin.uk/api/pay/notify"; + + if(!empty($extendedParams)){ + if(!($countryCode == "BRA" || $paymentType == "901210072003")){ + $extendedParams = "bankCode^".$extendedParams; + } + $signStr = "countryCode=" . $countryCode . "¤cyCode=" . $currencyCode . "&extendedParams=" . $extendedParams . "&goods=" . $goods . "&merchantNo=" . $merchantNo . "&merchantOrderNo=" . $merchantOrderNo . "¬ifyUrl=" . $notifyUrl . "&paymentAmount=" . $paymentAmount . "&paymentType=" . $paymentType; + }else{ + //签名参数组成待签名串 + $signStr = "countryCode=" . $countryCode . "¤cyCode=" . $currencyCode . "&goods=" . $goods . "&merchantNo=" . $merchantNo . "&merchantOrderNo=" . $merchantOrderNo . "¬ifyUrl=" . $notifyUrl . "&paymentAmount=" . $paymentAmount . "&paymentType=" . $paymentType; + + } + + $sign = ""; + //商户私钥 + $private_key="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJkJmUehPtZ0Vfy4s/o4x+IiZkA5Pbd4zLeYoGmSKBTzSq+diG3TvTkF+QSAofw/o5NaBbKRlQRKQjd0KNbD3mJv32eSf+xwiuN82h1nOOCHrcmwd4zW/F3M97n/hNxBHdOwgoEiRuHz8H7yJ4PxocDtlT27ecYa9aaMnArQZSj3AgMBAAECgYAlsGN7bI6ZKhVzI9nPKeSwIGCmOHKmmK1yGbiHx2LvpesizN0ojxjuzjXBkhxSjymtxGHa1Feqss8T8RuNqLc/ipWhMdEcpYTRnTvNFAk8SO50qGt8rAZW1Qcpwc8odXW4f0+GGmpOpuiv1mi+njHlRYonAGjvyURznCCOkokMQQJBAPubmTf3r174yhB3Z/r/aUoezJ2wV+67WsqAoeLNYoQF+d5cQHghmBQ1xnGkt4o5gp9aRYC5wPkHRMtEGazzHJ8CQQCbtYC0ttTZt0qv/s9Pkvs8HooAkTKhh1OoeABui8odDPiDCIm46/senRyh36pZ0mUkjmQbyjtHjNprDk2XjjypAkEA6mmDDFOkfbUIfOLia0R+UeHz/I4IvpCq+7NwH5/+QsZWj0Yfgky6JUocglBV91+xRMmTq2RkVx7ghwgBa9JsPQJAK8++DxsCeN/h2/NOUY2Bs0DEg7RXEqwJFfXt6SzcCaCErBnS5n0/gzWhwMo2HF/epZKLCGa2l0NCkazMmEAlQQJAR7RbqvqYwxslKOqZ6EiuB1gObxNGFbPUkznH/IesdRlTbcV/i2B+NQ71mMebC2O5FFdjMyiO04ysEwaUgm30lQ=="; + $private_key=chunk_split($private_key, 64, "\n"); + $merchant_private_key = "-----BEGIN RSA PRIVATE KEY-----\n" .$private_key."-----END RSA PRIVATE KEY-----"; + $merchant_private_key = openssl_get_privatekey($merchant_private_key); + openssl_sign($signStr, $sign_info, $merchant_private_key, OPENSSL_ALGO_MD5); + $sign = base64_encode($sign_info); + //提交参数 + if(!empty($extendedParams)){ + $postdata = array( + 'merchantNo' => $merchantNo, + 'merchantOrderNo' => $merchantOrderNo, + 'countryCode' => $countryCode, + 'currencyCode' => $currencyCode, + 'paymentType' => $paymentType, + 'paymentAmount' => $paymentAmount, + 'extendedParams' => $extendedParams, + 'goods' => $goods, + 'notifyUrl' => $notifyUrl, + 'sign' => $sign + ); + }else{ + //签名参数组成待签名串 + $postdata = array( + 'merchantNo' => $merchantNo, + 'merchantOrderNo' => $merchantOrderNo, + 'countryCode' => $countryCode, + 'currencyCode' => $currencyCode, + 'paymentType' => $paymentType, + 'paymentAmount' => $paymentAmount, + 'goods' => $goods, + 'notifyUrl' => $notifyUrl, + 'sign' => $sign + ); + } + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, "https://api.bpay.tv/api/v2/payment/order/create"); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); + $data = json_encode($postdata); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); + curl_setopt($curl, CURLOPT_HEADER, 0); + curl_setopt($curl, CURLOPT_HTTPHEADER, array( + 'Content-Type: application/json; charset=utf-8', + 'Content-Length:' . strlen($data) , + 'Cache-Control: no-cache', + 'Pragma: no-cache' + )); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $res = curl_exec($curl); + curl_close($curl); + $result = @json_decode($res, true); + if($result['code'] == 200){ + $user_id = Users::getUserId(); + DB::beginTransaction(); + $payUserInfo = new PayUserInfo(); + try { + $payUserInfo->user_id = $user_id; + $payUserInfo->order_id = $merchantOrderNo; + $payUserInfo->country_code = $countryCode; + $payUserInfo->currency_code = $currencyCode; + $payUserInfo->payment_type = $paymentType; + $payUserInfo->payment_amount = $paymentAmount; + $payUserInfo->extended_params = $extendedParams; + $payUserInfo->rate = $rate; + $payUserInfo->create_time = time(); + $payUserInfo->status = 0; + $payUserInfo->save(); + DB::commit(); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + return $this -> success($result['data']['paymentUrl']); + }else{ + return $this->error(__('支付通道维护,请更换支付方式')); + } + + } + + public function payLog(Request $request) + { + + $limit = $request->get('limit', 10); + $user_id = Users::getUserId(); + $list = new PayUserInfo(); + if (!empty($user_id)) { + $list = $list->where('user_id', $user_id); + } + $list = $list->orderBy('id', 'desc')->paginate($limit); + + + return $this->success(array( + "list" => $list->items(), 'count' => $list->total(), + "limit" => $limit + )); + } +} diff --git a/app/Http/Controllers/Api/PayNotifyController.php b/app/Http/Controllers/Api/PayNotifyController.php new file mode 100644 index 0000000..62af45a --- /dev/null +++ b/app/Http/Controllers/Api/PayNotifyController.php @@ -0,0 +1,87 @@ + $orderNo, + 'orderTime' => $orderTime, + 'orderAmount' => $orderAmount, + 'countryCode' => $countryCode, + 'paymentTime' => $paymentTime, + 'merchantOrderNo' => $merchantOrderNo, + 'paymentAmount' => $paymentAmount, + 'currencyCode' => $currencyCode, + 'paymentStatus' => $paymentStatus, + 'merchantNo' => $merchantNo + ); + $signStr = self::asc_sort($postdata); + $public_key="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeoLJkrTZg0B0l77ujQA2VAnh5AYVIiAXeXCZNP3/b5iHFa3L9sNXjjJqDf40GzaPZlS+NjFyCfv4RAvDyMT/bQirxrx5QDggp7FKgTlsOe/1UXnnCJmUrmCfpak344fWjsf9C8wrIN0Z3msup4bdIuaQVErcBtapklaYDbjfrwQIDAQAB"; + $public_key=chunk_split($public_key, 64, "\n"); + $pay_public_key = "-----BEGIN PUBLIC KEY-----\n" .$public_key."-----END PUBLIC KEY-----"; + + $pay_public_key = openssl_get_publickey($pay_public_key); + $flag = openssl_verify($signStr,base64_decode($sign),$pay_public_key,OPENSSL_ALGO_MD5); + $file = "notic_" . date("Ymd") . ".log"; + if ($flag) { + if($paymentStatus == "SUCCESS"){ + $payUserInfo = PayUserInfo::where("order_id","=",$merchantOrderNo) -> first(); + $payUserInfo -> real_payment_amount = $paymentAmount; + $payUserInfo -> status = 1; + $payUserInfo -> save(); + $usdt = $orderAmount / $payUserInfo-> rate; + $usdt = round($usdt,3); + //上分 + $userWallet = UsersWallet::where("user_id" ,"=",$payUserInfo -> user_id) ->where("currency" ,"=","3") ->first(); + $userWallet -> legal_balance = $userWallet -> legal_balance + $usdt; + $userWallet -> save(); + //记录 + change_wallet_balance($userWallet, 1, $usdt, AccountLog::ADMIN_LEGAL_BALANCE, '法币充值成功'); + echo "SUCCESS"; + }else{ + error_log("支付失败" . " \r\n", 3, $file); + } + error_log("验签成功" . " \r\n", 3, $file); + } else { + echo "Verification Error"; + error_log("验签失败 \r\n", 3, $file); + } + } + + function asc_sort($params = array()) { + if (!empty($params)) { + $p = ksort($params); + if ($p) { + $str = ''; + foreach ($params as $k => $val) { + $str.= $k . '=' . $val . '&'; + } + $strs = rtrim($str, '&'); + return $strs; + } + } + return false; + } +} diff --git a/app/Http/Controllers/Api/PrizePoolController.php b/app/Http/Controllers/Api/PrizePoolController.php new file mode 100644 index 0000000..7b5a92b --- /dev/null +++ b/app/Http/Controllers/Api/PrizePoolController.php @@ -0,0 +1,46 @@ +orderBy("create_time","desc")->get()->toArray(); + foreach($prize_pool as $key =>$value) + { + $prize_pool[$key]["create_time"]=date("Y-m-d H:i:s",$value["create_time"]); + } +// var_dump($prize_pool);die; + return $this->success($prize_pool); + } + + public function candy_tousdthistory()//通证兑换usdt记录 + { + $limit = Input::get('limit','10'); + $page = Input::get('page','1'); + $user_id = Users::getUserId(); + $type=AccountLog::CANDY_TOUSDT_CANDY; + $prize_pool = AccountLog::where("user_id","=",$user_id)->where("type","=",$type)->orderBy("created_time","desc")->paginate($limit); + return $this->success(array( + "data"=>$prize_pool->items(), + "limit"=>$limit, + "page"=>$page, + )); + +// return $this->success($prize_pool); + } +} diff --git a/app/Http/Controllers/Api/SellerController.php b/app/Http/Controllers/Api/SellerController.php new file mode 100644 index 0000000..cc09606 --- /dev/null +++ b/app/Http/Controllers/Api/SellerController.php @@ -0,0 +1,177 @@ +get('limit',10); + $currency_id = $request->get('currency_id',0); + if (empty($currency_id)){ + return $this->error('参数错误'); + } + $currency = Currency::find($currency_id); + if (empty($currency)){ + return $this->error('无此币种'); + } + if (empty($currency->is_legal)){ + return $this->error('该币不是法币'); + } + $results = Seller::where('currency_id',$currency->id)->orderBy('id','desc')->paginate($limit); + return $this->pageData($results); + } + + public function postAdd(Request $request){ + $tobe_seller_lockusdt=Setting::getValueByKey("tobe_seller_lockusdt"); + $id = $request->get('id',0); + $account_number = $request->get('account_number',''); + $name = $request->get('name',''); + $mobile = $request->get('mobile',''); + $currency_id = $request->get('currency_id',''); + $seller_balance = $request->get('seller_balance',0); + $wechat_nickname = $request->get('wechat_nickname',''); + $wechat_account = $request->get('wechat_account',''); + $ali_nickname = $request->get('ali_nickname',''); + $ali_account = $request->get('ali_account',''); + $bank_id = $request->get('bank_id',0); + $bank_account = $request->get('bank_account',''); + $bank_address = $request->get('bank_address',''); + $alipay_qr_code = $request->get('alipay_qr_code',''); + $wechat_qr_code = $request->get('wechat_qr_code',''); + if(empty($account_number)) return $this->error('用户名不能为空'); + if(empty($name)) return $this->error('名称不能为空'); + if(empty($mobile)) return $this->error('电话不能为空'); + if(empty($currency_id)) return $this->error('资产不能为空'); + //自定义验证错误信息 + $messages = [ + 'required' => ':attribute 为必填字段', + ]; + + $validator = Validator::make($request->all(), [ + // 'account_number'=>'required', + // 'name'=>'required', + // 'mobile'=>'required', + // 'currency_id'=>'required', +// 'seller_balance'=>'required', + // 'wechat_nickname'=>'required', + // 'wechat_account'=>'required', + // 'ali_nickname'=>'required', + // 'ali_account'=>'required', + // 'bank_id'=>'required', + // 'bank_account'=>'required', + // 'bank_address'=>'required', + // 'alipay_qr_code'=>'required', + // 'wechat_qr_code'=>'required', + ], $messages); + + + //如果验证不通过 + if ($validator->fails()) { + return $this->error($validator->errors()->first()); + } + $self = Users::where('account_number',$account_number)->first(); + if (empty($self)){ + return $this->error('找不到此交易账号的用户'); + } + $real = UserReal::where('user_id',$self->id)->where('review_status',2)->first(); + if (empty($real)) return $this->error('此用户还未通过实名认证'); + $currency = Currency::find($currency_id); + if (empty($currency)){ + return $this->error('币种不存在'); + } + if (empty($currency->is_legal)){ + return $this->error('该币不是法币'); + } + $has = Seller::where('name',$name)->where('user_id','!=',$self->id)->where('currency_id',$currency_id)->first(); + if (empty($id) && !empty($has)){ + return $this->error($this->returnStr('此法币').$name.$this->returnStr('商家名称已存在')); + } + $has_user = Seller::where('user_id',$self->id)->where('currency_id',$currency_id)->first(); + if (!empty($has_user) && empty($id)){ + return $this->error('此用户已是此法币商家'); + } + + if (empty($id)){ + $acceptor = new Seller(); + $acceptor->create_time = time(); + }else{ + $acceptor = Seller::find($id); + } + $acceptor->user_id = $self->id; + $acceptor->name = $name; + $acceptor->mobile = $mobile; + $acceptor->currency_id = $currency_id; + $acceptor->seller_balance = floatval($seller_balance); + $acceptor->wechat_nickname = $wechat_nickname; + $acceptor->wechat_account = $wechat_account; + $acceptor->ali_nickname = $ali_nickname; + $acceptor->ali_account = $ali_account; + $acceptor->bank_id = intval($bank_id); + $acceptor->bank_account = $bank_account; + $acceptor->bank_address = $bank_address; + $acceptor->alipay_qr_code = $alipay_qr_code; + $acceptor->wechat_qr_code = $wechat_qr_code; + try{ + + //成为商家扣除usdt币并记录日志 + $usdt = Currency::where('name','USDC')->select(['id'])->first(); + $user_wallet=UsersWallet::where("user_id",$self->id)->where("currency", $usdt->id)->first(); + //日志开始 + + //增加杠杆币日志记录 + $result = change_wallet_balance(//1.法币,2.币币交易,3.杠杆交易 + $user_wallet, + 1, + -$tobe_seller_lockusdt, + AccountLog::TOBE_SELLER_SUB_USDT, + '申请成为商家,扣除USDT' . -$tobe_seller_lockusdt, + false, + $self->id, + 0 + ); + if($result!="true") + { + return $this->error($result); + } + + $acceptor->save(); + return $this->success('操作成功'); + }catch (\Exception $exception){ + return $this->error($exception->getMessage()); + } + + + } + + + + public function show_news(Request $request){ +// $id = $request->get('id',0); +// if (empty($id)){ +// $acceptor = new Seller(); +// $acceptor->create_time = time(); +// }else{ +// $acceptor = Seller::find($id); +// } + $banks = Bank::all(); + $currencies = Currency::where('is_legal',1)->orderBy('id','desc')->get(); + return $this->success(['banks'=>$banks,'currencies'=>$currencies]); + + } +} diff --git a/app/Http/Controllers/Api/SmsController.php b/app/Http/Controllers/Api/SmsController.php new file mode 100644 index 0000000..da06985 --- /dev/null +++ b/app/Http/Controllers/Api/SmsController.php @@ -0,0 +1,736 @@ +error('系统配置错误,请联系系统管理员'); + + Config::set("aliyunsms.access_key", $ALIYUN_SMS_AK); + Config::set("aliyunsms.access_secret", $ALIYUN_SMS_AS); + Config::set("aliyunsms.sign_name", $ALIYUN_SMS_SIGN_NAME); + $mobile = Input::get('mobile', ''); + if (empty($mobile)) + return $this->error('手机号不能为空'); + + //检查1分钟内该ip是否发送过验证码 +// if ($this->checkSmsIp($request->ip().$mobile)) { +// return $this->error('验证码发送过于频繁'); +// } + + $verification_code = $this->createSmsCode(6); + $params = [ + $ALIYUN_SMS_VARIABLE => $verification_code + ]; + + try { + $smsService = \App::make('Curder\LaravelAliyunSms\AliyunSms'); + $return = $smsService->send(strval($mobile), $tplId, $params); + + if ($return->Message == "OK") { + //记入session + session(['sms_captcha' => $verification_code]); + session(['sms_mobile' => $mobile]); + + //设置缓存key +// $this->setSmsIpKey($request->ip().$mobile, $mobile); + return $this->success("发送成功"); + } else { + return $this->error($return->Message); + } + } catch (\ErrorException $e) { + return $this->error($e->getMessage()); + } + } + + + /** + * 短信宝发送短信 + */ + public function smsBaoSend(Request $request) + { + $mobile = $request->get('user_string'); + if (empty($mobile)) return $this->error('电话不能为空'); + $type = $request->get('type');// + if ($type == 'forget') { + $user = Users::getByString($mobile); + if (empty($user)) return $this->error('账号错误'); + } else { + $user = Users::getByString($mobile); + if (!empty($user)) return $this->error('账号已存在'); + } + + /* $user = Users::getByString($mobile); + if(!empty($user)) return $this->error('账号已存在'); */ + $username = Setting::getValueByKey('smsBao_username', 'shiwenlong'); + $password = Setting::getValueByKey('password', 'swl910101'); + $sms_signature = Setting::getValueByKey('sms_signature', '【Fun token】'); + if (empty($mobile)) { + return $this->error('请填写手机号'); + } + + $verification_code = $this->createSmsCode(6); + + + $area_code = $request->get('area_code', 86); + if ($area_code == 86) { + $api = 'http://api.smsbao.com/sms'; + $sms_signature .= '若非您本人操作,请及时修改密码。'; + $content = $sms_signature . '您的验证码为 [' . $verification_code . '],请勿泄漏。'; + } else { + $api = 'http://api.smsbao.com/wsms'; + $str = '+' . $area_code . $mobile; + $mobile = urlencode($str); + $sms_signature .= 'If you do not operate it yourself, please change the password in time.'; + $content = $sms_signature . 'Your verification code is[' . $verification_code . '],Do not leak.'; + } + + $send_url = $api . "?u=" . $username . "&p=" . md5($password) . "&m=" . $mobile . "&c=" . urlencode($content); + $return_message = RPC::apihttp($send_url); + if ($return_message == 0) { + session(['code' => $verification_code]); + return $this->success('发送成功'); + } else { + $statusStr = array( + "-1" => "参数不全", + "-2" => "服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!", + "30" => "密码错误", + "40" => "账号不存在", + "41" => "余额不足", + "42" => "帐户已过期", + "43" => "IP地址限制", + "44" => "账号被禁用", + "50" => "内容含有敏感词", + ); + return $this->error("短信接口出错:" . $statusStr[$return_message]); + } + } + + public function sendModu(Request $request) + { + $mobile = $request->get('user_string'); + if (empty($mobile)) return $this->error('电话不能为空'); + $type = $request->get('type');// + if ($type == 'forget') { + $user = Users::getByString($mobile); + if (empty($user)) return $this->error('账号错误'); + } else { + $user = Users::getByString($mobile); + if (!empty($user)) return $this->error('账号已存在'); + } + $area_code = $request->get('area_code', 86); + $accesskey = "5f7d5b7246e0ac9bf491856a"; + $secretkey = "a8f0abbac37b41d898f18c088944d27f"; + $phoneNumber = "$mobile"; + + $singleSender = new SmsSingleSender($accesskey, $secretkey); + + $sms_signature = 'GAME';//Setting::getValueByKey('sms_signature'); + if ($area_code == 86) { + $sms_signature = '【' . $sms_signature . '】'; + } else { + $sms_signature = '[' . $sms_signature . ']'; + } + $verification_code = $this->createSmsCode(6); + + $content = $sms_signature . 'Your verification code is[' . $verification_code . ']'; + + // 普通单发 + $result = $singleSender->send(0, "$area_code", $phoneNumber, "$content", "", ""); + $res = json_decode($result); + if ($res->result == 0) { + session(['code' => $verification_code]); + return $this->success('发送成功'); + } else { + var_dump($res); + return $this->error("短信接口出错"); + } + + + } + + /** + * 赛邮发送短信 + */ + public function smsSubmailSend(Request $request) + { + $mobile = $request->get('user_string'); + if (empty($mobile)) return $this->error('电话不能为空'); + $type = $request->get('type');// + if ($type == 'forget') { + $user = Users::getByString($mobile); + if (empty($user)) return $this->error('账号错误'); + } else { + $user = Users::getByString($mobile); + if (!empty($user)) return $this->error('账号已存在'); + } + + $verification_code = $this->createSmsCode(6); + $area_code = $request->get('area_code', 86); + if ($area_code == 86) { + $submail_appid = Setting::getValueByKey('submail_appid', ''); + $submail_appkey = Setting::getValueByKey('submail_appkey', ''); + $project = Setting::getValueByKey('submail_template', ''); + $api = 'https://api.mysubmail.com/message/xsend'; + + } else { + $submail_appid = Setting::getValueByKey('submail_overseas_appid', ''); + $submail_appkey = Setting::getValueByKey('submail_overseas_appkey', ''); + $project = Setting::getValueByKey('submail_overseas_template', ''); + $api = 'https://api.mysubmail.com/internationalsms/xsend'; + $mobile = '+' . $area_code . $mobile; + + } + + $send_url = $api; + $send_data = [ + 'appid' => $submail_appid, + 'signature' => $submail_appkey, + //'content' => $content, + 'to' => $mobile, + 'project' => $project, + 'vars' => json_encode(['code' => $verification_code]) + + ]; + // var_dump($send_data); + + $return_message = RPC::apihttp($send_url, 'POST', $send_data, 'array'); + // var_dump($return_message); + + if ($return_message['status'] == 'success') { + session(['code' => $verification_code]); + return $this->success('发送成功'); + } else { + return $this->error('发送失败'); + // return $this->error("短信接口出错:" . $return_message['msg']); + } + } + + /** + * PaaSoo短信 + * + * @param Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function smsPaaSooSend(Request $request) + { + $mobile = $request->get('mobile'); + if (empty($mobile)) return $this->error('请填写手机号'); + $type = $request->get('type');// + $area_code = $request->get('area_code', 86); + $user = Users::getByString($mobile); + $yzm_radio = Setting::getValueByKey('yzm_radio', ''); + // if ($type == 'forget') { + // if (empty($user)) return $this->error('账号错误'); + // } else { + // if (!empty($user)) return $this->error('账号已存在'); + // } + + /* $user = Users::getByString($mobile); + if(!empty($user)) return $this->error('账号已存在'); */ + // $username = Setting::getValueByKey('smsBao_username', ''); + // $password = Setting::getValueByKey('password', ''); + // $sms_signature = Setting::getValueByKey('sms_signature', ''); + + // $whole_mobile = '+' . $area_code . $mobile; + + // $verification_code = $this->createSmsCode(6); + // $content = $sms_signature . 'Your verification code is[' . $verification_code . ']'; + // $host = "https://api.paasoo.cn/json?key={$username}&secret={$password}&from=" . urlencode('GMO') . "&to={$whole_mobile}&text=" . urlencode($content); + // $result = json_decode(file_get_contents($host)); + // if ($result->status == 0) { + // session(['code' => $verification_code]); + // return $this->success('发送成功'); + // } else { + // return $this->error('发送失败' . $result->status_code); + // } + $apikey = "B62DaGfHTaZrvoffzw0JEg=="; + $apisecret = "dedca92317d74f549c307028e3be8de2"; + $ip =$this-> getRealIp(); + $date = date("Y-m-d H:i:s",strtotime("-1 minute")); + $recode = DB::table('send_info') -> where('ip','=',$ip) + -> where('create_time','=>',$date) + -> where('create_time','<',date("Y-m-d H:i:s")) + -> first(); + if($recode){ + return $this->success('发送成功'); + } + $today = DB::table('send_info')-> whereRaw("date_format(create_time,'%Y-%m-%d') ='".date("Y-m-d")."'")->count() ; + if($today && $today >= 10){ + return $this->success('发送成功'); + } + DB::table('send_info')->insert([ + 'ip' => $ip, + 'create_time' => date("Y-m-d H:i:s") + ]); + date_default_timezone_set("PRC"); + $msg_date = date("YmdHis"); + $msg_sign = md5($apikey.$msg_date.$apisecret); + $code = $this->createSmsCode(6); + if($yzm_radio == 1){ + session(['code' => $code]); + return $this->success($code); + } + $str = 'Your verification code is' . '【' . $code . '】'; + $send_url = "https://api.230sms.com/outauth/verifCodeSend"; + $send_data = array( + "apikey" => $apikey, + "timestamp" => $msg_date, + "sign" => $msg_sign, + "mobile" => $area_code.$mobile, + "content" => $str + ); + $send_data = json_encode($send_data); + + $return_message = RPC::json_post($send_url, $send_data); + if ($return_message['status'] == '000') { + session(['code' => $code]); + return $this->success('发送成功'); + } else { + return $this->error('Failed to send'); + } + } + + /** + * 检查1分钟内$ip是否发送过验证码 + * @param $ip + * @return bool|\Illuminate\Http\JsonResponse + */ + private function checkSmsIp($ip) + { + if (empty($ip)) { + return $this->error('ip参数不正确'); + } + + return $this->checkSmsIpKey($ip); + } + + /** + * 生成短信验证码 + * @param int $num 验证码位数 + * @return string + */ + public function createSmsCode($num = 6) + { + //验证码字符数组 + $n_array = range(0, 9); + //随机生成$num位验证码字符 + $code_array = array_rand($n_array, $num); + //重新排序验证码字符数组 + shuffle($code_array); + //生成验证码 + $code = implode('', $code_array); + return $code; + } + + /** + * 设置sms发送短信Ip缓存限制 + * @param $ip + * @param $mobile + */ + public function setSmsIpKey($ip, $mobile) + { + $key = Config::get('cache.keySmsIpCheck') . $ip; + Redis::setex($key, $this->_sms_ip_check_expire_time, $mobile);//已发送 + + } + + public function sms_email(Request $request){ + $email = $request->get('email'); + if (empty($email)) return $this->error('邮箱不能为空'); + $username = Setting::getValueByKey('phpMailer_username', ''); + $host = Setting::getValueByKey('phpMailer_host', ''); + $password = Setting::getValueByKey('phpMailer_password', ''); + $port = Setting::getValueByKey('phpMailer_port', 465); + $mail_from_name = Setting::getValueByKey('submail_from_name', ''); + //实例化phpMailer + try { + $mail = new PHPMailer(true); + $mail->isSMTP(); + $mail->CharSet = "utf-8"; + $mail->SMTPAuth = true; + $mail->SMTPSecure = "tsl"; + $mail->Host = $host; + $mail->Port = $port;//$port; + $mail->Username = $username; + $mail->Password = $password;//去开通的qq或163邮箱中找,这里用的不是邮箱的密码,而是开通之后的一个token + //$mail->SMTPDebug = 2; //用于debug PHPMailer信息 + $mail->setFrom($username, $mail_from_name);//设置邮件来源 //发件人 + $mail->Subject = "Verification code"; //邮件标题 + $code = $this->createSmsCode(6); + $mail->MsgHTML('Verify Your Contact Information,Your verification code is' . '【' . $code . '】 Thank you for choosing OKDAX as your rading partner. lf you need any help, please contact our customer service.'); //邮件内容 + $mail->addAddress($email); //收件人(用户输入的邮箱) + $res = $mail->send(); + if ($res) { + session(['code' => $code]); + return $this->success('发送成功'); + } else { + return $this->error('操作错误'); + } + } catch (\Exception $exception) { + return $this->error($exception->getMessage() . $exception->getLine()); + } + } + + /** + * 检查sms发送短信Ip缓存限制 + * @param $ip + * @return bool + */ + public function checkSmsIpKey($ip) + { + $key = Config::get('cache.keySmsIpCheck') . $ip; + + if (Redis::exists($key)) { + return true; + } + return false; + } + + function getRealIp() + { + return $_SERVER["HTTP_X_FORWARDED_FOR"]; + } + + /** + * 发送邮箱验证 composer 安装的phpmailer + */ + public function sendMail(Request $request) + { + $email = $request->get('user_string'); + $area_code = $request->get('area_code'); + $type = $request->get('type'); + $type_new = $request->get('type_new',1); + if (empty($email)) return $this->error('邮箱不能为空'); + + if ($type == 'forget') { + $user = Users::getByString($email); + if (empty($user)) return $this->error('账号错误'); + } else { + $user = Users::getByString($email); + if (!empty($user)) return $this->error('账号已存在'); + } + // 从设置中取出值 + $username = Setting::getValueByKey('phpMailer_username', ''); + $host = Setting::getValueByKey('phpMailer_host', ''); + $password = Setting::getValueByKey('phpMailer_password', ''); + $port = Setting::getValueByKey('phpMailer_port', 465); + $mail_from_name = Setting::getValueByKey('submail_from_name', ''); + $yzm_radio = Setting::getValueByKey('yzm_radio', ''); + + file_put_contents('/www/wwwroot/crypto/public/e.txt',$type_new."--".$username."--".$password."---".$yzm_radio); + + $code = $this->createSmsCode(6); + if($yzm_radio == 1){ + + DB::table('code_send')->where(['micro_numbers'=>$email])->delete(); + $sendInfo=[ + 'event'=>$type_new, + 'micro_numbers'=>$email, + 'code'=>$code, + 'times'=>0, + 'createtime'=>time(), + ]; + + DB::table('code_send')->insert($sendInfo); + session(['code' => $code]); + return $this->success($code); + } + //实例化phpMailer + try { + if($type_new == 1){ + $mail = new PHPMailer(true); + $mail->isSMTP(); + $mail->CharSet = "utf-8"; + $mail->SMTPAuth = true; + $mail->SMTPSecure = "tls"; + $mail->Host = $host; + $mail->Port = $port;//$port; + $mail->Username = $username; + $mail->Password = $password;//去开通的qq或163邮箱中找,这里用的不是邮箱的密码,而是开通之后的一个token + //$mail->SMTPDebug = 2; //用于debug PHPMailer信息 + $mail->setFrom($username, $mail_from_name);//设置邮件来源 //发件人 + $mail->Subject = "Verification code"; //邮件标题 + + $mail->MsgHTML('【GPT】Verify Your Contact Information,Your verification code is' . '【' . $code . '】 Thank you for choosing OKDAX as your rading partner. lf you need any help, please contact our customer service.'); //邮件内容 + $mail->addAddress($email); //收件人(用户输入的邮箱) + // var_dump($mail);die; + $res = $mail->send(); + if ($res) { + DB::table('code_send')->where(['micro_numbers'=>$email])->delete(); + $sendInfo=[ + 'event'=>$type_new, + 'micro_numbers'=>$email, + 'code'=>$code, + 'times'=>0, + 'createtime'=>time(), + ]; + + DB::table('code_send')->insert($sendInfo); + session(['code' => $code]); + return $this->success('发送成功'); + } else { + return $this->error('操作错误'); + } + }else{ + + $apikey = "B62DaGfHTaZrvoffzw0JEg=="; + $apisecret = "dedca92317d74f549c307028e3be8de2"; + // $ip =$this-> getRealIp(); + $ip='172.0.0.1'; + $date = date("Y-m-d H:i:s",strtotime("-1 minute")); + $recode = DB::table('send_info') -> where('ip','=',$ip) + -> where('create_time','=>',$date) + -> where('create_time','<',date("Y-m-d H:i:s")) + -> first(); + if($recode){ + return $this->success('发送成功'); + } + + $today = DB::table('send_info')-> whereRaw("date_format(create_time,'%Y-%m-%d') ='".date("Y-m-d")."'")->count() ; + if($today && $today >= 100){ + return $this->success('发送成功'); + } + DB::table('send_info')->insert([ + 'ip' => $ip, + 'create_time' => date("Y-m-d H:i:s") + ]); + date_default_timezone_set("PRC"); + $msg_date = date("YmdHis"); + $msg_sign = md5($apikey.$msg_date.$apisecret); + $code = $this->createSmsCode(6); + if($yzm_radio == 1){ + + + DB::table('code_send')->where(['micro_numbers'=>$email])->delete(); + $sendInfo=[ + 'event'=>$type_new, + 'micro_numbers'=>$email, + 'code'=>$code, + 'times'=>0, + 'createtime'=>time(), + ]; + + DB::table('code_send')->insert($sendInfo); + session(['code' => $code]); + return $this->success($code); + } + // return $this->success('短信code是'.$area_code); + if($area_code=='+86'){ + $str = '【武齐科技】您的验证码是' . '【' . $code . '】, 请尽快完成验证'; + // $send_url = "https://api.230sms.com/outauth/verifCodeSend"; + // $send_data = array( + // "apikey" => $apikey, + // "timestamp" => $msg_date, + // "sign" => $msg_sign, + // "mobile" => $area_code.$email, + // "content" => $str + // ); + // $send_data = json_encode($send_data); + // $return_message = RPC::json_post($send_url, $send_data); + + //新发送短信 + $send_url = "http://smsapi.abosend.com:8205/api/sendSMS"; + $content="jkugghj"; + $mobileArea=$area_code; + $mobiles=$area_code.$email; + $query = [ + "orgCode" => 'LwybDLlX', + "mobileArea"=>$area_code, + "mobiles" => $mobiles, + "content" => urlencode(urlencode($str)), + "rand" => $code, + "sign" =>strtoupper(MD5('LwybDLlX'.$str.$code.'WXRSYBHCIKGLKVSWZDERICDIDEQSDFPK')) + ]; + }else{ + $str = '【OKDAX】Your verification code is' . '【' . $code . '】, please do not tell others! The verification code will expire in' . '5' . ' minutes.'; + // $send_url = "https://api.230sms.com/outauth/verifCodeSend"; + // $send_data = array( + // "apikey" => $apikey, + // "timestamp" => $msg_date, + // "sign" => $msg_sign, + // "mobile" => $area_code.$email, + // "content" => $str + // ); + // $send_data = json_encode($send_data); + // $return_message = RPC::json_post($send_url, $send_data); + + //新发送短信 + $send_url = "http://smsapi.abosend.com:8205/api/sendSMS"; + $content="jkugghj"; + $mobileArea=$area_code; + $mobiles=$area_code.$email; + $query = [ + "orgCode" => 'BdqhPSsH', + "mobileArea"=>$area_code, + "mobiles" => $mobiles, + "content" => urlencode(urlencode($str)), + "rand" => $code, + "sign" =>strtoupper(MD5('BdqhPSsH'.$str.$code.'PKWSBRYKOCFWEGZSUSBLABHTPNGETSVS')) + ]; + } + $url = $send_url; + $query=http_build_query($query); + + $return_message=$this->sendPost($url,$query); + // $return_message=[ + // "code"=>200, + // "data"=> + // [ + // "sendCode"=>"20240307231342LPT6O", + + // "message"=> "Submitted successfully"] + // ]; + + + //结束 + if ($return_message['code'] == '200') { + DB::table('code_send')->where(['micro_numbers'=>$email])->delete(); + $sendInfo=[ + 'event'=>$type_new, + 'micro_numbers'=>$email, + 'code'=>$code, + 'times'=>0, + 'createtime'=>time(), + ]; + + DB::table('code_send')->insert($sendInfo); + session(['code' => $code]); + return $this->success('发送成功'); + } else { + return $this->error('Failed to send'); + } + } + + } catch (\Exception $exception) { + return $this->error($exception->getMessage() . $exception->getLine()); + } + + } + + public function get_area_code(){ + $send_url = "http://smsapi.abosend.com:8205/api/viewOrgCostNameAndValue"; + $content="jkugghj"; + $code = $this->createSmsCode(6); + $query = [ + "orgCode" => 'BdqhPSsH', + "rand" => $code, + "sign" =>strtoupper(MD5('BdqhPSsH'.$code.'PKWSBRYKOCFWEGZSUSBLABHTPNGETSVS')) + ]; + + $url = $send_url; + $query=http_build_query($query); + + $return_message=$this->sendPost($url,$query); + if ($return_message['code'] == '200') { + $return_message['data']['costList']= array_merge([['costName'=>'+86','costValue'=>'','operator'=>'All']],$return_message['data']['costList']); + return $this->success($return_message['data']); + } else { + return $this->error('Failed'); + } + } + public function sendPost($url='',$data=''){ + + $ch = curl_init (); + + curl_setopt ( $ch, CURLOPT_URL, $url ); + + curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); + + curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 ); + + curl_setopt ( $ch, CURLOPT_POST, 1 ); //启用POST提交 + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + + curl_setopt ( $ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded') );//使用x-www-form-urlencoded + + $file_contents = curl_exec ( $ch );curl_close ( $ch ); + $return_message= json_decode($file_contents,true); + return $return_message; + } + + public function submail_sendMail(Request $request) + { + $email = $request->get('user_string'); + $type = $request->get('type'); + if (empty($email)) return $this->error('邮箱不能为空'); + + if ($type == 'forget') { + $user = Users::getByString($email); + if (empty($user)) return $this->error('账号错误'); + } else { + $user = Users::getByString($email); + if (!empty($user)) return $this->error('账号已存在'); + } + + // 从设置中取出值 + $appid = Setting::getValueByKey('submail_mail_send_appid', '14738'); + $appkey = Setting::getValueByKey('submail_mail_send_appkey', 'f4a0ef91e604402e2fde52600d648670'); + + $server = 'https://api.mysubmail.com/'; + + $mail_configs['appid'] = $appid; + + $mail_configs['appkey'] = $appkey; + + $mail_configs['sign_type'] = 'normal'; + + $mail_configs['server'] = $server; + + $submail = new SubmailMailSend($mail_configs); + + + $submail->AddTo($email); + + $submail->SetSender('mail@futurecoin.top', 'futurecoin.top'); + + $submail->SetSubject('短信验证码'); + + $code = $this->createSmsCode(6); + + $submail->SetText("您的验证码是:【{$code}】"); + + /* + |调用 send 方法发送邮件 + |-------------------------------------------------------------------------- + */ + + + $send = $submail->send(); + + if ($send['status'] == 'success') { + session(['code' => $code]); + return $this->success('发送成功'); + } else { + return $this->error("发送失败:{$send['msg']}"); + } + } +} diff --git a/app/Http/Controllers/Api/TransactionController.php b/app/Http/Controllers/Api/TransactionController.php new file mode 100644 index 0000000..88eedf1 --- /dev/null +++ b/app/Http/Controllers/Api/TransactionController.php @@ -0,0 +1,929 @@ +error('参数错误'); + $limit = Input::get('limit', 10); + $page = Input::get('page', 1); + $transactionIn = TransactionIn::where('user_id', $user_id)->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page); + if (empty($transactionIn)) return $this->error('您还没有交易记录'); + return $this->success(array( + "list" => $transactionIn->items(), 'count' => $transactionIn->total(), + "page" => $page, "limit" => $limit + )); + } + + public function TransactionOutList() + { + $user_id = Users::getUserId(); + if (empty($user_id)) { + return $this->error('参数错误'); + } + $limit = Input::get('limit', 10); + $page = Input::get('page', 1); + $transactionOut = TransactionOut::where('user_id', $user_id)->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page); + if (empty($transactionOut)) { + return $this->error('您还没有交易记录'); + } + return $this->success(array( + "list" => $transactionOut->items(), 'count' => $transactionOut->total(), + "page" => $page, "limit" => $limit + )); + } + + public function TransactionCompleteList() + { + $user_id = Users::getUserId(); + $limit = Input::get('limit', 10); + $page = Input::get('page', 1); + if (empty($user_id)) { + return $this->error('参数错误'); + } + $TransactionComplete = TransactionComplete::where('user_id', $user_id) + ->orwhere('from_user_id', $user_id) + ->orderBy('id', 'desc') + ->paginate($limit, ['*'], 'page', $page); + if (empty($TransactionComplete)) { + return $this->error('您还没有交易记录'); + } + foreach ($TransactionComplete->items() as $key => &$value) { + if ($value['type'] == 2) { + //触发者是买方 + if ($value['user_id'] == $user_id) { + $value['type'] = 'in'; + } else { + $value['type'] = 'out'; + } + } elseif ($value['type'] == 1) { + //触发者是卖方 + if ($value['user_id'] == $user_id) { + $value['type'] = 'out'; + } else { + $value['type'] = 'in'; + } + } + } + return $this->success(array( + "list" => $TransactionComplete->items(), 'count' => $TransactionComplete->total(), + "page" => $page, "limit" => $limit + )); + } + + + public function TransactionDel() + { + $user_id = Users::getUserId(); + $id = Input::get('id', ''); + $type = Input::get('type', ''); + if (empty($user_id) || empty($id) || empty($type)) return $this->error('参数错误'); + DB::beginTransaction(); + if ($type == 'in') {//取消法币锁定 + try { + $transactionIn = TransactionIn::where('user_id', $user_id)->find($id); //限定只能操作自己发布的 + if (!$transactionIn) { + throw new \Exception('非法操作,不能撤回非自己发布的信息'); + } + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $transactionIn->legal) + ->lockForUpdate() + ->first(); + $amount = bc_mul($transactionIn->price, $transactionIn->number, 5); + if (bc_comp($user_wallet->lock_legal_balance, $amount) < 0) { + throw new \Exception('非法操作:('); + } + $data_wallet1 = [ + 'balance_type' => 1, + 'wallet_id' => $user_wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_wallet->lock_legal_balance, + 'change' => -$amount, + 'after' => bc_sub($user_wallet->lock_legal_balance, $amount, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 1, + 'wallet_id' => $user_wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_wallet->legal_balance, + 'change' => $transactionIn->number, + 'after' => bc_add($user_wallet->legal_balance, $transactionIn->number, 5), + ]; + $user_wallet->lock_legal_balance = bc_sub($user_wallet->lock_legal_balance, $amount, 5); + $user_wallet->legal_balance = bc_add($user_wallet->legal_balance, $amount, 5); + $user_wallet->save();//法币余额增加 法币锁定余额减少 + $del_result = TransactionIn::destroy($id); + if ($del_result < 1) { + throw new \Exception('取销卖出交易失败'); + } + AccountLog::insertLog([ + 'user_id' => $user_id, + 'value' => -$transactionIn->number, + 'info' => "取消买入交易,解除法币余额锁定", + 'type' => AccountLog::TRANSACTIONIN_IN_DEL, + 'currency' => $transactionIn->legal, + ],$data_wallet1); + AccountLog::insertLog([ + 'user_id' => $user_id, + 'value' => $transactionIn->number, + 'info' => "取消买入交易,解除法币余额锁定", + 'type' => AccountLog::TRANSACTIONIN_IN_DEL, + 'currency' => $transactionIn->legal, + ],$data_wallet2); + DB::commit(); + return $this->success('取消成功'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } else if ($type == 'out') { + try { + $transactionOut = TransactionOut::where('user_id', $user_id)->find($id); //限定只能操作自己发布的 + if (!$transactionOut) { + throw new \Exception('非法操作'); + } + $user_wallet = UsersWallet::where('user_id', $user_id) + ->where('currency', $transactionOut->currency) + ->lockForUpdate() + ->first(); + if (bc_comp($user_wallet->lock_change_balance, $transactionOut->number) < 0) { + throw new \Exception('非法操作'); + } + $data_wallet1 = [ + 'balance_type' => 1, + 'wallet_id' => $user_wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_wallet->lock_legal_balance, + 'change' => -$transactionOut->number, + 'after' => bc_sub($user_wallet->lock_legal_balance, $transactionOut->number, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 1, + 'wallet_id' => $user_wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_wallet->legal_balance, + 'change' => $transactionOut->number, + 'after' => bc_add($user_wallet->legal_balance, $transactionOut->number, 5), + ]; + $user_wallet->lock_change_balance = bc_sub($user_wallet->lock_change_balance, $transactionOut->number, 5); + $user_wallet->change_balance = bc_add($user_wallet->change_balance, $transactionOut->number, 5); + $user_wallet->save();//余额增加 法币锁定余额减少 + $del_result = TransactionOut::destroy($id); + if ($del_result < 1) { + throw new \Exception('取销卖出交易失败'); + } + AccountLog::insertLog([ + 'user_id' => $user_id, + 'value' => -$transactionOut->number, + 'info' => "取消卖出交易,解除交易余额锁定", + 'type' => AccountLog::TRANSACTIONIN_OUT_DEL, + 'currency' => $transactionOut->currency, + ],$data_wallet1); + AccountLog::insertLog([ + 'user_id' => $user_id, + 'value' => $transactionOut->number, + 'info' => "取消卖出交易,解除交易余额锁定", + 'type' => AccountLog::TRANSACTIONIN_OUT_DEL, + 'currency' => $transactionOut->currency, + ],$data_wallet2); + DB::commit(); + return $this->success('取消成功'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } else { + return $this->error('类型错误'); + } + } + + public static function delTemp($id) + { + DB::beginTransaction(); + try { + $transactionOut = TransactionOut::find($id); //限定只能操作自己发布的 + if (!$transactionOut) { + return '交易不存在'; + } + $user_id = $transactionOut->user_id; + $user_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $transactionOut->currency)->first(); + if (bc_comp($user_wallet->lock_change_balance, $transactionOut->number) < 0) { + return '资金不足'; + } + + $data_wallet1 = [ + 'balance_type' => 1, + 'wallet_id' => $user_wallet->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_wallet->lock_legal_balance, + 'change' => -$transactionOut->number, + 'after' => bc_sub($user_wallet->lock_legal_balance, $transactionOut->number, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 1, + 'wallet_id' => $user_wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_wallet->legal_balance, + 'change' => $transactionOut->number, + 'after' => bc_add($user_wallet->legal_balance, $transactionOut->number, 5), + ]; + $user_wallet->lock_change_balance = $user_wallet->lock_change_balance - $transactionOut->number; + $user_wallet->change_balance = $user_wallet->change_balance + $transactionOut->number; + $user_wallet->save();//余额增加 法币锁定余额减少 + TransactionOut::destroy($id); + AccountLog::insertLog([ + 'user_id' => $user_id, + 'value' => -$transactionOut->number, + 'info' => "取消卖出交易,解除交易余额锁定", + 'type' => AccountLog::TRANSACTIONIN_OUT_DEL, + 'currency' => $transactionOut->currency + ],$data_wallet1); + AccountLog::insertLog([ + 'user_id' => $user_id, + 'value' => $transactionOut->number, + 'info' => "取消卖出交易,解除交易余额锁定", + 'type' => AccountLog::TRANSACTIONIN_OUT_DEL, + 'currency' => $transactionOut->currency + ],$data_wallet2); + DB::commit(); + return true; + } catch (\Exception $ex) { + DB::rollBack(); + return $ex->getMessage(); + } + } + + public function out() + { + + $user_id = Users::getUserId(); + + $price = Input::get("price"); + $num = Input::get("num"); + + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + + $has_num = 0; + if (empty($user_id) || empty($price) || empty($num) || empty($legal_id) || empty($currency_id)) { + return $this->error("参数错误"); + } + + + $user = Users::find($user_id); + $legal = Currency::where("is_display", 1) + ->where("id", $legal_id) + ->where("is_legal", 1) + ->first(); + $currency = Currency::where("is_display", 1) + ->where("id", $currency_id) + ->first(); + if (empty($user) || empty($legal) || empty($currency)) { + + return $this->error("数据未找到"); + } + try { + DB::beginTransaction(); + $user_currency = UsersWallet::where("user_id", $user_id) + ->where("currency", $currency_id) + ->lockForUpdate() + ->first(); + if (empty($user_currency)) { + throw new \Exception("请先添加钱包"); + } + if (bc_comp($price, 0) <= 0 || bc_comp($num, 0) <= 0) { + throw new \Exception("价格和数量必须大于0"); + } + if (bc_comp($user_currency->change_balance, $num) < 0) { + throw new \Exception("您的币不足"); + } + if (bc_comp($user_currency->lock_change_balance, 0) < 0) { + throw new \Exception("您的锁定资金异常,禁止挂卖"); + } + $today = date('Y-m-d'); + //查询该用户是不是黑名单用户 + $is_blacklist = $user->is_blacklist; + //查询当天已经交易的IMC币数 + $my_outs = TransactionOut::where("user_id", $user_id) + ->where("currency", "9") + ->where('create_time', '>=', $today) + ->sum('number'); + $my_complete_outs = TransactionComplete::where(function ($query) use ($today, $user_id) { + $query->orWhere(function ($query) use ($user_id) { + $query->where('way', 1)->where('user_id', $user_id); + })->orWhere(function ($query) use ($user_id) { + $query->where('way', 2)->where('from_user_id', $user_id); + }); + })->where('create_time', '>=', $today) + ->where('currency', 9) + ->sum('number'); + $my_total_outs = bc_add($my_outs, $my_complete_outs); + $should_num = bc_add($my_total_outs, $num); + if ($is_blacklist == 1 && $currency_id == 9) { + $can_out_today = bc_mul($user_currency->change_balance, 0.1); + if (bc_comp($can_out_today, $should_num) < 0) { + throw new \Exception("你今天的交易额度已达到上限!"); + } + } + $in = TransactionIn::where("price", ">=", $price) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->where("number", ">", "0") + ->orderBy('price', 'desc') + ->orderBy('id', 'asc') + ->get(); + + if (!empty($in)) { + foreach ($in as $i) { + if (bc_comp($has_num, $num) < 0) { + $shengyu_num = bc_sub($num, $has_num); + $this_num = 0; + if (bc_comp($i->number, $shengyu_num) > 0) { + $this_num = $shengyu_num; + } else { + $this_num = $i->number; + } + $has_num = bc_add($has_num, $this_num, 5); + if (bc_comp($this_num, 0) > 0) { + TransactionOut::transaction($i, $this_num, $user, $user_currency, $legal_id, $currency_id); + } + } else { + break; + } + } + } + + $num = bc_sub($num, $has_num, 5); + + if (bc_comp($num, 0) > 0) { + $out = new TransactionOut(); + $out->user_id = $user_id; + $out->price = $price; + $out->number = $num; + $out->currency = $currency_id; + $out->legal = $legal_id; + $out->create_time = time(); + $out->save(); + + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $user_currency->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_currency->change_balance, + 'change' => -$num, + 'after' => bc_sub($user_currency->change_balance, $num, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 2, + 'wallet_id' => $user_currency->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_currency->lock_change_balance, + 'change' => $num, + 'after' => bc_add($user_currency->lock_change_balance, $num, 5), + ]; + $user_currency->change_balance = bc_sub($user_currency->change_balance, $num, 5); + $user_currency->lock_change_balance = bc_add($user_currency->lock_change_balance, $num, 5); + $user_currency->save(); + + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => bc_mul($num, -1), + 'info' => "提交卖出记录扣除", + 'type' => AccountLog::TRANSACTIONOUT_SUBMIT_REDUCE, + 'currency' => $currency_id + ],$data_wallet1); + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => $num, + 'info' => "提交卖出记录(增加锁定)", + 'type' => AccountLog::TRANSACTIONOUT_SUBMIT_REDUCE, + 'currency' => $currency_id + ],$data_wallet2); + } + Transaction::pushNews($currency_id, $legal_id); + DB::commit(); + return $this->success("操作成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function in() + { + $user_id = Users::getUserId(); + + $price = Input::get("price"); + $num = Input::get("num"); + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + + $has_num = 0; + if (empty($user_id) || empty($price) || empty($num) || empty($legal_id) || empty($currency_id)) { + return $this->error("参数错误"); + } + + $legal = Currency::where("is_display", 1) + ->where("id", $legal_id) + ->where("is_legal", 1) + ->first(); + $currency = Currency::where("is_display", 1) + ->where("id", $currency_id) + ->first(); + + $user = Users::find($user_id); + if (empty($user) || empty($legal) || empty($currency)) { + return $this->error("数据未找到"); + } + if (bc_comp($price, 0) <= 0 || bc_comp($num, 0) <= 0) { + return $this->error("价格和数量必须大于0"); + } + + try { + DB::beginTransaction(); + //买方法币钱包 + $user_legal = UsersWallet::where("user_id", $user_id) + ->where("currency", $legal_id) + ->lockForUpdate() + ->first(); + $all_balance = bc_mul($price, $num, 5); + if (bc_comp($user_legal->legal_balance, $all_balance) < 0) { + throw new \Exception('余额不足'); + } + //查找所有价格小于等于当前价格的卖出委托 + $out = TransactionOut::where("price", "<=", $price) + ->where("number", ">", "0") + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->orderBy('price', 'asc') + ->orderBy('id', 'asc') + ->get(); + + if (!empty($out)) { + foreach ($out as $o) { + if (bc_comp($has_num, $num) < 0) { + $shengyu_num = bc_sub($num, $has_num, 5); + $this_num = 0; + if (bc_comp($o->number, $shengyu_num) > 0) { + $this_num = $shengyu_num; + } else { + $this_num = $o->number; + } + $has_num = bc_add($has_num, $this_num, 5); + if (bc_comp($this_num, 0) > 0) { + TransactionIn::transaction($o, $this_num, $user, $legal_id, $currency_id); + } + } else { + break; + } + } + } + + $remain_num = bcsub($num, $has_num); //匹配后的剩余数量 + + if (bc_comp($remain_num, 0) > 0) { + $in = new TransactionIn(); + $in->user_id = $user_id; + $in->price = $price; + $in->number = $remain_num; + $in->currency = $currency_id; + $in->legal = $legal_id; + $in->create_time = time(); + + $in->save(); + + $all_balance = bc_mul($price, $remain_num, 5); + $data_wallet1 = [ + 'balance_type' => 1, + 'wallet_id' => $user_legal->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_legal->legal_balance, + 'change' => -$all_balance, + 'after' => bc_sub($user_legal->legal_balance, $all_balance, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 1, + 'wallet_id' => $user_legal->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_legal->lock_legal_balance, + 'change' => $all_balance, + 'after' => bc_add($user_legal->lock_legal_balance, $all_balance, 5), + ]; + + $user_legal->legal_balance = bc_sub($user_legal->legal_balance, $all_balance, 5); + $user_legal->lock_legal_balance = bc_add($user_legal->lock_legal_balance, $all_balance, 5); + $user_legal->save(); + + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => bc_mul($all_balance, -1, 5), + 'info' => "提交卖入记录扣除", + 'type' => AccountLog::TRANSACTIONIN_SUBMIT_REDUCE, + 'currency' => $currency_id, + ],$data_wallet1); + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => $all_balance, + 'info' => "提交卖入记录扣除", + 'type' => AccountLog::TRANSACTIONIN_SUBMIT_REDUCE, + 'currency' => $currency_id, + ],$data_wallet2); + } else { + //匹配完成s + } + Transaction::pushNews($currency_id, $legal_id); + DB::commit(); + return $this->success("操作成功"); + } catch (\Exception $ex) { + DB::rollback(); + return $this->error($ex->getMessage()); + } + } + + public function deal() + { + $user_id = Users::getUserId(); + + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + + if (empty($legal_id) || empty($currency_id)) { + return $this->error("参数错误"); + } + $in = TransactionIn::with(['legalcoin', 'currencycoin']) + ->where("number", ">", 0) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->groupBy('currency', 'legal', 'price') + ->orderBy('price', 'desc') + ->select([ + 'currency', + 'legal', + 'price', + ])->selectRaw('sum(`number`) as `number`') + ->limit(10) + ->get() + ->toArray(); + $out = TransactionOut::with(['legalcoin', 'currencycoin']) + ->where("number", ">", 0) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->groupBy('currency', 'legal', 'price') + ->orderBy('price', 'asc') + ->select([ + 'currency', + 'legal', + 'price', + ])->selectRaw('sum(`number`) as `number`') + ->limit(10) + ->get() + ->toArray(); + + krsort($out); + $out_data = array(); + foreach ($out as $o) { + array_push($out_data, $o); + } + + $complete = TransactionComplete::orderBy('id', 'desc')->where("currency", $currency_id)->where("legal", $legal_id)->take(15)->get(); + + $last_price = 0; + $last = TransactionComplete::orderBy('id', 'desc')->where("currency", $currency_id)->where("legal", $legal_id)->first(); + if (!empty($last)) { + $last_price = $last->price; + } + + $user_legal = 0; + $user_currency = 0; + if (!empty($user_id)) { + $legal = UsersWallet::where("user_id", $user_id)->where("currency", $legal_id)->first(); + if ($legal) { + $user_legal = $legal->legal_balance; + } + $currency = UsersWallet::where("user_id", $user_id)->where("currency", $currency_id)->first(); + if ($currency) { + $user_currency = $currency->change_balance; + } + } + + $ustd_price = 0; + $last = TransactionComplete::orderBy('id', 'desc') + ->where("currency", $legal_id) + ->where("legal", 1)->first();//4是usdt + if (!empty($last)) { + $ustd_price = $last->price; + } + if ($legal_id == 1) { + $ustd_price = 1; + } + $cny_price = Currency::getCnyPrice($legal_id); + return $this->success([ + "in" => $in, + "out" => $out_data, + "cny_price"=> $cny_price, + "last_price" => $last_price, + "user_legal" => $user_legal, + "user_currency" => $user_currency, + "complete" => $complete + ]); + } + + public function walletIn() + { + $user_id = Users::getUserId(); + + $price = Input::get("price"); + $num = Input::get("num"); + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + + $has_num = 0; + if (empty($user_id) || empty($price) || empty($num) || empty($legal_id) || empty($currency_id)) { + return $this->error("参数错误"); + } + + $legal = Currency::where("is_display", 1) + ->where("id", $legal_id) + // ->where("is_legal", 1) + ->first(); + $currency = Currency::where("is_display", 1) + ->where("id", $currency_id) + ->first(); + + $user = Users::find($user_id); + if (empty($user) || empty($legal) || empty($currency)) { + return $this->error("数据未找到"); + } + if (bc_comp($price, 0) <= 0 || bc_comp($num, 0) <= 0) { + return $this->error("价格和数量必须大于0"); + } + + try { + DB::beginTransaction(); + //买方交易币币钱包 + $user_change = UsersWallet::where("user_id", $user_id) + ->where("currency", $legal_id) + ->lockForUpdate() + ->first(); + $all_balance = bc_mul($price, $num, 5); + if (bc_comp($user_change->change_balance, $all_balance) < 0) { + throw new \Exception('余额不足'); + } + //查找所有价格小于等于当前价格的卖出委托 + $out = TransactionOut::where("price", "<=", $price) + ->where("number", ">", "0") + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->orderBy('price', 'asc') + ->orderBy('id', 'asc') + ->get(); + + if (!empty($out)) { + foreach ($out as $o) { + if (bc_comp($has_num, $num) < 0) { + $shengyu_num = bc_sub($num, $has_num, 5); + $this_num = 0; + if (bc_comp($o->number, $shengyu_num) > 0) { + $this_num = $shengyu_num; + } else { + $this_num = $o->number; + } + $has_num = bc_add($has_num, $this_num, 5); + if (bc_comp($this_num, 0) > 0) { + TransactionIn::walletTransaction($o, $this_num, $user, $legal_id, $currency_id); + } + } else { + break; + } + } + } + + $remain_num = bcsub($num, $has_num); //匹配后的剩余数量 + + if (bc_comp($remain_num, 0) > 0) { + $in = new TransactionIn(); + $in->user_id = $user_id; + $in->price = $price; + $in->number = $remain_num; + $in->currency = $currency_id; + $in->legal = $legal_id; + $in->create_time = time(); + + $in->save(); + + $all_balance = bc_mul($price, $remain_num, 5); + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $user_change->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_change->change_balance, + 'change' => -$all_balance, + 'after' => bc_sub($user_change->change_balance, $all_balance, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 1, + 'wallet_id' => $user_change->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_change->lock_change_balance, + 'change' => $all_balance, + 'after' => bc_add($user_change->lock_change_balance, $all_balance, 5), + ]; + + $user_change->change_balance = bc_sub($user_change->change_balance, $all_balance, 5); + $user_change->lock_change_balance = bc_add($user_change->lock_change_balance, $all_balance, 5); + $user_change->save(); + + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => bc_mul($all_balance, -1, 5), + 'info' => "提交卖入记录扣除", + 'type' => AccountLog::TRANSACTIONIN_SUBMIT_REDUCE, + 'currency' => $currency_id, + ],$data_wallet1); + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => $all_balance, + 'info' => "提交卖入记录扣除,锁定余额增加", + 'type' => AccountLog::TRANSACTIONIN_SUBMIT_REDUCE, + 'currency' => $currency_id, + ],$data_wallet2); + } else { + //匹配完成s + } + Transaction::pushNews($currency_id, $legal_id); + DB::commit(); + return $this->success("操作成功"); + } catch (\Exception $ex) { + DB::rollback(); + return $this->error($ex->getMessage()); + } + } + //钱包卖出代码 + public function walletOut() + { + + $user_id = Users::getUserId(); + + $price = Input::get("price"); + $num = Input::get("num"); + + $legal_id = Input::get("legal_id"); + $currency_id = Input::get("currency_id"); + + $has_num = 0; + if (empty($user_id) || empty($price) || empty($num) || empty($legal_id) || empty($currency_id)) { + return $this->error("参数错误"); + } + + + $user = Users::find($user_id); + $legal = Currency::where("is_display", 1) + ->where("id", $legal_id) + // ->where("is_legal", 1) + ->first(); + $currency = Currency::where("is_display", 1) + ->where("id", $currency_id) + ->first(); + if (empty($user) || empty($legal) || empty($currency)) { + + return $this->error("数据未找到"); + } + try { + DB::beginTransaction(); + $user_currency = UsersWallet::where("user_id", $user_id) + ->where("currency", $currency_id) + ->lockForUpdate() + ->first(); + if (empty($user_currency)) { + throw new \Exception("请先添加钱包"); + } + if (bc_comp($price, 0) <= 0 || bc_comp($num, 0) <= 0) { + throw new \Exception("价格和数量必须大于0"); + } + if (bc_comp($user_currency->change_balance, $num) < 0) { + throw new \Exception("您的币不足"); + } + + //查找价格高于等于当前卖出价格的所有买入委托 + $in = TransactionIn::where("price", ">=", $price) + ->where("currency", $currency_id) + ->where("legal", $legal_id) + ->where("number", ">", "0") + ->orderBy('price', 'desc') + ->orderBy('id', 'asc') + ->get(); + + if (!empty($in)) { + foreach ($in as $i) { + if (bc_comp($has_num, $num) < 0) { + $shengyu_num = bc_sub($num, $has_num); + $this_num = 0; + if (bc_comp($i->number, $shengyu_num) > 0) { + $this_num = $shengyu_num; + } else { + $this_num = $i->number; + } + $has_num = bc_add($has_num, $this_num, 5); + if (bc_comp($this_num, 0) > 0) { + TransactionOut::walletTransaction($i, $this_num, $user, $user_currency, $legal_id, $currency_id); + } + } else { + break; + } + } + } + + $num = bc_sub($num, $has_num, 5); + + if (bc_comp($num, 0) > 0) { + $out = new TransactionOut(); + $out->user_id = $user_id; + $out->price = $price; + $out->number = $num; + $out->currency = $currency_id; + $out->legal = $legal_id; + $out->create_time = time(); + $out->save(); + + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $user_currency->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $user_currency->change_balance, + 'change' => -$num, + 'after' => bc_sub($user_currency->change_balance, $num, 5), + ]; + $data_wallet2 = [ + 'balance_type' => 2, + 'wallet_id' => $user_currency->id, + 'lock_type' => 1, + 'create_time' => time(), + 'before' => $user_currency->lock_change_balance, + 'change' => $num, + 'after' => bc_add($user_currency->lock_change_balance, $num, 5), + ]; + $user_currency->change_balance = bc_sub($user_currency->change_balance, $num, 5); + $user_currency->lock_change_balance = bc_add($user_currency->lock_change_balance, $num, 5); + $user_currency->save(); + + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => bc_mul($num, -1), + 'info' => "提交卖出记录扣除", + 'type' => AccountLog::TRANSACTIONOUT_SUBMIT_REDUCE, + 'currency' => $currency_id + ],$data_wallet1); + AccountLog::insertLog([ + 'user_id' => $user->id, + 'value' => $num, + 'info' => "提交卖出记录(增加锁定)", + 'type' => AccountLog::TRANSACTIONOUT_SUBMIT_REDUCE, + 'currency' => $currency_id + ],$data_wallet2); + } + Transaction::pushNews($currency_id, $legal_id); + DB::commit(); + return $this->success("操作成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } +} diff --git a/app/Http/Controllers/Api/UserController.php b/app/Http/Controllers/Api/UserController.php new file mode 100644 index 0000000..92b8db1 --- /dev/null +++ b/app/Http/Controllers/Api/UserController.php @@ -0,0 +1,2928 @@ +get('from_currency_id',''); //被划转币种 + $to_currency_id = $request->get('to_currency_id','');//划转目标币种 + if(!$from_currency_id || !$to_currency_id){ + return $this->error('error, Parameter is empty!'); + } + $from_currency = Currency::where('id',$from_currency_id)->where('is_transfer',1)->first(); + $to_currency = Currency::where('id',$to_currency_id)->where('is_transfer',1)->first(); + $transfer_fee = Setting::getValueByKey('transfer_fee'); + + if(!$to_currency){ + return $this->error('This currency ['.$to_currency.'] does not support transfers'); + } + if(!$from_currency){ + return $this->error('This currency ['.$from_currency.'] does not support transfers'); + } + + $data =[ + 'form_price'=>$from_currency->price, + 'to_price'=>$to_currency->price, + 'fee'=>$transfer_fee, + ]; + + return $this->success($data); + } + + + //返回列表 + public function OrderList(Request $request) + { + $page = $request->get('page', 1); + $limit = $request->get('limit',10); + // $status=$request->get('status', 0); + $type=$request->get('type', 1); + $user_id = Users::getUserId();//66005883; + // $where['review_status'] = ['>', 0]; + // $where['status']= $status; + + if($type==1){ + $lists = DB::table('charge_req') + ->join('currency', 'currency.id', '=', 'charge_req.currency_id') + ->where('charge_req.uid',$user_id) + ->select('charge_req.*', 'currency.name') + ->orderBy('charge_req.id', 'desc') + ->paginate($limit); + + } + if($type==2){ + $lists = DB::table('users_wallet_out') + ->join('currency', 'currency.id', '=', 'users_wallet_out.currency') + ->where('users_wallet_out.user_id',$user_id) + ->select('users_wallet_out.id', 'users_wallet_out.number', + 'currency.name','users_wallet_out.create_time','users_wallet_out.real_number as amount' + ,'users_wallet_out.status') + ->orderBy('users_wallet_out.id', 'desc') + ->paginate($limit); + + foreach($lists->items() as &$items){ + $items->create_time = date('Y-m-d H:i:s',$items->create_time); + $arr = [1=>'审核中',2=>'审核完成',3=>'审核失败']; + $items->status_text = $arr[$items->status]; + } + unset($items); + + } + if($type==3){ + + $user['amount'] = DefiOrder::where('user_id',$user_id)->where('review_status',2)->sum('amount')??"0.00"; //已借USDT + $user['remainamount'] = DefiOrder::where('user_id',$user_id)->where('review_status',2)->where('status',0)->sum('total')??"0.00"; //剩余还币数量 + $user['repaid']= DefiOrder::where('user_id',$user_id)->where('review_status',2)->where('status',1)->sum('amount')??"0.00"; //已还 + $lists = DefiOrder::where('user_id',$user_id)->paginate($limit); + + $result = array('data' => $lists->items(), 'info'=>$user,'page' => $page, 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + + + + + + if($type==4){ + $currency_id = 0; + $user_wallet = UsersWallet::where('currency', 3)->where('user_id', $user_id)->first();//法币只有USDT + $balance = $user_wallet ? $user_wallet->lever_balance : 0; + //取盈亏总额 + list( + 'caution_money_total' => $caution_money_all, + 'origin_caution_money_total' => $origin_caution_money_all, + 'profits_total' => $profits_all + ) = LeverTransaction::getUserProfit($user_id, 3); + //取该交易对盈亏总额 + list( + 'caution_money_total' => $caution_money, + 'origin_caution_money_total' => $origin_caution_money, + 'profits_total' => $profits + ) = LeverTransaction::getUserProfit($user_id, 3, $currency_id); +// $total_all_money = bc_add($caution_money_all, $balance); + $hazard_rate = LeverTransaction::getWalletHazardRate($user_wallet); + $lever_transaction['rate_profits_total'] = [ + 'hazard_rate' => $hazard_rate, + 'profits_total' => $profits_all, + ]; + //接入风险率和持仓总盈亏end + + // $param = compact('status', 'legal_id', 'currency_id'); + $lever_transaction['message'] = LeverTransaction::where('user_id', $user_id) + ->orderBy('id', 'desc') + ->paginate($limit); + return $this->success($lever_transaction); + } + + + if($type==5){ + + $lists = AiOrder::where('user_id', $user_id)->select('id','ai_id','name','day','amount','number','total','commission','totalincome','startdate','expire','status')->orderBy('id', 'desc')->paginate($limit); + } + + + if($type==6){ + + $list = CoinTrade::where('u_id',$user_id) + ->orderBy('id','desc') + ->skip($limit*($page-1))->take($limit)->get(); + foreach($list as &$li){ + $li['symbol'] = Currency::getNameById($li->currency_id).'/'.Currency::getNameById($li->legal_id); + } + return $this->success($list); + } + + if($type==7){ + + $lists = DualOrder::where('user_id', $user_id)->select('id','name','amount','totalincome','invest','startdate','expire','status')->orderBy('id', 'desc')->paginate($limit); + + } + + + if($type==8) { + + $lists = DB::table('users_wallet_out') + ->join('currency', 'currency.id', '=', 'users_wallet_out.currency') + ->where('users_wallet_out.user_id',$user_id)->where('users_wallet_out.type',1) + ->select('users_wallet_out.id', 'users_wallet_out.number', + 'currency.name','users_wallet_out.create_time','users_wallet_out.real_number as amount' + ,'users_wallet_out.status') + ->orderBy('users_wallet_out.id', 'desc') + ->paginate($limit); + + foreach($lists->items() as &$items){ + $items->create_time = date('Y-m-d H:i:s',$items->create_time); + $arr = [1=>'审核中',2=>'审核完成',3=>'审核失败']; + $items->status_text = $arr[$items->status]; + } + unset($items); + + + } + $result = array('data' => $lists->items(), 'page' => $page, 'pages' => $lists->lastPage(), 'total' => $lists->total()); + + return $this->success($result); + + } + + + + //借贷 验证 + public function Verification(Request $request) + { + $user_id = Users::getUserId(); + $front_pic = $request->post('front_pic'); // z住房信息 + $dex_pic = $request->post('dex_pic'); // dex担保人 + $bank_pic = $request->post('bank_pic'); // 银行对账单 + $hand_pic = $request->post('hand_pic'); //证件照 + + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + + + + if (empty($front_pic) || empty($dex_pic) || empty($bank_pic) || empty($hand_pic)){ + return $this->error('请填写完整信息'); + } + + + + + $real = new UserJiedai; + $real->user_id = $user_id; + $real->dex_pic = $dex_pic; + $real->create_time = time(); + $real->review_status = 1; + $real->hand_pic = $hand_pic; + $real->front_pic = $front_pic; + $real->bank_pic = $bank_pic; + + $real->save(); + + return $this->success('申请成功,请等待审核'); + } + + + //查看我的借贷订单 + public function jiedai_list(Request $request){ + $limit = $request->get('limit', 10); + $status = $request->get('status',0); + + $user_id = 1;//Users::getUserId(); + $list = DB::table('user_jiedai')->where('user_id', $user_id)->where('status', $status)->orderBy('id', 'desc')->paginate($limit); + + + + return $this->success(array( + "list" => $list->items(), + "limit" => $limit, + )); + } + + + + //借贷还款 + public function Jiedaicancle(Request $request){ + $id = $request->post('id'); + + $user_id = Users::getUserId(); + + + if(empty($id) || !is_numeric($id)){ + return $this->error('Parameter error:ID Is NULL'); + } + + $dual_order = UserJiedai::where('id',$id)->where('review_status',2)->where('status',0)->where('user_id',$user_id)->first(); + + if (empty($dual_order)){ + return $this->error('No repayment exists'); //不存在还款 + } + + $amount = $dual_order->amount+$dual_order->lixi; + if(empty($amount)){ + return $this->error('Parameter error:amount Is NULL'); + } + + + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + + + + $dual_order->status = 1; + + $dual_order->end_time = date("Y-m-d H:i:s",time()); + + $result = change_wallet_balance($user_walllet , -4 , $amount , AccountLog::USER_LOAN_ORDER_RETURN,'借贷还款'); + if($result){ + $dual_order->save(); + return $this->success('操作成功'); + + } + + } + + + + //借贷 入库 + public function savejiedai(Request $request) + { + $user_id = Users::getUserId(); + + $hk_type = $request->post('hk_type'); // 还款方式 + + // $lv_perday = $request->post('lv_perday'); // 每日利率 + + $days = $request->post('days'); // 周期 + + $lixi = $request->post('lixi'); // 利息 + + $amount= $request->post('amount',0); // 借款金额 + + $info = UserJiedai::where('status',0)->where('review_status',2)->where('user_id',$user_id)->first(); + + if (!empty($info)){ + return $this->error('Loan already exists'); + } + + if (!$amount){ + return $this->error('amount error'); + } + + $name = $request->post('name'); //放款机构 + /* + $front_pic = $request->post('front_pic'); // z住房信息 + $dex_pic = $request->post('dex_pic'); // dex担保人 + $bank_pic = $request->post('bank_pic'); // 银行对账单 + $hand_pic = $request->post('hand_pic'); //证件照 + */ + + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + if ($amount){ + if (empty($name) || empty($hk_type) || empty($lixi) || empty($days)){ + return $this->error('请填写完整信息'); + } + + /* + if (empty($front_pic) || empty($dex_pic) || empty($bank_pic) || empty($hand_pic)){ + return $this->error('请填写完整信息'); + } + */ + + + + $real = new UserJiedai; + $real->hk_type = $hk_type; + $real->htcode = date("YmdHis",time()).'0000'.$user_id; + // $real->lv_perday = $lv_perday; + $real->lixi = $lixi; + $real->days = $days; + $real->name = $name; + $real->amount = $amount; + $real->user_id = $user_id; + // $real->dex_pic = $dex_pic; + $real->create_time = time(); + $real->review_status = 1; + // $real->hand_pic = $hand_pic; + // $real->front_pic = $front_pic; + // $real->bank_pic = $bank_pic; + + $real->save(); + } + return $this->success('申请成功,请等待审核'); + } + + + + + + // 借贷合同 + public function get_jiedai_htinfo(){ + + $user_id = Users::getUserId(); + if(!$user_id){ + return $this->error('error!'); + } + + $data['dai_amount'] = 0; //货币数量 + $data['over_amount'] = 0; // 已还款 + $data['hk_amount'] = 0; // 剩余还款 + $data['dqlixi_amount'] = 0; //利息 + + $info['data']=DB::table('user_jiedai')->where('user_id',$user_id)->orderBy('create_time','DESC')->first(); + if(empty($info)){ + + return $this->success(''); + } + $data['hk_amount'] = DB::table('user_jiedai')->where('user_id',$user_id)->where('review_status',2)->where('status',0)->sum('amount'); + $data['over_amount'] = DB::table('user_jiedai')->where('user_id',$user_id)->where('review_status',2)->where('status',1)->sum('amount'); + + $data['dqlixi_amount'] = DB::table('user_jiedai')->where('user_id',$user_id)->where('review_status',2)->where('status',0)->sum('lixi'); + // $data['total_dai_num'] = DB::table('user_jiedai')->where('user_id',$user_id)->where('review_status',2)->where('status',0)->count(); + + $data['hk_amount'] = $data['hk_amount'] +$data['dqlixi_amount']; + + + $info = array_merge($info,$data); + + return $this->success($info); + } + + + + // 借贷信息 + public function get_jiedai_info(){ + + $user_id = Users::getUserId(); + if(!$user_id){ + return $this->error('error!'); + } + + $data['dai_amount'] = 0; + $data['total_dai_amount'] = 0; + $data['total_dai_num'] = 0; + // $day=Input::get('day'); + $info['data']=DB::table('lk_zhiya')->where('status',1)->orderBy('id', 'asc')->get()->toArray(); + + + $data['total_dai_amount'] = DB::table('user_jiedai')->where('user_id',$user_id)->where('review_status',2)->sum('amount'); + $data['dai_amount'] = DB::table('user_jiedai')->where('user_id',$user_id)->where('review_status',2)->where('status',0)->sum('amount'); + $data['total_dai_num'] = DB::table('user_jiedai')->where('user_id',$user_id)->where('review_status',2)->where('status',0)->count(); + + + + + + $info = array_merge($info,$data); + + return $this->success($info); + } + + + + //获取可划转的币种 + public function getTransferList(){ + $user_id = Users::getUserId(); + if(!$user_id){ + return $this->error('error!'); + } + + $get_transfer_list = Currency::where('is_transfer',1)->get(['id','name'])->toArray(); + UsersWallet::leftjoin("currency", "currency.id", "users_wallet.currency") + ->where("users_wallet.user_id", $user_id) + ->where("currency.is_transfer", 1) + ->select(); + $user_wallet = UsersWallet::where("user_id","=",$user_id)->get(['currency','change_balance'])->toArray(); + + return $this->success(['transfer'=>$get_transfer_list??[],'wallet'=>$user_wallet]); + } + + + public function getCreditList(Request $request){ + $user_id = Users::getUserId(); + $limit = $request->get('limit', 15); + $page = $request->get('page', 1); + $lang = $request->get('lang', '') ?: session()->get('lang'); + $lang == '' && $lang = 'zh'; + + $list = DB::table('user_credit_bill')->where('user_id',$user_id) + ->orderBy('id', 'desc') + ->select('id','num','create_time_text','create_time',$lang.'_title',$lang.'_info') + ->paginate($limit, ['*'], 'page', $page); + $data['list']=$list; + $data['creditNum']=DB::table('user_credit_bill')->where('user_id',$user_id)->sum('num'); + $data['newNum']=DB::table('user_credit_bill')->where('user_id',$user_id)->orderBy('id', 'desc')->value('num'); + + return $this->success($data); + + } + //币币划转 + public function Transfer(Request $request){ + $user_id = Users::getUserId(); + $user = Users::find($user_id); + if($user->frozen_funds==1){ + return $this->error('资金已冻结'); + } + $from_currency_id = $request->get('from_currency_id',''); //被划转币种 + $to_currency_id = $request->get('to_currency_id','');//划转目标币种 + $number = $request->get('number',0);//划转数量 + if(Cache::has("on_the_way_$user_id")){ + return $this->error('Do not repeat the operation!'); + } + Cache::put("on_the_way_$user_id", 1, Carbon::now()->addSeconds(3)); + if(!$from_currency_id || !$to_currency_id|| !$number || !$user_id){ + return $this->error('error, Parameter is empty!'); + } + + if($from_currency_id==$to_currency_id){ + return $this->error('The same currency cannot be transferred!'); //相同币种不可划转 + } + $from_currency = Currency::where('id',$from_currency_id)->where('is_transfer',1)->first(); + $to_currency = Currency::where('id',$to_currency_id)->where('is_transfer',1)->first(); + $from_user_walllet_currency=UsersWallet::where("user_id","=",$user_id)->where("currency","=",$from_currency_id)->first(); + $to_user_walllet_currency=UsersWallet::where("user_id","=",$user_id)->where("currency","=",$to_currency_id)->first(); + if(!$from_user_walllet_currency || !$to_user_walllet_currency){ + return $this->error('User wallet does not exist'); + } + if(!$to_currency){ + return $this->error('This currency ['.$to_currency.'] does not support transfers'); + } + if(!$from_currency){ + return $this->error('This currency ['.$from_currency.'] does not support transfers'); + } + + + $f_new_price = $from_currency['price'];//最新币种 + $t_new_price = $to_currency['price'];//最新币种 + $transfer_fee = Setting::getValueByKey('transfer_fee',0);//获取手续费比例 + $form_amount = bc_mul($f_new_price ,$number); + $to_amount = bc_div($form_amount, $t_new_price); + if($transfer_fee<=0){ + $transfer_money = 0; + }else{ + $transfer_money = bc_div(bc_div(bc_mul($transfer_fee,$form_amount),100),$f_new_price); + } + + if($to_amount<=0 || $number<=0){ + return $this->error('Numerical error!'); + } + if($transfer_money<0){ + $transfer_money = 0; + } + + DB::beginTransaction(); + try{ + change_wallet_balance($from_user_walllet_currency , 2 , -$number , AccountLog::USER_EXCHANGE_DOWN,'划转减少' . $from_user_walllet_currency->name); + change_wallet_balance($to_user_walllet_currency , 2 , $to_amount , AccountLog::USER_EXCHANGE_ADD,'划转增加' . $to_user_walllet_currency->name); + change_wallet_balance($from_user_walllet_currency , 2 , -$transfer_money ,AccountLog::USER_EXCHANGE_FEE, '手续费' . $from_user_walllet_currency->name); //从被划转的币种扣除 + DB::commit(); + return $this->success('资产兑换成功!'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + + } + + public function getUserChargeAmount(Request $request){ + $key = $request->header('key'); + if($key != 'Ttzscdsfajcl123@$a'){ + return $this->error('非法请求'); + } + $user_id = $request->get('user_id'); + + $time = $request->get('starttime'); + if(!$time || !$user_id){ + return $this->error('缺少参数'); + } + $sum = AccountLog::where('user_id',$user_id)->where('currency',31)->where('created_time','>',$time)->where('type',AccountLog::WALLET_CURRENCY_IN)->sum('value'); + return $this->success(['total_charge'=>$sum]); + } + + public function addCollection(Request $request){ + $array = $request->get('value',''); + if(!$array){ + return $this->error('参数异常'); + } + $array = (string)$array; + $user_id = Users::getUserId(); + $key = 'User_Collect_'.$user_id; + $redis = RedisService::getInstance(3); + if(!$redis->sIsMember($key,$array)){ + $redis->sAdd($key,$array); + } + return $this->success('添加成功'); + } + public function getCollection(Request $request){ + + $user_id = Users::getUserId(); + $key = 'User_Collect_'.$user_id; + $redis = RedisService::getInstance(3); + $res = $redis->sMembers($key); + return $this->success($res); + } + public function deleteCollection(Request $request){ + $array = $request->get('value',''); + if(!$array){ + return $this->error('参数异常'); + } + $user_id = Users::getUserId(); + $key = 'User_Collect_'.$user_id; + $redis = RedisService::getInstance(3); + $redis->sRem($key,$array); + return $this->success(''); + } + + public function rechargeLog(Request $request) + { + $user_id = Users::getUserId(); + $page = $request->get('page',1); + $limit = $request->get('limit',10); + $lists = DB::table('charge_req') + ->join('currency', 'currency.id', '=', 'charge_req.currency_id') + ->where('charge_req.uid',$user_id) + ->select('charge_req.*', 'currency.name') + ->orderBy('charge_req.id', 'desc') + ->paginate($limit); + $result = array('data' => $lists->items(), 'page' => $page, 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + + //用户认证 + public function newrealState(Request $request) + { + $user_id = Users::getUserId(); + $real_status = 0; + $review_status = 0; + $advanced_review_status = 0; + + $real_data = DB::table('user_real')->where('user_id',$user_id) + ->first(); + + if (!empty($real_data)){ + if ($real_data->review_status == 1){ + $real_status = 1; + $review_status = 1; + } + + if ($real_data->review_status == 2){ + $real_status = 2; + $review_status = 2; + + } + + } + + $result = compact('real_status','review_status','advanced_review_status',"real_data"); + return $this->success($result); + } + + public function newsaveUserReal(Request $request) + { + $user_id = Users::getUserId(); + + $id_type = $request->post('id_type', 0); // 0身份证 1护照 2驾驶证 + $country = $request->post('country', ''); // 国家 + + // 接受参数 + $real_type = $request->post('real_type'); // 1 初级认证 2 高级认证 + if (!in_array($real_type,[1,2])){ + return $this->error('认证类型错误'); + } + $name = $request->post('name'); + $surname = $request->post('surname'); + // $card_id = $request->post('card_id'); + $gender = $request->post('gender'); + $birthday = $request->post('birthday'); + $address = $request->post('address'); + $tel = $request->post('tel'); + $email = $request->post('email'); + + $front_pic = $request->post('front_pic'); + $reverse_pic = $request->post('reverse_pic'); + $hand_pic = $request->post('hand_pic'); + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + if ($real_type == 1){ + if (empty($name) || empty($surname) || empty($country) || empty($birthday) || empty($address) || empty($tel) || empty($email)){ + return $this->error('请填写完整信息'); + } + + if (empty($front_pic) || empty($reverse_pic) || empty($hand_pic)){ + return $this->error('请上传身份证信息'); + } + //校验 身份证号码合法性 + // $idcheck = new IdCardIdentity(); + // $res = $idcheck->check_id($card_id); + // if (!$res) { + // return $this->error("请输入合法的身份证号码"); + // } + + // $userreal_number = UserReal::where("card_id",$card_id)->count(); + // if($userreal_number>0) + // { + // return $this->error("该身份证号已实名认证过!"); + // } + $real = UserReal::where('user_id',$user_id)->first(); + if ($real){ + return $this->error('已经审核过认证~'); + } + $real = new UserReal; + $real->id_type = $id_type; + $real->name = $name; + $real->surname = $surname; + $real->birthday = $birthday; + $real->address = $address; + $real->tel = $tel; + $real->email = $email; + $real->country = $country; + $real->user_id = $user_id; + // $real->card_id = $card_id; + $real->gender = $gender; + $real->front_pic = $front_pic; + $real->reverse_pic = $reverse_pic; + $real->hand_pic = $hand_pic; + $real->create_time = time(); + $real->save(); + $data_credit=[ + 'user_id'=>$user_id, + 'zh_title'=>'完成基础认证', + 'en_title'=>'Complete basic certification', + 'th_title'=>'完成基礎認證', + 'hk_title'=>'เสร็จสิ้นการรับรองขั้นพื้นฐาน', + 'jp_title'=>'基礎資格認定の完了', + 'kor_title'=>'기본 인증 완료', + 'fra_title'=>'Terminer la certification de base', + 'spa_title'=>'Completar la certificación básica', + + 'zh_info'=>'完成基础认证,增加信用分', + 'en_info'=>'Complete basic certification and increase credit score', + 'th_info'=>'完成基礎認證,新增信用分', + 'hk_info'=>'ผ่านการรับรองพื้นฐานและเพิ่มคะแนนเครดิต', + 'jp_info'=>'基礎認証を完了し、信用分を増やす', + 'kor_info'=>'기초인증 완료, 신용점수 증가', + 'fra_info'=>'Compléter la certification de base, augmenter les points de crédit', + 'spa_info'=>'Completar la certificación básica y aumentar la puntuación crediticia', + 'num'=>20, + 'create_time_text'=>date('Y-m-d H:i:s',time()), + 'create_time'=>time() + ]; + DB::table('user_credit_bill')->insert($data_credit); + }else{ + if (empty($front_pic) || empty($reverse_pic)){ + return $this->error('请填写完整信息'); + } + $real = UserReal::where('user_id',$user_id)->first(); + if (empty($real)){ + return $this->error('请先完成初级认证'); + } + if ($real->review_status != 2){ + return $this->error('初级认证审核中,请耐心等待'); + } + $real->front_pic = $front_pic; + $real->reverse_pic = $reverse_pic; + $real->advanced_user = 1; + $real->save(); + $data_credit=[ + 'user_id'=>$user_id, + 'zh_title'=>'完成高级认证', + 'en_title'=>'Complete advanced certification', + 'th_title'=>'完成高級認證', + 'hk_title'=>'เสร็จสิ้นการรับรองขั้นสูง', + 'jp_title'=>'高度な資格認定の完了', + 'kor_title'=>'고급 인증 완료', + 'fra_title'=>'Terminer la certification avancée', + 'spa_title'=>'Completar la certificación avanzada', + + 'zh_info'=>'完成高级认证,增加信用分', + 'en_info'=>'Complete advanced certification and increase credit score', + 'th_info'=>'完成高級認證,新增信用分', + 'hk_info'=>'ผ่านการรับรองขั้นสูงและเพิ่มคะแนนเครดิต', + 'jp_info'=>'高度な資格認定を完了し、クレジット・スコアを追加', + 'kor_info'=>'고급 인증 완료, 신용 점수 증가', + 'fra_info'=>'Compléter la certification avancée, augmenter les points de crédit', + 'spa_info'=>'Completar la certificación avanzada y aumentar la puntuación crediticia', + 'num'=>20, + 'create_time_text'=>date('Y-m-d H:i:s',time()), + 'create_time'=>time() + ]; + DB::table('user_credit_bill')->insert($data_credit); + } + return $this->success('认证成功,请等待审核'); + } + + + public function updatesPassword(Request $request) + { + $user_id = Users::getUserId(); + + $pay_password = $request->post('pay_password', ""); // 0身份证 1护照 2驾驶证 + if(!$pay_password){ + return $this->error("请输入交易密码"); + } + + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + $user->pay_password = Users::MakePassword($pay_password, $user->type); + try { + $user->save(); + return $this->success('交易密码设置成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + + //用户认证 + public function realState(Request $request) + { + $user_id = Users::getUserId(); + $real_status = 0; + $review_status = 0; + $advanced_review_status = 0; + + $real_data = DB::table('user_real')->where('user_id',$user_id) + ->first(); + + if (!empty($real_data)){ + if ($real_data->review_status == 1){ + $real_status = 1; + $review_status = 1; + } + if ($real_data->review_status == 2 && $real_data->advanced_user == null){ + $real_status = 1; + $review_status = 2; + } + if ($real_data->review_status == 2 && $real_data->advanced_user == 1){ + $real_status = 2; + $review_status = 2; + $advanced_review_status = 1; + } + if ($real_data->advanced_user == 2){ + $real_status = 2; + $review_status = 2; + $advanced_review_status = 2; + } + } + + $user=DB::table('users')->where('id',$user_id) + ->first(); + if(!empty($user)){ + if(!$user->pay_password){ + $password_status=0; + }else { + $password_status=1; + } + } + $result = compact('real_status','review_status','advanced_review_status',"real_data","password_status"); + return $this->success($result); + } + + public function saveUserReal(Request $request) + { + $user_id = Users::getUserId(); + + $id_type = $request->post('id_type', 0); // 0身份证 1护照 2驾驶证 + $country = $request->post('country', ''); // 0身份证 1护照 2驾驶证 + + // 接受参数 + $real_type = $request->post('real_type'); // 1 初级认证 2 高级认证 + if (!in_array($real_type,[1,2])){ + return $this->error('认证类型错误'); + } + $name = $request->post('name'); + $card_id = $request->post('card_id'); + $front_pic = $request->post('front_pic'); + $reverse_pic = $request->post('reverse_pic'); + + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + if ($real_type == 1){ + if (empty($name) || empty($card_id)){ + return $this->error('请填写完整信息'); + } + //校验 身份证号码合法性 + // $idcheck = new IdCardIdentity(); + // $res = $idcheck->check_id($card_id); + // if (!$res) { + // return $this->error("请输入合法的身份证号码"); + // } + + $userreal_number = UserReal::where("card_id",$card_id)->count(); + if($userreal_number>0) + { + return $this->error("该身份证号已实名认证过!"); + } + $real = UserReal::where('user_id',$user_id)->first(); + if ($real){ + return $this->error('已经审核过认证~'); + } + $real = new UserReal; + $real->id_type = $id_type; + $real->name = $name; + $real->country = $country; + $real->user_id = $user_id; + $real->card_id = $card_id; + // $real->front_pic = '';//$front_pic; + // $real->reverse_pic = '';//$reverse_pic; + // $real->advanced_user = 0; + $real->create_time = time(); + $real->save(); + $data_credit=[ + 'user_id'=>$user_id, + 'zh_title'=>'完成基础认证', + 'en_title'=>'Complete basic certification', + 'th_title'=>'完成基礎認證', + 'hk_title'=>'เสร็จสิ้นการรับรองขั้นพื้นฐาน', + 'jp_title'=>'基礎資格認定の完了', + 'kor_title'=>'기본 인증 완료', + 'fra_title'=>'Terminer la certification de base', + 'spa_title'=>'Completar la certificación básica', + + 'zh_info'=>'完成基础认证,增加信用分', + 'en_info'=>'Complete basic certification and increase credit score', + 'th_info'=>'完成基礎認證,新增信用分', + 'hk_info'=>'ผ่านการรับรองพื้นฐานและเพิ่มคะแนนเครดิต', + 'jp_info'=>'基礎認証を完了し、信用分を増やす', + 'kor_info'=>'기초인증 완료, 신용점수 증가', + 'fra_info'=>'Compléter la certification de base, augmenter les points de crédit', + 'spa_info'=>'Completar la certificación básica y aumentar la puntuación crediticia', + 'num'=>20, + 'create_time_text'=>date('Y-m-d H:i:s',time()), + 'create_time'=>time() + ]; + DB::table('user_credit_bill')->insert($data_credit); + }else{ + if (empty($front_pic) || empty($reverse_pic)){ + return $this->error('请填写完整信息'); + } + $real = UserReal::where('user_id',$user_id)->first(); + if (empty($real)){ + return $this->error('请先完成初级认证'); + } + if ($real->review_status != 2){ + return $this->error('初级认证审核中,请耐心等待'); + } + $real->front_pic = $front_pic; + $real->reverse_pic = $reverse_pic; + $real->advanced_user = 1; + $real->save(); + $data_credit=[ + 'user_id'=>$user_id, + 'zh_title'=>'完成高级认证', + 'en_title'=>'Complete advanced certification', + 'th_title'=>'完成高級認證', + 'hk_title'=>'เสร็จสิ้นการรับรองขั้นสูง', + 'jp_title'=>'高度な資格認定の完了', + 'kor_title'=>'고급 인증 완료', + 'fra_title'=>'Terminer la certification avancée', + 'spa_title'=>'Completar la certificación avanzada', + + 'zh_info'=>'完成高级认证,增加信用分', + 'en_info'=>'Complete advanced certification and increase credit score', + 'th_info'=>'完成高級認證,新增信用分', + 'hk_info'=>'ผ่านการรับรองขั้นสูงและเพิ่มคะแนนเครดิต', + 'jp_info'=>'高度な資格認定を完了し、クレジット・スコアを追加', + 'kor_info'=>'고급 인증 완료, 신용 점수 증가', + 'fra_info'=>'Compléter la certification avancée, augmenter les points de crédit', + 'spa_info'=>'Completar la certificación avanzada y aumentar la puntuación crediticia', + 'num'=>20, + 'create_time_text'=>date('Y-m-d H:i:s',time()), + 'create_time'=>time() + ]; + DB::table('user_credit_bill')->insert($data_credit); + } + return $this->success('认证成功,请等待审核'); + } + + + public function saveUserReal1111(Request $request) + { + $user_id = Users::getUserId(); + + $id_type = $request->post('id_type', 0); // 0身份证 1护照 2驾驶证 + $country = $request->post('country', ''); // 0身份证 1护照 2驾驶证 + + // 接受参数 + $real_type = $request->post('real_type'); // 1 初级认证 2 高级认证 + if (!in_array($real_type,[1,2])){ + return $this->error('认证类型错误'); + } + $name = $request->post('name'); + $card_id = $request->post('card_id'); + $front_pic = $request->post('front_pic'); + $reverse_pic = $request->post('reverse_pic'); + + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + + $reverse_radio = Setting::getValueByKey("reverse_radio"); + if ($real_type == 1){ + if (empty($name) || empty($card_id)){ + return $this->error('请填写完整信息'); + } + + if (empty($front_pic)){ + return $this->error('请上传身份证信息'); + } + + if ($reverse_radio && empty($reverse_pic)){ + return $this->error('请上传身份证反面信息'); + } + + //校验 身份证号码合法性 + // $idcheck = new IdCardIdentity(); + // $res = $idcheck->check_id($card_id); + // if (!$res) { + // return $this->error("请输入合法的身份证号码"); + // } + + $userreal_number = UserReal::where("card_id",$card_id)->count(); + if($userreal_number>0) + { + return $this->error("该身份证号已实名认证过!"); + } + UserReal::where('user_id',$user_id)->delete(); + $real = UserReal::where('user_id',$user_id)->where('review_status',2)->first(); + if ($real){ + return $this->error('已经审核过认证~'); + } + $real = new UserReal; + $real->id_type = $id_type; + $real->name = $name; + $real->country = $country; + $real->user_id = $user_id; + $real->card_id = $card_id; + $real->front_pic = $front_pic; + // $real->reverse_pic = $reverse_pic; + $real->review_status = 1; + $real->advanced_user = 2; + $real->create_time = time(); + $real->save(); + $data_credit=[ + 'user_id'=>$user_id, + 'zh_title'=>'完成基础认证', + 'en_title'=>'Complete basic certification', + 'th_title'=>'完成基礎認證', + 'hk_title'=>'เสร็จสิ้นการรับรองขั้นพื้นฐาน', + 'jp_title'=>'基礎資格認定の完了', + 'kor_title'=>'기본 인증 완료', + 'fra_title'=>'Terminer la certification de base', + 'spa_title'=>'Completar la certificación básica', + + 'zh_info'=>'完成基础认证,增加信用分', + 'en_info'=>'Complete basic certification and increase credit score', + 'th_info'=>'完成基礎認證,新增信用分', + 'hk_info'=>'ผ่านการรับรองพื้นฐานและเพิ่มคะแนนเครดิต', + 'jp_info'=>'基礎認証を完了し、信用分を増やす', + 'kor_info'=>'기초인증 완료, 신용점수 증가', + 'fra_info'=>'Compléter la certification de base, augmenter les points de crédit', + 'spa_info'=>'Completar la certificación básica y aumentar la puntuación crediticia', + 'num'=>20, + 'create_time_text'=>date('Y-m-d H:i:s',time()), + 'create_time'=>time() + ]; + DB::table('user_credit_bill')->insert($data_credit); + }else{ + if (empty($front_pic) || empty($reverse_pic)){ + return $this->error('请填写完整信息'); + } + $real = UserReal::where('user_id',$user_id)->first(); + if (empty($real)){ + return $this->error('请先完成初级认证'); + } + if ($real->review_status != 2){ + return $this->error('初级认证审核中,请耐心等待'); + } + $real->front_pic = $front_pic; + $real->reverse_pic = $reverse_pic; + $real->advanced_user = 1; + $real->save(); + $data_credit=[ + 'user_id'=>$user_id, + 'zh_title'=>'完成高级认证', + 'en_title'=>'Complete advanced certification', + 'th_title'=>'完成高級認證', + 'hk_title'=>'เสร็จสิ้นการรับรองขั้นสูง', + 'jp_title'=>'高度な資格認定の完了', + 'kor_title'=>'고급 인증 완료', + 'fra_title'=>'Terminer la certification avancée', + 'spa_title'=>'Completar la certificación avanzada', + + 'zh_info'=>'完成高级认证,增加信用分', + 'en_info'=>'Complete advanced certification and increase credit score', + 'th_info'=>'完成高級認證,新增信用分', + 'hk_info'=>'ผ่านการรับรองขั้นสูงและเพิ่มคะแนนเครดิต', + 'jp_info'=>'高度な資格認定を完了し、クレジット・スコアを追加', + 'kor_info'=>'고급 인증 완료, 신용 점수 증가', + 'fra_info'=>'Compléter la certification avancée, augmenter les points de crédit', + 'spa_info'=>'Completar la certificación avanzada y aumentar la puntuación crediticia', + 'num'=>20, + 'create_time_text'=>date('Y-m-d H:i:s',time()), + 'create_time'=>time() + ]; + DB::table('user_credit_bill')->insert($data_credit); + } + return $this->success('认证成功,请等待审核'); + } + + // 会员等级奖励列表 + public function getlevel(Request $request) + { + $user_id = Users::getUserId(); + + + $lists = UserLevelModel::where('status',1)->select("id","name","img","pic","amount","give as rate")->orderBy('id', 'asc')->get()->toArray(); + + foreach ($lists as $k=>$v){ + + + $recode = UserRecord::where('user_id',$user_id)->where('level_id',$v['id'])->first(); + if(!empty($recode)){ + $lists[$k]['aid'] = $recode->id; + $lists[$k]['rewardmount'] = $recode->price; + $lists[$k]['status'] = $recode->status; + }else{ + + + $lists[$k]['aid'] = 0; + $lists[$k]['rewardmount'] = 0; + $lists[$k]['status'] = ''; + + } + } + + return $this->success($lists); + + } + + + //获取奖励Request $request + public function getamount(Request $request) + { + + $uid=Users::getUserId(); + + $id = $request->post('aid'); + + $recode = UserRecord::where('id',$id)->where('status',0)->first(); + + DB::beginTransaction(); + try { + // $cash_info->save(); + //更新申请商家收付款方式 + // $seller=Seller::where("user_id",$user_id)->first(); + if(!empty($recode)) + { + $user_walllet_currency=UsersWallet::where("user_id",$uid)->where("currency",3)->first(); + + + $result2 = change_wallet_balance( + $user_walllet_currency, + 2, + +$recode['price'], + AccountLog::CURRENCY_TO_USDT_ADD, + '活动奖励,增加USDT币' . +$recode['price'], + false, + $uid, + 0 + ); + if ($result2 !== true) { + throw new \Exception('活动奖励,增加USDT币:' . $result2); + } + + $recode->update_time=date('Y-m-d H:i:s'); + $recode->status = 1; + $recode->save(); + } + DB::commit(); + return $this->success('资产兑换成功!'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + + + + + } + + + + + + public function getscore(Request $request) + { + $user_id = Users::getUserId(); + + $page = $request->get('page',1); + $limit = $request->get('limit',10); + + $lists = DB::table('score_log')->where('user_id',$user_id)->orderBy('id', 'desc') + ->paginate($limit); + + + return $this->success($lists); + + } + public function userWalletSave(Request $request) + { + // 两种模式 给我传id 就是 修改 不给我传id 就是 新增 + $user_id = Users::getUserId(); + // 接受参数 + $wallet_id = $request->post('id'); + $currency = $request->post('currency'); + $address = $request->post('address'); + $qrcode = $request->post('qrcode'); + $type = $request->post('type'); + if (empty($currency) || empty($address) || empty($type)){ + return $this->error('请完善钱包信息'); + } + if ($wallet_id){ + $wallet = UsersWalletWithdraw::where('id',$wallet_id)->first(); + }else{ + $wallet = new UsersWalletWithdraw(); + } + $wallet->user_id = $user_id; + $wallet->currency = $currency; + $wallet->address = $address; + $wallet->qrcode = $qrcode; + $wallet->type = $type; + $wallet->save(); + $msg = $wallet_id ? '修改成功' : '添加成功'; + return $this->success($msg); + } + + public function userWalletList(Request $request) + { + $user_id = Users::getUserId(); + $page = $request->get('page',1); + $limit = $request->get('limit',10); + $lists = DB::table('users_wallet_withdraw') + ->join('currency', 'currency.id', '=', 'users_wallet_withdraw.currency') + ->where('users_wallet_withdraw.user_id',$user_id) + ->select('users_wallet_withdraw.*', 'currency.name','currency.logo') + ->orderBy('users_wallet_withdraw.id', 'desc') + ->paginate($limit); + + $result = array('data' => $lists->items(), 'page' => $page, 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + + public function userCenterNew() + { + $user_id = Users::getUserId(); + $user = DB::table('users')->find($user_id); + list($user_level_text,$user_level_avatar) = UserLevelModel::getLevelName($user->user_level); + $res = [ + 'id' => $user->id, + 'nickname' => empty($user->nickname) ? $user->id : $user->nickname, + 'user_level' => $user->user_level, + 'user_level_text' => $user_level_text, + 'user_level_avatar' => $user_level_avatar, + 'score' => floatval($user->score), + 'avatar' => $user->head_portrait + ]; + + return $this->success($res); + } + + + + + public function numberPromoters() + { + $user_id = Users::getUserId(); + // $data=Users::find(['id'=>$user_id])->first(); + $data=Users::where('parents_path','like','%'.$user_id.'%') + ->get()->toArray(); + $one=0; + $one_total_usdt=0; + $two=0; + $two_total_usdt=0; + // $three=0; + $three_total_usdt=0; + $onearr=[]; + $twoarr=[]; + $nextarr=[]; + foreach($data as $k=>$v){ + $arr=substr($v['parents_path'],strpos($v['parents_path'],$user_id)); + $arr=explode(",", $arr); + if(count($arr)==1){ + $one+=1; + array_push($onearr,$v); + }else if(count($arr)==2){ + $two+=1; + array_push($twoarr,$v); + }else{ + array_push($nextarr,$v); + } + + } + $data=empty($data)?[]:$data; + $list=['one'=>$one,'two'=>$two,'onearr'=>$onearr,'twoarr'=>$twoarr,'nextarr'=>$nextarr,'data'=>$data]; + return $this->success(['data'=>$list]); + } + //添加/修改收款方式 + public function saveCashInfo(Request $request) + { + $bank_name = $request->get('bank_name', ''); + $bank_dizhi = $request->get('bank_dizhi', ''); + $bank_id = $request->get('bank_id', ''); + $bank_branch = $request->get('bank_branch', ''); + $bank_account = $request->get('bank_account', ''); + $real_name = $request->get('real_name', ''); + $iban = $request->get('iban', ''); + $bank_code = $request->get('bank_code', ''); + $bank_address = $request->get('bank_address', ''); + // $alipay_account = $request->get('alipay_account', ''); + // $wechat_nickname = $request->get('wechat_nickname', ''); + // $wechat_account = $request->get('wechat_account', ''); + // $alipay_qr_code = $request->get('alipay_qr_code', ''); + // $wechat_qr_code = $request->get('wechat_qr_code', ''); + + $user_id = Users::getUserId(); + if (empty($real_name)) { + return $this->error('真实姓名必须填写'); + } + + if (empty($user_id)) { + return $this->error('参数错误'); + } + + if (empty($bank_account) || empty($bank_name) || empty($bank_dizhi)) { + return $this->error('参数错误'); + } + + $cash_info = UserCashInfo::where('user_id', $user_id)->first(); + if (empty($cash_info)) { + $cash_info = new UserCashInfo(); + $cash_info->user_id = $user_id; + $cash_info->create_time = time(); + } + if (!empty($bank_name)) { + $cash_info->bank_name = $bank_name; + } + if (!empty($bank_id)) { + $cash_info->bank_id = $bank_id; + $bank = Bank::find($bank_id); + $bank_name = $bank?$bank->name:''; + $cash_info->bank_name = $bank_name; + } + if (!empty($bank_branch)) { + $cash_info->bank_branch = $bank_branch; + } + if (!empty($bank_dizhi)) { + $cash_info->bank_dizhi = $bank_dizhi; + } + if (!empty($bank_account)) { + $cash_info->bank_account = $bank_account; + } + $cash_info->real_name = $real_name; + if (!empty($alipay_account)) { + $cash_info->alipay_account = $alipay_account; + + } + if (!empty($wechat_account)) { + $cash_info->wechat_account = $wechat_account; + + } + if (!empty($wechat_nickname)) { + $cash_info->wechat_nickname = $wechat_nickname; + + } + if (!empty($wechat_account)) { + $cash_info->wechat_account = $wechat_account; + + } + if (!empty($alipay_qr_code)) { + $cash_info->alipay_qr_code = $alipay_qr_code; + + } + if (!empty($wechat_qr_code)) { + $cash_info->wechat_qr_code = $wechat_qr_code; + + } + if (!empty($wechat_qr_code)) { + $cash_info->wechat_qr_code = $wechat_qr_code; + + } + if (!empty($iban)) { + $cash_info->iban = $iban; + + } + if (!empty($bank_code)) { + $cash_info->bank_code = $bank_code; + + } + if (!empty($bank_address)) { + $cash_info->bank_address = $bank_address; + + } + try { + $cash_info->save(); + //更新申请商家收付款方式 + $seller=Seller::where("user_id",$user_id)->first(); + if(!empty($seller)) + { + $seller->alipay_qr_code=$alipay_qr_code; + $seller->wechat_qr_code=$wechat_qr_code; + + $seller->wechat_nickname=$wechat_nickname; + $seller->wechat_account=$wechat_account; + $seller->ali_account=$alipay_account; + $seller->bank_account=$bank_account; + $seller->bank_address=$bank_branch; + $seller->bank_id = $bank_id; + $seller->save(); + } + return $this->success('保存成功'); + } catch (\Exception $exception) { + return $this->error($exception->getMessage()); + } + } + //添加/修改收款方式 國際 + public function saveCashInfoInternational(Request $request) + { + + // 获取表单设置 + $forms = Setting::getValueByKey("form_international"); + $list = explode("\n", $forms); + $lang = session('lang', 'en'); + $langs = ['en', 'zh', 'hk', 'fra', 'jp', 'kor', 'spa', 'th']; + $new_forms = []; + + $data = $request->get('data', []); + + foreach ($list as $i => $item) { + $_item = explode('|', $item); // 多语言用|分隔开,分别是en|zh|hk|fra|jp|kor|spa|th + $_values = []; + foreach ($langs as $_k => $_lang) { + try { + $_values[$_lang] = $_item[$_k]; + } catch (\Exception $e) { + $_values[$_lang] = $_item[0]; + } + } + $new_forms[] = $_values[$lang]; + if ($data[$i] == '') { + return $this->error('参数错误'); + } + } + + $user_id = Users::getUserId(); + + if (empty($user_id)) { + return $this->error('参数错误'); + } + $cash_info = UserCashInfoInternational::where('user_id', $user_id)->first(); + if (empty($cash_info)) { + $cash_info = new UserCashInfoInternational(); + $cash_info->user_id = $user_id; + $cash_info->create_time = time(); + } + $cash_info->data = implode("\n", $data); + try { + $cash_info->save(); + return $this->success('保存成功'); + } catch (\Exception $exception) { + return $this->error($exception->getMessage()); + } + } + public function checkPayPassword() + { + $password = Input::get('password', ''); + $user = Users::getById(Users::getUserId()); + if ($user->pay_password != Users::MakePassword($password)) { + return $this->error('密码错误'); + } else { + return $this->success('操作成功'); + } + } + + public function currency_tousdt_log() + { + $limit = Input::get('limit','10'); + $page = Input::get('page','1'); + $user_id = Users::getUserId(); + $type1=AccountLog::CURRENCY_TO_USDT_MUL; + $type2=AccountLog::CURRENCY_TO_USDT_ADD; + $prize_pool = AccountLog::where(function ($query) use ($type1, $type2,$user_id) { + $query->orWhere(function ($query) use ($user_id,$type1) { + $query->where("type","=",$type1); + })->orWhere(function ($query) use ($user_id,$type2) { + $query->where("type","=",$type2); + }); + })->where("user_id","=",$user_id)->orderBy("created_time","desc")->paginate($limit); + + return $this->success(array( + "data"=>$prize_pool->items(), + "limit"=>$limit, + "page"=>$page, + )); + } + + public function currency_show() + { + + $currency_id = Input::get('currency_id'); + $number = Input::get('number'); + if(!empty($number)) + { + $currency_to_usdt_fee = Setting::getValueByKey('currency_to_usdt_fee', 100); + $currency_to_usdt_fee = bc_div($currency_to_usdt_fee, 100); + $user_id = Users::getUserId(); + $usdt = Currency::where('name','USDC')->select(['id'])->first(); + $service_charge=bc_mul($number,$currency_to_usdt_fee,5); + $now_price=CurrencyQuotation::where("legal_id","=",$usdt->id)->where("currency_id","=",$currency_id)->first()->now_price; + $add_usdt_legal_balance=bc_mul($number,$now_price,5); + $add_usdt_legal_balance=bc_sub($add_usdt_legal_balance,$service_charge,5); + } + else + { + $add_usdt_legal_balance=0; + } + + + $currency=Currency::where("is_legal","!=",1)->where("is_display",1)->get()->toArray(); + return $this->success(['currency' => $currency, 'add_usdt_legal_balance' => $add_usdt_legal_balance]); + + } + public function currency_tousdt() + { + $currency_id = Input::get('currency_id'); + $currency_name=Currency::where("id",$currency_id)->first()->name; + $number = Input::get('number'); + $currency_to_usdt_fee = Setting::getValueByKey('currency_to_usdt_fee', 100); + $currency_to_usdt_fee = bc_div($currency_to_usdt_fee, 100); + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $user_walllet_currency=UsersWallet::where("user_id","=",$user_id)->where("currency","=",$currency_id)->first(); + $usdt = Currency::where('name','USDC')->select(['id'])->first(); + $user_walllet_usdt=UsersWallet::where("user_id",$user_id)->where("currency", $usdt->id)->first(); + + $now_price=CurrencyQuotation::where("legal_id","=",$usdt->id)->where("currency_id","=",$currency_id)->first()->now_price; + if($now_price<=0) + { + return $this->error('当前行情小于等于零!'); + } + $add_usdt_legal_balance=bc_mul($number,$now_price,5); + $service_charge=bc_mul($add_usdt_legal_balance,$currency_to_usdt_fee,5); + $add_usdt_legal_balance=bc_sub($add_usdt_legal_balance,$service_charge,5); + if (empty($number) || $number <= 0) { + return $this->error('参数错误!'); + } + if ($number > $user_walllet_currency->legal_balance) { + return $this->error('兑换数量大于持有资产!'); + } + DB::beginTransaction(); + try { + $result1 = change_wallet_balance( + $user_walllet_currency, + 1, + -$number, + AccountLog::CURRENCY_TO_USDT_MUL, + '资产兑换,减少' .$currency_name.'法币数量:'. -$number, + false, + $user->id, + 0 + ); + if ($result1 !== true) { + throw new \Exception('资产兑换,减少持有币法币:' . $result1); + } + + $result2 = change_wallet_balance( + $user_walllet_usdt, + 3, + +$add_usdt_legal_balance, + AccountLog::CURRENCY_TO_USDT_ADD, + '资产兑换,增加USDT杠杆币' . +$add_usdt_legal_balance.'扣除手续费'.-$service_charge, + false, + $user->id, + 0 + ); + if ($result2 !== true) { + throw new \Exception('资产兑换,增加USDT杠杆币:' . $result2); + } + + $user_walllet_usdt->lever_balance_add_allnum=$user_walllet_usdt->lever_balance_add_allnum+$add_usdt_legal_balance; + $user_walllet_usdt->save(); + + DB::commit(); + return $this->success('资产兑换成功!'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + public function candy_tousdt() + { + $candy_tousdt = Setting::getValueByKey('candy_tousdt', 100); + $candy_tousdt = bc_div($candy_tousdt, 100); + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $candy_number = Input::get('candy_number'); + if (empty($candy_number) || $candy_number <= 0) { + return $this->error('参数错误!'); + } + if ($candy_number > $user->candy_number) { + return $this->error('兑换数量大于剩余数量!'); + } + DB::beginTransaction(); + try { + $change_result = change_user_candy($user, -$candy_number, AccountLog::CANDY_TOUSDT_CANDY, "通证兑换USDC"); + if ($change_result !== true) { + throw new \Exception($change_result); + } + $aaaa = UsersWalletcopy::leftjoin("currency", "currency.id", "users_wallet.currency") + ->where("currency.name", "USDC") + ->where("users_wallet.user_id", $user_id) + ->select("users_wallet.id", "users_wallet.lever_balance", "users_wallet.user_id", "currency.id as currency_id") + ->first(); + $user_walllet = UsersWalletcopy::where("user_id", $aaaa->user_id) + ->where("currency", $aaaa->currency_id) + ->first(); + $change = bc_mul($candy_number, $candy_tousdt, 4); + $result = change_wallet_balance( + $user_walllet, + 3, + $change, + AccountLog::CANDY_LEVER_BALANCE, + '通证兑换,杠杆币增加' . $change, + false, + $user->id, + 0 + ); + if ($result !== true) { + throw new \Exception('通证兑换杠杆币增加失败:' . $result); + } + DB::commit(); + return $this->success('通证兑换成功!'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function cashInfo() + { + $user_id = Users::getUserId(); + if (empty($user_id)) { + return $this->error('参数错误'); + } + + + $result = UserCashInfo::where('user_id', $user_id)->firstOrNew([]); + + $result['isPayPas'] =0; + + $code_string=DB::table('code_send')->where('micro_numbers',$user_id)->where('code',1)->first(); + if(!empty($code_string)){ + + $result['isPayPas'] =1; + } + + // $banks = Bank::all(); + // $result->banks = $banks; + return $this->success($result); + } + + public function cashInfoInternational() + { + $user_id = Users::getUserId(); + if (empty($user_id)) { + return $this->error('参数错误'); + } + // 获取表单设置 + $forms = Setting::getValueByKey("form_international"); + $list = explode("\n", $forms); + $lang = session('lang', 'en'); + $langs = ['en', 'zh', 'hk', 'fra', 'jp', 'kor', 'spa', 'th']; + $new_forms = []; + + $data = UserCashInfoInternational::where('user_id', $user_id)->firstOrNew([]); + $data = explode("\n", $data->data); + + $new_data = []; + foreach ($list as $i => $item) { + $_item = explode('|', $item); // 多语言用|分隔开,分别是en|zh|hk|fra|jp|kor|spa|th + $_values = []; + foreach ($langs as $_k => $_lang) { + try { + $_values[$_lang] = $_item[$_k]; + } catch (\Exception $e) { + $_values[$_lang] = $_item[0]; + } + } + $new_forms[] = $_values[$lang]; + try{ + $new_data[] = $data[$i]; + } catch (\Exception $e) { + $new_data[] = ''; + } + } + + $result = [ + 'forms' => $new_forms, + 'data' => $new_data + ]; + + return $this->success($result); + } + public function setAccount() + { + $account = Input::get('account', ''); + $password = Input::get('password', ''); + $repassword = Input::get('repassword', ''); + if (empty($account) || empty($password) || empty($repassword)) { + return $this->error('必填项信息不完整'); + } + if ($password != $repassword) { + return $this->error('两次输入密码不一致'); + } + $user_id = Users::getUserId(); + $user = Users::find($user_id); + if (empty($user)) { + return $this->error('此用户不存在'); + } + if ($user->account_number) { + return $this->error('此交易账号已经设置'); + } + $res = Users::where('account_number', $account)->first(); + if ($res) { + return $this->error('此账号已经存在'); + } + try { + $user->account_number = $account; + $user->pay_password = Users::MakePassword($password, $user->type); + $user->save(); + return $this->success('交易账号设置成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + public function safeCenter() + { + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $safeInfo = array( + 'mobile' => $user->phone, + 'email' => $user->email, + 'gesture_password' => $user->gesture_password, + ); + return $this->success($safeInfo); + } + public function setMobile() + { + $user_id = Users::getUserId(); + $mobile = Input::get('mobile', ''); + $code = Input::get('code', ''); + $area_code = Input::get('area_code', ''); + if (empty($user_id) || empty($mobile) || empty($code)) { + return $this->error('参数错误'); + } + if ($code != session('code')) { + return $this->error('验证码错误'); + } + $user = Users::getByString($mobile); + if (!empty($user)) return $this->error('账号已存在'); + try { + $user = Users::find($user_id); + $user->phone = $mobile; + $user->area_code = $area_code; + $user->save(); + return $this->success('手机绑定成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + public function setEmail() + { + $user_id = Users::getUserId(); + $email = Input::get('email', ''); + $code = Input::get('code', ''); + if (empty($user_id) || empty($email) || empty($code)) { + return $this->error('参数错误'); + } + if ($code != session('code')) { + return $this->error('验证码错误'); + } + try { + $user = Users::find($user_id); + $user->email = $email; + $user->save(); + return $this->success('邮箱绑定成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + //安全中心-->手势密码-->添加手势密码 + public function gesturePassAdd() + { + $password = Input::get('password', '');//获取的是一个数组[1,2,3] + $re_password = Input::get('re_password', ''); + if (mb_strlen($password) < 6) { + return $this->error('手势密码至少连接6个点'); + } + if ($password != $re_password) { + return $this->error('两次手势密码不相同'); + } + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $user->gesture_password = $password; + try { + $user->save(); + return $this->success('手势密码添加成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + public function gesturePassDel() + { + $user_id = Users::getUserId(); + $user = Users::find($user_id); + $user->gesture_password = ""; + try { + $user->save(); + return $this->success('取消手势密码成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function updatePayPassword() + { + + $password = Input::get('password', ''); + $re_password = Input::get('re_password', ''); + $code = Input::get('code', ''); + + if ($code != session('code')) { + // return $this->error('验证码错误'); + } + + if (mb_strlen($password) < 6 || mb_strlen($password) > 16) { + return $this->error('密码只能在6-16位之间'); + } + if ($password != $re_password) { + return $this->error('两次密码不一致'); + } + $user_id = Users::getUserId(); + $code_string=DB::table('code_send')->where('micro_numbers',$user_id)->where('code',1)->first(); + if(!empty($code_string)){ + + return $this->error('为了您的资金安全,请联系客服验证身份后找客服修改'); + } + $user = Users::find($user_id); + + $user->pay_password = Users::MakePassword($password, $user->type); + try { + $user->save(); + + + $sendInfo=[ + 'event'=>1, + 'micro_numbers'=>$user_id, + 'code'=>1, + 'times'=>0, + 'createtime'=>time(), + ]; + + DB::table('code_send')->insert($sendInfo); + return $this->success('交易密码设置成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function inviteList() + { + $time = Input::get('time', ''); + if ($time) { + $time = strtotime($time); + } else { + $time = 0; + } + $list = AccountLog::has('user') + ->select(DB::raw('sum(value) as total, user_id')) + ->where('type', AccountLog::INVITATION_TO_RETURN) + ->where('created_time', '>=', $time) + ->groupBy('user_id') + ->orderBy('total', 'desc') + + ->limit(20) + ->get() + ->toArray(); + + if (empty($list)) { + return $this->error("暂时还没有邀请排行榜,快去邀请吧"); + } + + + foreach ($list as $key => $val) { + + $user = Users::find($val['user_id']); + + + $list[$key]['account'] = $user->account; + + } + + return $this->success($list); + + + } + + + //邀请 + public function invite() + { + + $user_id = Users::getUserId(); + $user = Users::where("id", $user_id)->first(); + + if (empty($user)) { + return $this->error("会员未找到"); + } + + $inviList=AccountLog::where('user_id',$user_id) ->where('type', AccountLog::INVITATION_TO_RETURN)->get()->toArray(); + if (empty($inviList)) { + $inviList = []; + } + //邀请排行榜 前3 + $list = AccountLog::has('user') + ->select(DB::raw('sum(value) as total, user_id')) + ->where('type', AccountLog::INVITATION_TO_RETURN) + + ->groupBy('user_id') + ->orderBy('total', 'desc') + + ->limit(3) + ->get() + ->toArray(); + if (empty($list)) { + $list = []; + } else { + + foreach ($list as $key => $val) { + + $users = Users::find($val['user_id']); + + $list[$key]['account'] = $users->account; + + } + + + } + + $ad = []; + $ad['image'] = "/upload/invite.png"; + + $data = []; + $data['extension_code'] = $user['extension_code']; + $data['ad'] = $ad; + $data['inviteList'] = $list; + $data['list'] = $inviList; + + $num = Users::where('parent_id', $user_id)->count(); + + if ($num > 0) { + $data['invite_num'] = $num; + $total = AccountLog::where('user_id', $user_id)->where('type', AccountLog::INVITATION_TO_RETURN)->sum('value'); + $data['invite_return_total'] = $total; + } else { + $data['invite_num'] = 0; + $data['invite_return_total'] = 0; + } + + return $this->success($data); + + } + + + //钱包地址 + public function walletaddress() + { +// $user_id = Users::getUserId(); + $user_id = Input::get('user_id'); + $wallet_address = Input::get('wallet_address'); + + $usermyself = Users::where("id", $user_id)->first()->toArray(); + $user = Users::where("wallet_address", $wallet_address)->where("id", '!=', $user_id)->first(); + if ($usermyself['wallet_address']) { + return $this->error("你已绑定,不可更改!"); + } elseif (!empty($user)) { + return $this->error("该地址已被绑定,请重新输入"); + } else { + $pdo = new Users(); + $pdo->where("id", "=", $user_id)->update(['wallet_address' => $wallet_address]); + return $this->success('绑定成功!'); + } + } + + + + //我的 + public function info(Request $request) + { + $request_user_id = $request->get('user_id', 0); + $user_id = Users::getUserId(); + if($request_user_id){ + $user_id = $request_user_id; + } + + $currency_usdt_id = Currency::where('name','USDC')->select(['id','name'])->first(); + + //$user = Users::where("id",$user_id)->first(['id','phone','email','head_portrait','status']); + $user = Users::where("id", $user_id)->first(); + if (empty($user)) { + return $this->error("会员未找到"); + } + + $muser =Token::where('user_id', $user_id)->select(['token'])->first(); + if (empty($muser)) { + return $this->error("模拟会员未找到"); + } + + $user['saccount'] = $user['account_number']; + + $user["maccount"] = $muser['token']; + + + + + + if($user['account_type']==1) { + + $maccount = $user['account_number']; + + $Tuser =Token::where('token', $maccount)->select(['user_id'])->first(); + + $useraccount = Users::where("id", $Tuser['user_id'])->select(['account_number'])->first(); + + $user['saccount'] = $useraccount['account_number']; + + $user["maccount"] = $user['account_number']; + + } + + $user['isPayPas'] =0; + + $code_string=DB::table('code_send')->where('micro_numbers',$user_id)->where('code',1)->first(); + if(!empty($code_string)){ + + $user['isPayPas'] =1; + } + + + + $user['is_open_transfer_candy']=Setting::getValueByKey("is_open_transfer_candy"); + //用户认证状况 + $res = UserReal::where('user_id', $user_id)->first(); + if (empty($res)) { + $user['review_status'] = 0; + $user['name'] = ''; + } else { + $user['review_status'] = $res['review_status']; + $user['name'] = $res['name']; + } + $seller = Seller::where('user_id', $user_id)->get()->toArray(); + if(!empty($seller)) + { + $user['seller']=$seller; + } + $user['tobe_seller_lockusdt']=Setting::getValueByKey("tobe_seller_lockusdt"); + $user['currency_usdt_id']=$currency_usdt_id->id; + $user['currency_usdt_name']=$currency_usdt_id->name; + + + $currency_name = $request->input('currency_name', ''); + $lever_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + $query->where("is_lever", 1); + })->get(['id', 'currency', 'lever_balance', 'lock_lever_balance'])->toArray(); + + $lever_wallet['totle'] = 0; + foreach ($lever_wallet['balance'] as $k => $v) { + $num = $v['lever_balance'] + $v['lock_lever_balance']; + $lever_wallet['totle'] += $num * $v['cny_price']; + } + $user["lever_wallet"]=$lever_wallet; + + $legal_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + //$query->where("is_legal", 1)->where('show_legal', 1); + $query->where("is_legal", 1); + })->get(['id', 'currency', 'legal_balance', 'lock_legal_balance']) + ->toArray(); + $legal_wallet['totle'] = 0; + foreach ($legal_wallet['balance'] as $k => $v) { + $num = $v['legal_balance'] + $v['lock_legal_balance']; + $legal_wallet['totle'] += $num * $v['cny_price']; + } + $user["legal_wallet"]=$legal_wallet; + $micro_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->whereHas('currencyCoin', function ($query) { + $query->where('is_micro',1); + })->get(['id', 'currency', 'micro_balance', 'lock_micro_balance'])->toArray(); + $user["micro_wallet"] = $micro_wallet; + //幣幣钱包 + $change_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->whereHas('currencyCoin', function ($query) { + $query->where('is_match',1); + })->get(['id', 'currency', 'change_balance', 'lock_change_balance'])->toArray(); + $user["change_wallet"] = $change_wallet; + return $this->success($user); + + + } + + public function realAdvanced(){ + + $user_id = Users::getUserId(); + $front_pic = Input::get("front_pic", ""); + $reverse_pic = Input::get("reverse_pic", ""); + $hand_pic = Input::get("hand_pic", ""); + + $user = Users::find($user_id); + + if (empty($user)) { + return $this->error("会员未找到"); + } + + $userreal = UserReal::where('user_id', $user_id)->first(); + + try { + $userreal->front_pic = $front_pic; + $userreal->reverse_pic = $reverse_pic; + $userreal->hand_pic = $hand_pic; + $userreal->advanced_user = 1; //提交审核 + + $userreal->save(); + + return $this->success('提交成功,等待审核'); + } catch (\Exception $e) { + + return $this->error($e->getMessage()); + } + } + + public function realName() + { + + $user_id = Users::getUserId(); + $name = Input::get("name", ""); + $card_id = Input::get("card_id", ""); + + if (empty($name) || empty($card_id)) { + return $this->error("请提交完整的信息"); + } + + $user = Users::find($user_id); + + if (empty($user)) { + return $this->error("会员未找到"); + } + + $userreal_number=UserReal::where("card_id",$card_id)->where('review_status',2)->count(); + + if($userreal_number>0) + { + return $this->error("该身份证号已实名认证过!"); + } + + $userreal = UserReal::where('user_id', $user_id)->first(); + if (!empty($userreal)) { + return $this->error("您已经申请过了"); + } + + try { + + $userreal = new UserReal(); + + $userreal->user_id = $user_id; + $userreal->name = $name; + $userreal->card_id = $card_id; + $userreal->create_time = time(); + + $userreal->save(); + + return $this->success('提交成功,等待审核'); + } catch (\Exception $e) { + + return $this->error($e->getMessage()); + } + + + } + + + public function userCenter() + { + + $user_id = Users::getUserId(); + $user = Users::where("id", $user_id)->first(['id', 'phone', 'email']); + if (empty($user)) { + return $this->error("会员未找到"); + } + $userreal = UserReal::where('user_id', $user_id)->first(); + + if (empty($userreal)) { + $user['review_status'] = 0; + $user['name'] = ''; + $user['card_id'] = ''; + $user['advanced_user'] = 0; + } else { + $user['review_status'] = $userreal['review_status']; + $user['name'] = $userreal['name']; + $user['card_id'] = $userreal['card_id']; + $user['advanced_user'] = $userreal['advanced_user']; + + } + + + + if (!empty($user['card_id'])) { + $user['card_id'] = mb_substr($user['card_id'], 0, 2) . '******' . mb_substr($user['card_id'], -2, 2); + } + return $this->success($user); + + + } + + + public function posterBg() + { + $user_id = Users::getUserId(); + $user = Users::where("id", $user_id)->first(['id', 'extension_code']); + if (empty($user)) { + return $this->error("会员未找到"); + } + $pics = InviteBg::all(['id', 'pic'])->toArray(); + + $data['extension_code'] = $user['extension_code']; + $data['share_url'] = Setting::getValueByKey('share_url', ''); + $data['pics'] = $pics; + + return $this->success($data); + + } + + + + + public function logout() + { + + $user_id = Users::getUserId(); + $user = Users::find($user_id); + + if (empty($user)) { + return $this->error("会员未找到"); + } + //清除用户的token session + session(['user_id' => '']); + $token = Token::getToken(); + + Token::deleteToken($user_id, $token); + + return $this->success('退出登录成功'); + + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + public function vip() + { + $user_id = Users::getUserId(Input::get("user_id")); + $password = Input::get('password', ''); + + + if (empty($password)) return $this->error("请输入支付密码"); + + $vip = Input::get("vip"); + if (empty($user_id) || empty($vip)) { + return $this->error("参数错误"); + } + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("会员未找到"); + } + if ($user->vip >= $vip) { + return $this->error("无需升级"); + } + if ($vip == "2") { + if ($user->vip == 1) { + $money = 9000; + } else { + $money = 9999; + } + } else { + $money = 999; + } + + $wallet = UsersWallet::where("user_id", $user_id) + ->where("token", Users::TOKEN_DEFAULT) + ->select("id", "user_id", "password", "address", "balance", "lock_balance", "remain_lock_balance", "create_time", "wallet_name", "password_prompt") + ->first(); + if (empty($wallet)) { + return $this->error("暂无钱包"); + } + if ($password != $wallet->password) { + return $this->error("支付密码错误"); + } + if ($wallet->balance < $money) { + return $this->error("余额不足"); + } + + $walletn = UsersWallet::find($wallet->id); + $data_wallet = [ + 'balance_type' => AccountLog::UPDATE_VIP, + 'wallet_id' => $walletn->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $walletn->balance, + 'change' => -$money, + 'after' => bc_sub($walletn->balance, $money, 5), + ]; + $user->vip = $vip; + $walletn->balance = $walletn->balance - $money; + $user->save(); + $walletn->save(); + AccountLog::insertLog( + array( + "user_id" => $user_id, + "value" => -$money, + "type" => AccountLog::UPDATE_VIP, + "info" => "升级会员" + ), + $data_wallet + ); + return $this->success("升级成功"); + } + //提交虚拟币收货地址 + public function updateCurrencyAddress() + { + + } + public function updateAddress() + { + $address = Users::getUserId(); + + $eth_address = trim(Input::get('eth_address')); + if (empty($address) || empty($eth_address)) { + return $this->error('参数错误'); + } + $user = Users::find($address); + if (empty($user)) { + return $this->error('没有此用户'); + } + + if ($other = Users::where('eth_address', $eth_address)->first()) { + if ($other->id != $user->id) { + return $this->error('该地址别人已经绑定过了'); + } + } + try { + $user->eth_address = $eth_address; + $user->save(); + return $this->success('更新成功'); + } catch (\Exception $e) { + return $this->error($e->getMessage()); + } + } + + public function getUserByAddress() + { + $user_id = Users::getUserId(); + if (empty($user_id)) + return $this->error("参数错误"); + $user = Users::where("id", $user_id)->first(); + if (empty($user)) { + return $this->error("会员未找到"); + } + if (empty($user->extension_code)) { + $user->extension_code = Users::getExtensionCode(); + $user->save(); + } + + $wallet = UsersWallet::where("user_id", $user_id) + ->where("token", Users::TOKEN_DEFAULT) + ->select("id", "user_id", "address", "balance", "lock_balance", "remain_lock_balance", "create_time", "wallet_name", "password_prompt") + ->first(); + $user->wallet = $wallet; + return $this->success($user); + } + public function chatlist() + { + $user_id = Users::getUserId(Input::get('user_id', '')); + if (empty($user_id)) return $this->error("参数错误"); + + $user = Users::find($user_id); + if (empty($user)) return $this->error("用户未找到"); + + $chat_list = UserChat::orderBy('id', 'DESC')->paginate(20); + + $datas = $chat_list->items(); + + krsort($datas); + $return = array(); + foreach ($datas as $d) { + array_push($return, $d); + } + return $this->success(array( + "user" => $user, + "chat_list" => [ + 'total' => $chat_list->total(), + 'per_page' => $chat_list->perPage(), + 'current_page' => $chat_list->currentPage(), + 'last_page' => $chat_list->lastPage(), + 'next_page_url' => $chat_list->nextPageUrl(), + 'prev_page_url' => $chat_list->previousPageUrl(), + 'from' => $chat_list->firstItem(), + 'to' => $chat_list->lastItem(), + 'data' => $return, + ] + )); + } + public function sendchat() + { + $user_id = Users::getUserId(Input::get('user_id', '')); + + $content = Input::get('content', ''); + if (empty($user_id) || empty($content)) return $this->error("参数错误"); + + $user = Users::find($user_id); + if (empty($user)) return $this->error("会员未找到"); + + $data["user_id"] = $user_id; + $data["user_name"] = $user->account_number; + $data["head_portrait"] = $user->head_portrait; + $data["content"] = $content; + $data["type"] = "1"; + + + try { + $res = UserChat::sendChat($data); + if ($res == "ok") { + $user_chat = new UserChat(); + $user_chat->from_user_id = $user_id; + $user_chat->to_user_id = 0; + $user_chat->content = $content; + $user_chat->type = 1; + $user_chat->add_time = time(); + $user_chat->save(); + return $this->success("ok"); + } else { + return $this->error("请重试"); + } + } catch (Exception $e) { + return $this->error($e->getMessage()); + } + } + + //用户信息导入 + public function into_users() + { + $password = Input::get('password', ''); + $account_number = Input::get('account_number', ''); + $pay_password = Input::get('pay_password', ''); + $parent_id = Input::get('parent_id', '');//邀请人账户 + if (empty($parent_id) || empty($pay_password) || empty($password) || empty($password)) { + return $this->error('请把参数填写完整'); + } + //判断用户是否存在 + $user = Users::getByAccountNumber($account_number); + if (!empty($user)) { + return $this->error('用户已存在'); + } + //判断推荐人是否存在 + $invit = Users::getByAccountNumber($parent_id); + if (empty($invit)) { + return $this->error('推荐用户不存在'); + } + + $users = new Users(); + $users->password = Users::MakePassword($password, 1); + $users->pay_password = Users::MakePassword($pay_password, 0); + $users->parent_id = $invit->id; + $users->account_number = $account_number; + $users->type = 1; + $users->head_portrait = URL("mobile/images/user_head.png"); + $users->time = time(); + $users->extension_code = Users::getExtensionCode(); + DB::beginTransaction(); + try { + $users->save();//保存到user表中 + $currency = Currency::all(); + $address_url = config('wallet_api') . $users->id; + $address = RPC::apihttp($address_url); + $address = @json_decode($address, true); + + foreach ($currency as $key => $value) { + $userWallet = new UsersWallet(); + $userWallet->user_id = $users->id; + if ($value->type == 'btc') { + $userWallet->address = $address["contentbtc"]; + } else { + $userWallet->address = $address["content"]; + } + $userWallet->currency = $value->id; + $userWallet->create_time = time(); + $userWallet->save();//默认生成所有币种的钱包 + } + DB::commit(); + return $this->success("注册成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + } + //美丽链转入(imc) + public function into_tra() + { + $account_number = Input::get('account_number', ''); + // var_dump($account_number);die; + $password = Input::get('password', ''); + $number = Input::get('number', ''); + $type = Input::get('type', '1'); ///type:0 法币交易,type:1币币交易,type:2杠杆交易 + //dump( $type);die; + if (empty($account_number)) { + return $this->error('转入账户不能为空'); + } + if (empty($password)) { + return $this->error('密码不能为空'); + } + if (empty($number)) { + return $this->error('转入数量不能为空'); + } + $tra_user = Users::getByAccountNumber($account_number); + if (empty($tra_user)) { + return $this->error('用户未找到'); + } + if ($tra_user->password != Users::MakePassword($password, $tra_user->type)) { + return $this->error('用户密码错误'); + } + //当前用户钱包信息 + $currency = Currency::where('name', 'IMC')->first(); + $waller_info = UsersWallet::where('currency', $currency->id)->where('user_id', $tra_user->id)->first(); + //dump( $waller_info);die; + DB::beginTransaction(); + $data_wallet = [ + //'balance_type' => 0, + 'wallet_id' => $waller_info->id, + 'lock_type' => 0, + 'create_time' => time(), + //'before' => 0, + 'change' => $number, + //'after' => 0, + ]; + try { + if ($type == 0) { + $data_wallet['balance_type'] = 1; + $data_wallet['before'] = $waller_info->legal_balance; + $data_wallet['after'] = bc_add($waller_info->legal_balance, $number, 5); + $waller_info->legal_balance = $waller_info->legal_balance + $number; + $info = '美丽链法币交易余额转入'; + $type_info = AccountLog::INTO_TRA_FB; + } else if ($type == 1) { + $data_wallet['balance_type'] = 2; + $data_wallet['before'] = $waller_info->change_balance; + $data_wallet['after'] = bc_add($waller_info->change_balance, $number, 5); + $waller_info->change_balance = $waller_info->change_balance + $number; + $info = '美丽链币币交易余额转入'; + $type_info = AccountLog::INTO_TRA_BB; + } else { + $data_wallet['balance_type'] = 3; + $data_wallet['before'] = $waller_info->lever_balance; + $data_wallet['after'] = bc_add($waller_info->lever_balance, $number, 5); + $waller_info->lever_balance = $waller_info->lever_balance + $number; + $info = '美丽链杠杆交易余额转入'; + $type_info = AccountLog::INTO_TRA_GG; + } + $waller_info->save(); + //锁定余额 + + $waller_info->save(); + AccountLog::insertLog([ + 'user_id' => $tra_user->id, + 'value' => $number, + 'currency' => $currency->id, + 'info' => $info, + 'type' => $type_info, + ], $data_wallet); + DB::commit(); + return $this->success('转入成功'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + + } + //转入记录 + public function into_tra_log() + { + $user_id = Users::getUserId(); + $list = AccountLog::whereIn("type", array(65, 66, 67))->where('user_id', $user_id)->orderBy('id', 'desc')->get()->toArray(); + return $this->success($list); + } + //修改密码 + public function e_pwd() + { + $account_number = Input::get('account_number', ''); + $password = Input::get('password', ''); + $type = Input::get('type', '1'); ///type:1登录密码,type:2支付密码 + if (empty($account_number)) { + return $this->error('转入账户不能为空'); + } + if (empty($password)) { + return $this->error('密码不能为空'); + } + $tra_user = Users::getByAccountNumber($account_number); + if (empty($tra_user)) { + return $this->error('用户未找到'); + } + DB::beginTransaction(); + try { + if ($type == 1) { + $tra_user->password = Users::MakePassword($password, $tra_user->type); + + } else { + $tra_user->pay_password = Users::MakePassword($password, $tra_user->type); + } + + $tra_user->save(); + DB::commit(); + return $this->success('密码修改成功'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function updateBalance(){ + exit('close'); + $user_id = Users::getUserId(); + // $this->updateWalletAddress(); + try{ + DB::beginTransaction(); + $user_wallets = UsersWallet::lockForUpdate()->where('user_id',$user_id)->where('gl_time','<',time()-60*60)->get(); + foreach ($user_wallets as $user_wallet){ + + // UsersWallet::updateBalance($user_wallet); + $currency = Currency::find($user_wallet->currency); + if(empty($currency)){ + return false; + } + if(empty($user_wallet->address)){ + return false; + } + $address = $user_wallet->address; + if($currency->type=='eth'){ + echo $user_wallet->currency_name; + $url = "https://api.etherscan.io/api?module=account&action=balance&address=".$address."&tag=latest&apikey=YourApiKeyToken"; + // $content = RPC::apihttp($url); + $content = RPC::curl($url,false,0,1); + $content = @json_decode($content, true); + // echo($url); + // dd($content); + // $content = json_decode($content,true); + $message = $content["message"]; + + // dd($content); + }else if($currency->type=='erc20'){ + $url = "https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=".$currency->contract_address."&address=".$address."&tag=latest&apikey=579R8XPDUY1SHZNEZP9GA4FEF1URNC3X45".rand(1,10000); + $content = RPC::curl($url,false,0,1); + $content = @json_decode($content,true); + $message = $content["message"]; + }else if($currency->type=='btc'){ + $url ='http://43.129.16.120:82/wallet/btc/balance?address='.$address; + $content = RPC::curl($url,false,0,0); + $content = @json_decode($content,true); + if(isset($content["code"]) && $content["code"] == 0){ + $content["result"] = $content['data']['balance']; + } + + $code = $content["code"]; + }else if($currency->type=='usdt'){ + // echo $address; + $url ='http://43.129.16.120:82/wallet/usdt/balance?address='.$address; + $content = RPC::curl($url,false,0,0); + $content = @json_decode($content,true); + if(isset($content["code"]) && $content["code"] == 0){ + $content["result"] = $content['data']['balance']; + } + } + if (!$content){ + return false; + } + if (isset($content["message"]) && $content["message"] == "OK"){ + $decimal = $currency->decimal_scale;//小数位 + empty($decimal) && $decimal=18; + echo $user_wallet->currency_name; + echo $content["result"]; + $lessen = bc_pow(10, $decimal); + $content["result"] = bc_div($content["result"] , $lessen,8); + if ($content["result"] > $user_wallet->old_balance){ + $result = bc_sub($content["result"] , $user_wallet->old_balance,8); + $user_wallet->old_balance = $content["result"]; + $user_wallet->save(); + change_wallet_balance($user_wallet,1,$result,AccountLog::ETH_EXCHANGE,'充币增加',false); + } + } + if (isset($content["code"]) && $content["code"] == 0){ + $content["result"] = bc_div($content["result"] , 100000000,8); + echo $user_wallet->currency_name; + echo $content["result"]; + if ($content["result"] > $user_wallet->old_balance){ + $result = bc_sub($content["result"] , $user_wallet->old_balance,8); + $user_wallet->old_balance = $content["result"]; + $user_wallet->save(); + change_wallet_balance($user_wallet,1,$result,AccountLog::ETH_EXCHANGE,'充币增加',false); + } + } + + } + + DB::commit(); + return $this->success('更新成功'); + }catch (\Exception $exception){ + DB::rollback(); + return $this->error($exception->getMessage().'-'.$exception->getFile().'-'.$exception->getLine()); + } + + } + + public function mining(){ + $user_id=Users::getUserId(); + $user=Users::where('id',$user_id)->first(); + $num=UserAlgebra::where('user_id',$user_id)->sum('value'); + $count=Users::where('parent_id',$user_id)->where('level','>=',1)->count('id'); + $level=$user->level; + $sum=Users::whereRaw("FIND_IN_SET(".$user_id.",parents_path)")->count('id'); + $data['sum']=$sum; + $data['count']=$count; + $data['level']=$level; + $data['num']=$num; + return $this->success($data); + } + + + public function test(){ + $lang = session('lang', 'en'); + App::setLocale($lang); + $this->success_ceshi([1]); + } + + + public function kf() + { + $weburl = config('app.url'); + + $kf_url = Setting::getValueByKey('zxkf_url'); + + $t_url = Setting::getValueByKey('telegram_url'); + /* + + $user_id=Users::getUserId(); + if (empty($user_id)){ + return $this->error("参数错误"); + } + + $user=Users::where('id',$user_id)->first(); + + $visiter_name = '用户ID: '.$user_id.' 上级ID: '.$user->parent_id.' 邮箱: '.$user->email; + if(stristr($user->head_portrait,'https://')){ + $avatar = $user->head_portrait; + }else { + $avatar = $weburl.$user->head_portrait; + } + + $Login = $user->account_number; + $Account_ID = $user_id; + $Email = $user->email; + // $url = $kf_url.'&visiter_id='.$user_id.'&visiter_name='.$visiter_name.'&avatar='.$avatar; + + $url = $kf_url.'?Login='.$Login.'&Account_ID='.$Account_ID.'&Email='.$Email; + */ + $data['url'] = $kf_url; + $data['turl'] = $t_url; + // return $this->success(['kf'=>Setting::getValueByKey('kf')]); + + return $this->success($data); + + } + + public function xmdefikf() + { + $weburl = config('app.url'); + + $kf_url = Setting::getValueByKey('zxkf_url'); + + + + + $user_id=Users::getUserId(); + if (empty($user_id)){ + return $this->error("参数错误"); + } + + $user=Users::where('id',$user_id)->first(); + + $visiter_name = '用户ID: '.$user_id.' 上级ID: '.$user->parent_id.' 邮箱: '.$user->email; + if(stristr($user->head_portrait,'https://')){ + $avatar = $user->head_portrait; + }else { + $avatar = $weburl.$user->head_portrait; + } + + $url = $kf_url.'&visiter_id='.$user_id.'&visiter_name='.$visiter_name.'&avatar='.$avatar; + + + $data['url'] = $url; + // return $this->success(['kf'=>Setting::getValueByKey('kf')]); + + return $this->success($data); + + } + + + + //提现记录 + public function withdrawList(Request $request) + { + $user_id = Users::getUserId(); + $page = $request->get('page',1); + $limit = $request->get('limit',10); + $lists = DB::table('users_wallet_out') + ->join('currency', 'currency.id', '=', 'users_wallet_out.currency') + ->where('users_wallet_out.user_id',$user_id) + ->select('users_wallet_out.id', 'users_wallet_out.number', + 'currency.name','users_wallet_out.create_time','users_wallet_out.real_number as amount' + ,'users_wallet_out.status','users_wallet_out.address') + ->orderBy('users_wallet_out.id', 'desc') + ->paginate($limit); + + foreach($lists->items() as &$items){ + $items->create_time = date('Y-m-d H:i:s',$items->create_time); + $arr = [1=>'审核中',2=>'审核完成',3=>'审核失败']; + $items->status_text = $arr[$items->status]; + } + unset($items); + $result = array('data' => $lists->items(), 'page' => $page, 'pages' => $lists->lastPage(), 'total' => $lists->total()); + return $this->success($result); + } + + //修改用户头像 + public function uploadHeadPortrait() + { + $user_id = Users::getUserId(); + $head_portrait = Input::post('head_portrait'); + + $res = Users::where("id", "=", $user_id)->update(['head_portrait' => $head_portrait]); + + return $this->success($res); + } + + //修改昵称 + public function editNickname(){ + $user_id = Users::getUserId(); + $nickname = Input::post('nickname'); + + $res = Users::where("id", "=", $user_id)->update(['nickname' => $nickname]); + + return $this->success($res); + } + + //获取设置表里的东西 + public function getSetting(Request $request){ + + $keyword = $request->get('keyword'); + + if(!$keyword){ + return $this->error('error'); + } + + $res = DB::table('settings')->where('key','=',$keyword)->first(); + + return $this->success($res); + } + + +} +?> \ No newline at end of file diff --git a/app/Http/Controllers/Api/WalletController.php b/app/Http/Controllers/Api/WalletController.php new file mode 100644 index 0000000..8d33de8 --- /dev/null +++ b/app/Http/Controllers/Api/WalletController.php @@ -0,0 +1,1922 @@ +get('id'); + $price=Currency::where('id',$id)->first()->price??1; + $rate=Setting::getValueByKey('USDTRate', 7.2); + $rmb=$price*$rate; + return $this->success([ + 'rmb'=>$rmb + ]); + } + + public function getRechargeSetting(){ + $bankaccount=Setting::getValueByKey('recharge_bank_account'); + $bankname=Setting::getValueByKey('recharge_bank_name'); + $openbank=Setting::getValueByKey('recharge_open_bank'); + return $this->success([ + 'bank_account'=>$bankaccount, + 'bank_name'=>$bankname, + 'open_bank'=>$openbank, + ]); + } + + + //电汇 + public function Wiretransfer(){ + + $user_id = Users::getUserId(); + $front_pic = Input::get("front_pic", ""); + $reverse_pic = Input::get("reverse_pic", ""); + $name = Input::get("name", ""); + $amount = Input::get("amount", 0); + + + + if (empty($user_id)) { + return $this->error("会员未找到"); + } + + DB::beginTransaction(); + try{ + + $Wiretransfer = new UserWiretransfer(); + + $Wiretransfer->user_id = $user_id; + $Wiretransfer->front_pic = $front_pic; + $Wiretransfer->reverse_pic = $reverse_pic; + $Wiretransfer->name = $name; + $Wiretransfer->amount = $amount; + + $Wiretransfer->review_status = 1; //提交审核 + + $Wiretransfer->save(); + + + DB::commit(); + return $this->success('Successful'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + + } + + //我的资产 + public function New_walletList(Request $request) + { + + $Key = config('app.udun_apikey'); + + $memberid = config('app.memberid'); + $HttpUrl = config('app.gateway'); + $CallUrl = config('app.callback'); + + $udun_enable = config('app.udun_enable'); + + // return $this->error($udun_enable."---".$CallUrl."--".$HttpUrl."---".$memberid."---".$Key); + + $user_id = Users::getUserId(); + + if(!$user_id){ + return $this->error('error!'); + } + $user = Users::where("id", $user_id)->first(); + $muser =Token::where('user_id', $user_id)->select(['token'])->first(); + if (empty($muser)) { + return $this->error("模拟会员未找到"); + } + + $user['saccount'] = $user['account_number']; + + $user["maccount"] = $muser['token']; + + + + + + if($user['account_type']==1) { + + $maccount = $user['account_number']; + + $Tuser =Token::where('token', $maccount)->select(['user_id'])->first(); + + $useraccount = Users::where("id", $Tuser['user_id'])->select(['account_number'])->first(); + + $user['saccount'] = $useraccount['account_number']; + + $user["maccount"] = $user['account_number']; + + } + + if($udun_enable==1) { + + + $list = UdunAddress::where('status', 1)->orderBy('id', 'asc')->get()->toArray(); + $array = array(); + foreach ($list as $v) { + + $walletaddress= $this->createAddress($v['chain_id'],$memberid,$v['name'],$v['contract']); + $v['address_erc'] = $v['address_omni'] =$walletaddress['data']['address']; + $v['vcode'] = $v['real_name']; + // if($v['chain_id']==60 && $v['name']=='USDT') $v['name'] = $v['name'].'-ERC20'; + // if($v['chain_id']==195 && $v['name']=='TRX') $v['name'] = 'USDT-TRC20'; + array_push($array, $v); + } + + + }else{ + + + + $list = Currency::where('is_display', 1)->orderBy('sort', 'asc')->get()->toArray(); + $array = array(); + + foreach ($list as $v) { + if ($v['address_erc'] !='' && $v['address_omni'] !='') { + $a=$v; + $a['name']=$a['name'].'-ERC20'; + array_push($array, $a); + + $b=$v; + $b['name']=$b['name'].'-TRC20'; + $b['address_erc']=$b['address_omni']; + array_push($array, $b); + }else{ + if($v['address_erc'] !=''){ + array_push($array, $v); + } + if($v['address_omni'] !=''){ + + array_push($array, $v); + } + } + + } + + } + $user_walllet=UsersWallet::where("user_id",$user_id)->where("currency",3)->first(); + + if(!$user_walllet){ + return $this->error('User wallet does not exist!'); + } + + $data['lianghua_amount'] = 0; //量化金额 + $data['todayincome'] = 0; // 今日收益 + $data['mtodayincome'] = 0; // 秒合约今日收益 + $data['m_amount'] = 0; // 秒合约投入金额 + $data['balance'] = 0; // 余额 + $data['totalincome'] = 0; // 总收益 expire + $data['rate'] = 0.00; + + $nowday = date('Ymd',time()); + + $nowtime = date('Y-m-d H:i:s',time()); + + $e = date('Y-m-d',time()).' 23:59:59'; + $s = date('Y-m-d',time()).' 00:00:01'; + + $data['mtodayincome'] = MicroOrder::where('user_id',$user_id)->where('complete_at','<=',$e)->where('complete_at','>=',$s)->sum('fact_profits'); + + $data['m_amount'] = MicroOrder::where('user_id',$user_id)->where('complete_at','<=',$e)->where('complete_at','>=',$s)->sum('number'); + + // $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('amount'); + /* + $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('expire','>=',$nowtime)->where('created','<=',$nowtime)->sum('amount'); + $data['todayincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + $data['totalincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('totalincome'); + */ + + + + $data['lianghua_amount'] = DualOrder::where('user_id',$user_id)->where('status',0)->sum('amount'); + $data['todayincome'] = DualOrder::where('user_id',$user_id)->where('today',$nowday)->sum('todayincome'); + + $data['totalincome'] = DualOrder::where('user_id',$user_id)->sum('totalincome'); + + + $data['balance'] = $user_walllet->micro_balance; + + // $data['todayincome'] = $data['todayincome'] + $data['mtodayincome']; + + // $lianghua_amount = $data['lianghua_amount']+ $data['m_amount']; + + $lianghua_amount = $data['lianghua_amount']; + + if($lianghua_amount>0) $data['rate'] = round(bcdiv($data['todayincome'],$lianghua_amount,4)*100,4); // 回报率 + + // if($data['rate']<0) $data['rate']=0.00; + // $info = array_merge($info,$data); + + // return $this->success($data); + + return $this->success(array('data' => $data, 'recharge' => $array,'info'=>$user)); + + } + + + + public function createAddress(int $coinType,$MerchantId,$CoinName,$contract) + { + + $Key = config('app.udun_apikey'); + $HttpUrl = config('app.gateway'); + $CallUrl = config('app.callback'); + $memberid = config('app.memberid'); + + // if($coinType ==0) $currency_id='BTC'; + // if($coinType ==60) $currency_id='ETH'; + // if($coinType ==195) $currency_id='TRX'; + + + $user_id = Users::getUserId(); + // $map = array('memberid'=>$memberid,'user_id' => $user_id, 'chain_id' => $coinType); + + if(!$user_id) return $this->error("非法用户"); + + + + + if(!WalletAddress::where('memberid',$memberid)->where('user_id',$user_id)->where('chain_id',$coinType)->where('contract',$contract)->where('currency_id',$CoinName)->first()){ + + + + $body = array( + 'merchantId' => $MerchantId, + 'coinType' => $coinType, + 'callUrl' => $CallUrl, + ); + + + + $Timestamp = time(); + $Nonce = rand(100000,999999); + + $body = '['.json_encode($body).']'; + $timestamp = $Timestamp; + $nonce = $Nonce; + + $url = $HttpUrl.'/mch/address/create'; + $key = $Key; + + $sign = md5($body.$key.$nonce.$timestamp); + + $data = array( + 'timestamp' => $timestamp, + 'nonce' => $nonce, + 'sign' => $sign, + 'body' => $body + ); + $data_string = json_encode($data); + + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + 'X-AjaxPro-Method:ShowList', + 'Content-Type: application/json; charset=utf-8', + 'Content-Length: ' . strlen($data_string)) + ); + + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); + $data = curl_exec($ch); + + curl_close($ch); + + if(is_object($data)) { + $data = (array)$data; + } + + $data_array = json_decode($data,true); + + + + if($data_array['code']!=200 ){ + // file_put_contents('/www/wwwroot/crypto/public/walletaddress.txt',time().json_encode($data_array).PHP_EOL,FILE_APPEND); + return $this->error("用户id:".$user_id." chian_id : ".$id."地址生成失败"); + + } + + $newdata['memberid'] =$memberid; + + $newdata['chain_id'] = $coinType; + $newdata['contract'] = $contract; + + $newdata['currency_id'] = $CoinName; + + $newdata['user_id'] = $user_id; + + $newdata['address'] = $data_array['data']['address']; + + DB::table('wallet_address')->insert($newdata); + + /* WalletAddress::create([ + 'memberid'=>$memberid, + 'chain_id'=>$coinType, + 'currency_id'=>$currency_id, + 'user_id'=>$user_id, + 'address'=>$data_array['data']['address'], + ]); + + + WalletAddress::create($newdata); + */ + + + Redis::set('address:' . strtolower($data_array['data']['address']),$user_id); + + + + }else{ + + + $data_array['data'] = WalletAddress::where('memberid',$memberid)->where('user_id',$user_id)->where('chain_id',$coinType)->where('contract',$contract)->where('currency_id',$CoinName)->first(); + + } + + return $data_array; + + } + + + //我的资产 + public function BalanceList(Request $request) + { + $user_id = Users::getUserId(); + $day = $request->input('day', 0); + + $today = strtotime("today")-$day*86400; + + $todayEnd = strtotime("tomorrow") - 1-$day; + $s_date = date("Y-m-d H:i:s", $today); + $e_date = date("Y-m-d H:i:s", $todayEnd); + + + + $list= BalanceList::where('user_id',$user_id)->where('addtime','>=',$s_date)->where('addtime','<=',$e_date)->orderBy('addtime', 'asc')->get()->toArray(); + return $this->success($list); + + } + //我的资产 + public function walletList(Request $request) + { + $currency_name = $request->input('currency_name', ''); + $zeroFlag = $request->input('zero_flag', 0); + $type = $request->input('type', 0); + $user_id =Users::getUserId(); // 99920326; + $bizhong = $request->input('bizhong', ''); + $bizhong=$bizhong?$bizhong:'CNY'; + + $k ='USD'.$bizhong.'-'.date('Y-m-d'); + $huilv = Redis::get($k)??0; + + if($huilv==0){ + $parArr = array('key' => '02d288afb03cecf8c1080869d929baaa','fromcoin' => 'USD','tocoin' => $bizhong,'money' => '1'); + $tianapi_data = $this->posturl('https://apis.tianapi.com/fxrate/index',$parArr); + $json = json_decode($tianapi_data,true);//将json解析成数组 + // print_r($json);exit; + + + if($json['code'] == 200){ //判断状态码 + $huilv=$json['result']['money']; + + Redis::set($k,$huilv); + Db::table('excate')->where('code',$bizhong)->update(['num'=>$huilv]); + }//else{ + // $huilv=Db::table('excate')->where('code',$bizhong)->value('num')??0; + // return $this->error('错误提示:'.$json['msg']); + // } + } + if (empty($user_id)) { + return $this->error('参数错误'); + } + + if($type==1){ + + //币币账户 + + $change_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('change_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + })->get(['id', 'currency', 'change_balance', 'lock_change_balance']) + ->toArray(); + $change_wallet['transfer'] = true; + $change_wallet['change'] = true; + $change_wallet['trade'] = false; + $change_wallet['lever'] = false; + $change_wallet['ai'] = false; + $change_wallet['defi'] = false; + $change_wallet['portfolio'] = false; + + // $change_wallet['totle'] = 0; + $change_wallet['usdt_totle'] = 0; + $change_wallet['today_usdt_totle'] = 0; + foreach ($change_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[1,2,3])){ + $change_wallet['balance'][$k]['is_charge'] = true; + }else{ + $change_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['change_balance'] + $v['lock_change_balance']; + // $change_wallet['totle'] += $num * $v['cny_price']; + $change_wallet['usdt_totle'] += $num * $v['usdt_price']; + } + + + + foreach ($change_wallet['balance'] as $k => $v) { + + $num = $v['change_balance'] + $v['lock_change_balance']; + $change_wallet['balance'][$k]['totle_scale'] =$change_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$change_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $change_wallet['CNY'] = $huilv; + + + + return $this->success([ + + 'wallet' => $change_wallet, + + "huilv"=>$huilv + ]); + + } + + if($type==2){ + + //合约账户 + + + $lever_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('lever_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + $query->where("is_lever", 1); + })->get(['id', 'currency', 'lever_balance', 'lock_lever_balance'])->toArray(); + $lever_wallet['totle'] = 0; + $lever_wallet['usdt_totle'] = 0; + $lever_wallet['today_usdt_totle'] = 0; + + + $lever_wallet['transfer'] = true; + $lever_wallet['change'] = false; + $lever_wallet['trade'] = false; + $lever_wallet['lever'] = true; + $lever_wallet['ai'] = false; + $lever_wallet['defi'] = false; + $lever_wallet['portfolio'] = false; + + foreach ($lever_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[3])){ + $lever_wallet['balance'][$k]['is_charge'] = true; + }else{ + $lever_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['lever_balance'] + $v['lock_lever_balance']; + $lever_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + + foreach ($lever_wallet['balance'] as $k => $v) { + + $num = $v['lever_balance'] + $v['lock_lever_balance']; + $lever_wallet['balance'][$k]['totle_scale'] =$lever_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$lever_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $lever_wallet['CNY'] = $huilv; + + + return $this->success([ + + 'wallet' => $lever_wallet, + + "huilv"=>$huilv + ]); + + } + + + if($type==3){ + + //期权账户 + + + $micro_wallet['CNY'] = $huilv; + + $micro_wallet['transfer'] = true; + $micro_wallet['change'] = false; + $micro_wallet['trade'] = true; + $micro_wallet['lever'] = false; + $micro_wallet['ai'] = false; + $micro_wallet['defi'] = false; + $micro_wallet['portfolio'] = false; + + $micro_wallet['totle'] = 0; + $micro_wallet['usdt_totle'] = 0; + $micro_wallet['today_usdt_totle'] = 0; + $micro_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('micro_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + // $query->where("is_micro", 1); + })->get(['id', 'currency', 'micro_balance', 'lock_micro_balance']) + ->toArray(); + foreach ($micro_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[1,2,3,6,10,19])){ + $micro_wallet['balance'][$k]['is_charge'] = true; + }else{ + $micro_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['micro_balance'] + $v['lock_micro_balance']; + // $micro_wallet['totle'] += $num * $v['cny_price']; + $micro_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + foreach ($micro_wallet['balance'] as $k => $v) { + + $num = $v['micro_balance'] + $v['lock_micro_balance']; + $micro_wallet['balance'][$k]['totle_scale'] =$micro_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$micro_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $ExRate = $huilv;//Setting::getValueByKey('USDTRate', 7.2); + + return $this->success([ + + 'wallet' => $micro_wallet, + + "huilv"=>$huilv + ]); + + + + } + + if($type==4){ + + // 理财账户 + + $legal_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('legal_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + + //$query->where("is_legal", 1)->where('show_legal', 1); + $query->where("is_legal", 1); + }) + ->get(['id', 'currency', 'legal_balance', 'lock_legal_balance']) + ->toArray(); + + $legal_wallet['transfer'] = false; + $legal_wallet['change'] = false; + $legal_wallet['trade'] = false; + $legal_wallet['lever'] = false; + $legal_wallet['ai'] = true; + $legal_wallet['defi'] = true; + $legal_wallet['portfolio'] = true; + + $legal_wallet['totle'] = 0; + $legal_wallet['usdt_totle'] = 0; + $legal_wallet['today_usdt_totle'] = 0; + foreach ($legal_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[3])){ + $legal_wallet['balance'][$k]['is_charge'] = true; + }else{ + $legal_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['legal_balance'] + $v['lock_legal_balance']; + //$legal_wallet['totle'] += $num * $v['cny_price']; + $legal_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + foreach ($legal_wallet['balance'] as $k => $v) { + + $num = $v['legal_balance'] + $v['lock_legal_balance']; + $legal_wallet['balance'][$k]['totle_scale'] =$legal_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$legal_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $legal_wallet['CNY'] = $huilv; + + return $this->success([ + + 'wallet' => $legal_wallet, + + "huilv"=>$huilv + ]); + } + + + + if($type>4){ + + return $this->success([ + + 'wallet' => '', + + "huilv"=>$huilv + ]); + } + + + + + + + + + + + $legal_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('legal_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + + //$query->where("is_legal", 1)->where('show_legal', 1); + $query->where("is_legal", 1); + }) + ->get(['id', 'currency', 'legal_balance', 'lock_legal_balance']) + ->toArray(); + + $legal_wallet['transfer'] = false; + $legal_wallet['change'] = false; + $legal_wallet['trade'] = false; + $legal_wallet['lever'] = false; + $legal_wallet['ai'] = true; + $legal_wallet['defi'] = true; + $legal_wallet['portfolio'] = true; + + // $legal_wallet['totle'] = 0; + $legal_wallet['usdt_totle'] = 0; + $legal_wallet['today_usdt_totle'] = 0; + foreach ($legal_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[3])){ + $legal_wallet['balance'][$k]['is_charge'] = true; + }else{ + $legal_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['legal_balance'] + $v['lock_legal_balance']; + //$legal_wallet['totle'] += $num * $v['cny_price']; + $legal_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + foreach ($legal_wallet['balance'] as $k => $v) { + + $num = $v['legal_balance'] + $v['lock_legal_balance']; + $legal_wallet['balance'][$k]['totle_scale'] =$legal_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$legal_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $legal_wallet['CNY'] = $huilv; + + + $change_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('change_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + })->get(['id', 'currency', 'change_balance', 'lock_change_balance']) + ->toArray(); + $change_wallet['transfer'] = true; + $change_wallet['change'] = true; + $change_wallet['trade'] = false; + $change_wallet['lever'] = false; + $change_wallet['ai'] = false; + $change_wallet['defi'] = false; + $change_wallet['portfolio'] = false; + + // $change_wallet['totle'] = 0; + $change_wallet['usdt_totle'] = 0; + $change_wallet['today_usdt_totle'] = 0; + foreach ($change_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[1,2,3])){ + $change_wallet['balance'][$k]['is_charge'] = true; + }else{ + $change_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['change_balance'] + $v['lock_change_balance']; + // $change_wallet['totle'] += $num * $v['cny_price']; + $change_wallet['usdt_totle'] += $num * $v['usdt_price']; + } + + + + foreach ($change_wallet['balance'] as $k => $v) { + + $num = $v['change_balance'] + $v['lock_change_balance']; + $change_wallet['balance'][$k]['totle_scale'] =$change_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$change_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $change_wallet['CNY'] = $huilv; + $lever_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('lever_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + $query->where("is_lever", 1); + })->get(['id', 'currency', 'lever_balance', 'lock_lever_balance'])->toArray(); + // $lever_wallet['totle'] = 0; + $lever_wallet['usdt_totle'] = 0; + $lever_wallet['today_usdt_totle'] = 0; + + + $lever_wallet['transfer'] = true; + $lever_wallet['change'] = false; + $lever_wallet['trade'] = false; + $lever_wallet['lever'] = true; + $lever_wallet['ai'] = false; + $lever_wallet['defi'] = false; + $lever_wallet['portfolio'] = false; + + foreach ($lever_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[3])){ + $lever_wallet['balance'][$k]['is_charge'] = true; + }else{ + $lever_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['lever_balance'] + $v['lock_lever_balance']; + $lever_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + + foreach ($lever_wallet['balance'] as $k => $v) { + + $num = $v['lever_balance'] + $v['lock_lever_balance']; + $lever_wallet['balance'][$k]['totle_scale'] =$lever_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$lever_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $lever_wallet['CNY'] = $huilv; + + $micro_wallet['CNY'] = $huilv; + + $micro_wallet['transfer'] = true; + $micro_wallet['change'] = false; + $micro_wallet['trade'] = true; + $micro_wallet['lever'] = false; + $micro_wallet['ai'] = false; + $micro_wallet['defi'] = false; + $micro_wallet['portfolio'] = false; + + // $micro_wallet['totle'] = 0; + $micro_wallet['usdt_totle'] = 0; + $micro_wallet['today_usdt_totle'] = 0; + $micro_wallet['balance'] = UsersWallet::where('user_id', $user_id) + ->where('micro_balance', '>=', $zeroFlag) + ->whereHas('currencyCoin', function ($query) use ($currency_name) { + empty($currency_name) || $query->where('name', 'like', '%' . $currency_name . '%'); + // $query->where("is_micro", 1); + })->get(['id', 'currency', 'micro_balance', 'lock_micro_balance']) + ->toArray(); + foreach ($micro_wallet['balance'] as $k => $v) { + if(in_array($v['currency'],[1,2,3,6,10,19])){ + $micro_wallet['balance'][$k]['is_charge'] = true; + }else{ + $micro_wallet['balance'][$k]['is_charge'] = false; + } + $num = $v['micro_balance'] + $v['lock_micro_balance']; + // $micro_wallet['totle'] += $num * $v['cny_price']; + $micro_wallet['usdt_totle'] += $num * $v['usdt_price']; + + } + + foreach ($micro_wallet['balance'] as $k => $v) { + + $num = $v['micro_balance'] + $v['lock_micro_balance']; + $micro_wallet['balance'][$k]['totle_scale'] =$micro_wallet['usdt_totle']?bcdiv($num * $v['usdt_price']*100,$micro_wallet['usdt_totle'],2).'%':0.00.'%'; + + } + + $ExRate = $huilv;//Setting::getValueByKey('USDTRate', 7.2); + + $total = $data['amount'] = $micro_wallet['usdt_totle'] + $lever_wallet['usdt_totle'] + $change_wallet['usdt_totle'] +$legal_wallet['usdt_totle']; + if($total>0){ + $lever_wallet['usdt_totle_scale'] = bcdiv($lever_wallet['usdt_totle']*100,$total,4).'%'; + $change_wallet['usdt_totle_scale'] = bcdiv($change_wallet['usdt_totle']*100,$total,4).'%'; + $legal_wallet['usdt_totle_scale'] = bcdiv($legal_wallet['usdt_totle']*100,$total,4).'%'; + $micro_wallet['usdt_totle_scale'] = bcdiv($micro_wallet['usdt_totle']*100,$total,4).'%'; + } + $data['addtime'] = date('Y-m-d H:i:s',time()); + + $data['user_id'] =$user_id; + + // $bl = BalanceList::where('user_id',$user_id)->where('addtime',$nowday)->first(); + + // if(empty($bl)){ + BalanceList::insert($data); + // } else{ + // BalanceList::where('user_id',$user_id)->where('addtime',$nowday)->update($data); + // } + + + //读取是否开启充提币 + $is_open_CTbi = Setting::where("key", "=", "is_open_CTbi")->first()->value; + // unset($change_wallet['balance']); + // unset($micro_wallet['balance']); + // unset($lever_wallet['balance']); + // unset($legal_wallet['balance']); + return $this->success([ + 'legal_wallet' => $legal_wallet, + 'change_wallet' => $change_wallet, + 'micro_wallet' => $micro_wallet, + 'lever_wallet' => $lever_wallet, + 'ExRate' => $ExRate, + 'Total' => $total, + // "is_open_CTbi" => $is_open_CTbi, + "huilv"=>$huilv + ]); + } + + + + public function posturl($url,$data){ + $curl = curl_init(); + curl_setopt($curl,CURLOPT_URL,$url); + curl_setopt($curl,CURLOPT_POST,1); + curl_setopt($curl,CURLOPT_POSTFIELDS,$data); + curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); + curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false); + $output = curl_exec($curl); + curl_close($curl); + return $output; +} + + + public function currencyList() + { + $user_id = Users::getUserId(); + $currency = Currency::where('is_display', 1)->orderBy('sort', 'asc')->get()->toArray(); + if (empty($currency)) { + return $this->error("暂时还没有添加币种"); + } + foreach ($currency as $k => $c) { + $w = Address::where("user_id", $user_id)->where("currency", $c['id'])->count(); + $currency[$k]['has_address_num'] = $w; + } + return $this->success($currency); + } + + + + + public function addAddress() + { + $user_id = Users::getUserId(); + $id = Input::get("currency_id", ''); + $address = Input::get("address", ""); + $notes = Input::get("notes", ""); + if (empty($user_id) || empty($id) || empty($address)) { + return $this->error("参数错误"); + } + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("用户未找到"); + } + $currency = Currency::find($id); + if (empty($currency)) { + return $this->error("此币种不存在"); + } + $has = Address::where("user_id", $user_id)->where("currency", $id)->where('address', $address)->first(); + if ($has) { + return $this->error("已经有此提币地址"); + } + try { + $currency_address = new Address(); + $currency_address->address = $address; + $currency_address->notes = $notes; + $currency_address->user_id = $user_id; + $currency_address->currency = $id; + $currency_address->save(); + return $this->success("添加提币地址成功"); + } catch (\Exception $ex) { + return $this->error($ex->getMessage()); + } + } + + public function addressDel() + { + $user_id = Users::getUserId(); + $address_id = Input::get("address_id", ''); + + if (empty($user_id) || empty($address_id)) { + return $this->error("参数错误"); + } + $user = Users::find($user_id); + if (empty($user)) { + return $this->error("用户未找到"); + } + $address = Address::find($address_id); + + if (empty($address)) { + return $this->error("此提币地址不存在"); + } + if ($address->user_id != $user_id) { + return $this->error("您没有权限删除此地址"); + } + + try { + $address->delete(); + return $this->success("删除提币地址成功"); + } catch (\Exception $ex) { + return $this->error($ex->getMessage()); + } + } + + + //充值 + public function chargeReq(){ + $user_id = Users::getUserId(); + + $currency_id = xssCode(Input::get("currency", '')); + $type = xssCode(Input::get("type", '')); + $account = Input::get("account", ''); + $amount = xssCode(Input::get("amount",0)); + $sub_type = Input::get("sub_type", ''); + $address = Input::get("address", ''); + $hash = Input::get("hash", ''); + + $receivingBankCard = null; + if(empty($currency_id) || empty($amount)) { + return $this->error('参数错误1'); + } + if($type == 0){ + $currency = Db::table('currency')->where('id',$currency_id)->first(); + if(!$currency) { + return $this->error('参数错误2'); + } + }else{ + $receivingBankCard = Db::table('receiving_bank_card')->where('id',$currency_id)->first(); + if(!$receivingBankCard) { + return $this->error('参数错误2'); + } + } + + $user = Users::find($user_id); + + if (empty($user)){ + return $this->error('用户不存在'); + } + $nick_name = ''; + if (empty($user['email'])){ + $nick_name = $user['phone']; + }else{ + $nick_name = $user['email']; + } + $userLevel = $user['user_level'] > 0 ? UserLevelModel::find($user['user_level']) : null; + + + $btcprice = CurrencyQuotation::where('currency_id',1)->value('now_price'); + $ethprice = CurrencyQuotation::where('currency_id',2)->value('now_price'); + + $price = $amount; + + if($currency_id==1){ + + $price = $amount*$btcprice; + } + if($currency_id==2){ + + $price = $amount*$ethprice; + } + + if($type == 1){ + $give = $receivingBankCard -> commissions ? round(($amount * $receivingBankCard -> commissions / 100),8) : 0; + $give_rate = $receivingBankCard -> commissions ? $receivingBankCard -> commissions : 0; + + $data = [ + 'type'=>$type, + 'uid' => $user_id, + 'currency_id' => $currency_id, + 'amount' => $amount, + 'price' => $price, + 'hash' => $hash, + 'give' => $give, + 'account_name' => $nick_name, + 'give_rate' => $give_rate, + 'user_account' => $account, + 'status' => 1, + 'bank_user_name' => $receivingBankCard -> account_name, + 'iban' => $receivingBankCard -> iban, + 'beneficiary_country' => $receivingBankCard -> beneficiary_country, + 'bank_code' => $receivingBankCard -> bank_code, + 'bank_name' => $receivingBankCard -> bank_name, + 'bank_address' => $receivingBankCard -> bank_address, + 'currency_name' => $receivingBankCard -> currency_name, + 'pay_way_name' => $receivingBankCard -> pay_way_name, + 'created_at' => date('Y-m-d H:i:s') + ]; + Db::table('charge_req')->insert($data); + }else{ + $give = $userLevel ? round(($amount * $userLevel['give'] / 100),8) : 0; + $give_rate = $userLevel ? $userLevel['give'] : 0; + $data = [ + 'type'=>$type, + 'uid' => $user_id, + 'currency_id' => $currency_id, + 'amount' => $amount, + 'price' => $price, + 'give' => $give, + 'account_name' => $nick_name, + 'give_rate' => $give_rate, + 'user_account' => $account, + 'currency_name' => $currency -> name, + 'sub_type' => $sub_type, + 'address' => $address, + 'status' => 1, + 'created_at' => date('Y-m-d H:i:s') + ]; + Db::table('charge_req')->insert($data); + } + + return $this->success('申请成功'); + } + + + + + + //充值 + public function chargeReq11111(){ + $user_id = Users::getUserId(); + + $currency_id = xssCode(Input::get("currency", '')); + $type = xssCode(Input::get("type", '')); + $account = Input::get("account", ''); + $amount = xssCode(Input::get("amount",0)); + $sub_type = Input::get("sub_type", ''); + $address = Input::get("address", ''); + $hash = Input::get("hash", ''); + + $receivingBankCard = null; + if(empty($currency_id) || empty($amount)) { + return $this->error('参数错误1'); + } + if($type == 0){ + $currency = Db::table('currency')->where('id',$currency_id)->first(); + if(!$currency) { + return $this->error('参数错误2'); + } + }else{ + $receivingBankCard = Db::table('receiving_bank_card')->where('id',$currency_id)->first(); + if(!$receivingBankCard) { + return $this->error('参数错误2'); + } + } + + $user = Users::find($user_id); + + if (empty($user)){ + return $this->error('用户不存在'); + } + $nick_name = ''; + if (empty($user['email'])){ + $nick_name = $user['phone']; + }else{ + $nick_name = $user['email']; + } + $userLevel = $user['user_level'] > 0 ? UserLevelModel::find($user['user_level']) : null; + + if($type == 1){ + $give = $receivingBankCard -> commissions ? round(($amount * $receivingBankCard -> commissions / 100),8) : 0; + $give_rate = $receivingBankCard -> commissions ? $receivingBankCard -> commissions : 0; + + $data = [ + 'type'=>$type, + 'uid' => $user_id, + 'currency_id' => $currency_id, + 'amount' => $amount, + 'hash' => $hash, + 'give' => $give, + 'account_name' => $nick_name, + 'give_rate' => $give_rate, + 'user_account' => $account, + 'status' => 1, + 'bank_user_name' => $receivingBankCard -> account_name, + 'iban' => $receivingBankCard -> iban, + 'beneficiary_country' => $receivingBankCard -> beneficiary_country, + 'bank_code' => $receivingBankCard -> bank_code, + 'bank_name' => $receivingBankCard -> bank_name, + 'bank_address' => $receivingBankCard -> bank_address, + 'currency_name' => $receivingBankCard -> currency_name, + 'pay_way_name' => $receivingBankCard -> pay_way_name, + 'created_at' => date('Y-m-d H:i:s') + ]; + Db::table('charge_req')->insert($data); + }else{ + $give = $userLevel ? round(($amount * $userLevel['give'] / 100),8) : 0; + $give_rate = $userLevel ? $userLevel['give'] : 0; + $data = [ + 'type'=>$type, + 'uid' => $user_id, + 'currency_id' => $currency_id, + 'amount' => $amount, + 'give' => $give, + 'account_name' => $nick_name, + 'give_rate' => $give_rate, + 'user_account' => $account, + 'currency_name' => $currency -> name, + 'sub_type' => $sub_type, + 'address' => $address, + 'status' => 1, + 'created_at' => date('Y-m-d H:i:s') + ]; + Db::table('charge_req')->insert($data); + } + + return $this->success('申请成功'); + } + + public function hasLeverTrade($user_id) + { + $exist_close_trade = LeverTransaction::where('user_id', $user_id) + ->whereNotIn('status', [LeverTransaction::CLOSED, LeverTransaction::CANCEL]) + ->count(); + return $exist_close_trade > 0 ? true : false; + } + + + private $fromArr = [ + 'legal' => AccountLog::WALLET_LEGAL_OUT, + 'lever' => AccountLog::WALLET_LEVER_OUT, + 'micro' => AccountLog::WALLET_MCIRO_OUT, + 'change' => AccountLog::WALLET_CHANGE_OUT, + ]; + private $toArr = [ + 'legal' => AccountLog::WALLET_LEGAL_IN, + 'lever' => AccountLog::WALLET_LEVER_IN, + 'micro' => AccountLog::WALLET_MCIRO_IN, + 'change' => AccountLog::WALLET_CHANGE_IN, + ]; + private $mome = [ + 'legal' => 'c2c', + 'lever' => '合约', + 'micro' => '期权', + 'change' => '闪兑', + ]; + + public function changeWallet(Request $request) //BY tian + { + $type = [ + 'legal' => 1, + 'lever' => 3, + 'micro' => 4, + 'change' => 2, + ]; + $user_id = Users::getUserId(); + $currency_id = Input::get("currency_id", ''); + $number = Input::get("number", ''); + + $user = Users::find($user_id); + if($user->frozen_funds==1){ + return $this->error('资金已冻结'); + } + $from_field = $request->get('from_field', ""); + $to_field = $request->get('to_field', ""); + if (empty($from_field) || empty($number) || empty($to_field) || empty($currency_id)) { + return $this->error('参数错误'); + } + if ($number < 0) { + return $this->error('输入的金额不能为负数'); + } + $from_account_log_type = $this->fromArr[$from_field]; + $to_account_log_type = $this->toArr[$to_field]; + $memo = $this->mome[$from_field] . '划转' . $this->mome[$to_field]; + // if ($from_field == 'lever') { + // if ($this->hasLeverTrade($user_id)) { + // return $this->error('您有正在进行中的杆杠交易,不能进行此操作'); + // } + // } + try { + DB::beginTransaction(); + $user_wallet = UsersWallet::where('user_id', $user_id) + ->lockForUpdate() + ->where('currency', $currency_id) + ->first(); + if (!$user_wallet) { + throw new \Exception('钱包不存在'); + } + $result = change_wallet_balance($user_wallet, $type[$from_field], -$number, $from_account_log_type, $memo); + if ($result !== true) { + throw new \Exception($result); + } + $result = change_wallet_balance($user_wallet, $type[$to_field], $number, $to_account_log_type, $memo); + if ($result !== true) { + throw new \Exception($result); + } + DB::commit(); + return $this->success('划转成功'); + } catch (\Exception $e) { + DB::rollBack(); + return $this->error('操作失败:' . $e->getMessage()); + } + } + + public function hzhistory(Request $request) + { + $user_id = Users::getUserId(); + $limit = $request->get('limit', 10); + + $arr = [ + AccountLog::WALLET_LEGAL_OUT, + AccountLog::WALLET_LEVER_OUT, + AccountLog::WALLET_MCIRO_OUT, + AccountLog::WALLET_CHANGE_OUT, + AccountLog::WALLET_LEGAL_IN, + AccountLog::WALLET_LEVER_IN, + AccountLog::WALLET_MCIRO_IN, + AccountLog::WALLET_CHANGE_IN, + ]; + $result = AccountLog::where('user_id',$user_id)->whereIn('type', $arr)->orderBy('id', 'desc')->paginate($limit); + return $this->success($result); + + } + + + public function transhistory(Request $request) + { + $user_id = 99920342;//Users::getUserId(); + $limit = $request->get('limit', 10); + + $arr = [ + AccountLog::USER_EXCHANGE_DOWN, + AccountLog::USER_EXCHANGE_ADD, + + ]; + $result = AccountLog::where('user_id',$user_id)->whereIn('type', $arr)->orderBy('id', 'desc')->paginate($limit); + return $this->success($result); + + } + + //余额生息列表 + public function earnedhistory(Request $request) + { + $user_id = Users::getUserId(); + $limit = $request->get('limit', 10); + + $result = WalletLog::where('user_id',$user_id)->where('memo', 'earned by currency')->orderBy('id', 'desc')->paginate($limit); + foreach ($result as $l){ + + $l['create_time'] =date('Y-m-d H:i:s',$l['create_time']); + } + return $this->success($result); + + } + + public function getCurrencyInfo() + { + $user_id = Users::getUserId(); + $currency_id = Input::get("currency", ''); + if (empty($currency_id)) return $this->error('参数错误'); + $currencyInfo = Currency::find($currency_id); + if (empty($currencyInfo)) return $this->error('币种不存在'); + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->first(); + $data = [ + 'rate' => $currencyInfo->rate, + 'min_number' => $currencyInfo->min_number, + 'name' => $currencyInfo->name, + 'legal_balance' => $wallet->legal_balance, + 'change_balance' => $wallet->change_balance, + ]; + return $this->success($data); + } + + public function getAddressByCurrency() + { + $user_id = Users::getUserId(); + $currency_id = Input::get("currency", ''); + if (empty($user_id) || empty($currency_id)) { + return $this->error('参数错误'); + } + $address = Address::where('user_id', $user_id)->where('currency', $currency_id)->get()->toArray(); + if (empty($address)) { + return $this->error('您还没有添加提币地址'); + } + return $this->success($address); + } + + public function postWalletOut() + { + $user_id = Users::getUserId(); + $type = Input::get("type", ''); + $currency_id = Input::get("currency", 3); + + $number = Input::get("number", ''); + $amount = Input::get("amount", ''); + $rate = Input::get("rate", ''); + $address = Input::get("address", ''); + // + if (empty($currency_id) || empty($number) || ($type == 0 && empty($address))) { + return $this->error('参数错误'); + } + + switch ($currency_id) { + //BTC + case '1': + if (!(preg_match('/^(1|3)[a-zA-Z\d]{24,33}$/', $address) && preg_match('/^[^0OlI]{25,34}$/', $address))) { + return $this->error('参数错误'); + } + break; + //ETH + case '2': + + if (!(preg_match('/^(0x)?[0-9a-fA-F]{40}$/', $address))) { + return $this->error('参数错误'); + } + break; + } + if ($number < 0) { + return $this->error('输入的金额不能为负数'); + } + $user = Users::getById(Users::getUserId()); + + + // if($user->frozen_funds == 1){ + // return $this->error('资金已冻结'); + // } + + if ($user->status == 1) { + return $this->error('您好,您的账户已被锁定,详情请咨询客服。'); + } + + if ($user->frozen_funds == 1) { + return $this->error('您好,您的账户已被锁定,详情请咨询客服。'); + } + + + $zkRadio = Setting::getValueByKey('tk_radio', ''); + $password = Input::get('pay_password'); + + $payPassword = Users::MakePassword($password, $user->type); + + if($payPassword!=$user->pay_password) { + + $change = DB::table('score_log')->where("user_id",$user->id)->where('remarks','Pay Password error')->where("type",2)->sum("change"); + $users = new Users(); + $users->ChangeScore(1,$user, $user->id,'Pay Password error'); + $date = time()+30*86400; + if($change<=-4) {$users->lockUser($user, 1, $date, 1);} + + return $this->error('支付密码错误'); + + } + if($zkRadio == 1){ + + } + + $currencyInfo = Currency::find($currency_id); + if ($number < $currencyInfo->min_number) { + return $this->error('数量不能少于最小值'); + } + $user_name = $user['email']; + if (empty($user_name)){ + $user_name = $user['phone']; + } + try { + DB::beginTransaction(); + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->lockForUpdate()->first(); + + if ($number > $wallet->micro_balance) { + DB::rollBack(); + return $this->error('余额不足'); + } + $walletOut = new UsersWalletOut(); + $walletOut->type=$type; + $walletOut->user_id = $user_id; + $walletOut->currency = $currency_id; + $walletOut->number = $number; + $walletOut->address = $address; + $walletOut->user_name = $user_name; + $walletOut->rate = $rate; + // $walletOut->real_number = $number - $rate; + $walletOut->real_number = $amount; + $walletOut->create_time = time(); + $walletOut->status = 1; + $walletOut->save(); + + $result = change_wallet_balance($wallet, 2, -$number, AccountLog::WALLETOUT, '申请提币扣除余额'); + if ($result !== true) { + throw new \Exception($result); + } + + $result = change_wallet_balance($wallet, 2, $number, AccountLog::WALLETOUT, '申请提币锁定余额', true); + if ($result !== true) { + throw new \Exception($result); + } + DB::commit(); + return $this->success('提币申请已成功,等待审核'); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + } + + public function getWalletAddressIn() + { + $user_id = Users::getUserId(); + + $currency_id = Input::get("currency", ''); + if (empty($user_id) || empty($currency_id)) { + return $this->error('参数错误'); + } + $currencyInfo = Currency::find($currency_id); + if(!$currencyInfo){ + return $this->error('参数错误'); + } + $legal = UsersWallet::where("user_id", $user_id) + ->where("currency", $currency_id) //usdt + ->first(); + if($currency_id==3){//usdt充值地址 + $address=[ + 'erc20'=>$currencyInfo->address_erc ?? '', //erc20 + "trc20"=>$currencyInfo->address_omni ?? '' //trc20 + ]; + }else{ + $address=$currencyInfo->address_erc ?? ''; + } + return $this->success($address); + } + + public function getWalletDetail() + { + $user_id = Users::getUserId(); + $currency_id = Input::get("currency", ''); + $type = Input::get("type", ''); + if (empty($user_id) || empty($currency_id)) { + return $this->error('参数错误'); + } + $ExRate = Setting::getValueByKey('USDTRate', 7.2); + if ($type == 'legal') { + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->first(['id', 'currency', 'legal_balance', 'lock_legal_balance','address']); + } else if ($type == 'change') { + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->first(['id', 'currency', 'change_balance', 'lock_change_balance','address']); + + } else if ($type == 'lever') { + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->first(['id', 'currency', 'lever_balance', 'lock_lever_balance','address']); + } else if ($type == 'micro') { + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $currency_id)->first(['id', 'currency', 'micro_balance', 'lock_micro_balance','address']); + } else { + return $this->error('类型错误'); + } + if (empty($wallet)) return $this->error("钱包未找到"); + + $wallet->ExRate = $ExRate; + + if(in_array($wallet->currency,[1,2,3])){ + $wallet->is_charge = true; + }else{ + $wallet->is_charge = false; + } + + $wallet->coin_trade_fee = Setting::getValueByKey('COIN_TRADE_FEE'); + return $this->success($wallet); + } + + + public function gettype() + { + //1.法币,2.币币,3.永续合约 4 交割合约 5 理财 + $wallet =array(array('type'=>1,'name'=>'法币'), + array('type'=>2,'name'=>'币币'), + array('type'=>3,'name'=>'永续合约'), + array('type'=>4,'name'=>'交割合约'), + array('type'=>5,'name'=>'理财') + ); + + return $this->success($wallet); + } + public function legalLog(Request $request) + { + + $limit = $request->get('limit', 10); + $account = $request->get('account', ''); + $currency = $request->get('currency', 0); + $type= $request->get('type',0); + $user_id = Users::getUserId(); + $list = new AccountLog(); + if (!empty($currency)) { + $list = $list->where('currency', $currency); + } + if (!empty($user_id)) { + $list = $list->where('user_id', $user_id); + } + if (!empty($type) && $type<6) { + $list = $list->whereHas('walletLog',function($query) use($type){ + $query->where('balance_type',$type); + }); + } + + if ($type==6) { + $list = $list->whereHas('walletLog',function($query) use($type){ + $query->where('balance_type','<', $type); + }); + } + $list = $list->orderBy('id', 'desc')->paginate($limit); + + $is_open_CTbi = Setting::where("key", "=", "is_open_CTbi")->first()->value; + + return $this->success(array( + "list" => $list->items(), 'count' => $list->total(), + "limit" => $limit, + "is_open_CTbi" => $is_open_CTbi + )); + } + + public function walletOutLog() + { + $id = Input::get("id", ''); + $walletOut = UsersWalletOut::find($id); + return $this->success($walletOut); + } + + + + public function getLtcKMB() + { + $address = Input::get('address', ''); + $money = Input::get('money', ''); + $wallet = UsersWallet::whereHas('currencyCoin', function ($query) { + $query->where('name', 'PB'); + })->where('address', $address)->first(); + if (empty($wallet)) { + return $this->error('钱包不存在'); + } + DB::beginTransaction(); + try { + + $data_wallet1 = array( + 'balance_type' => 1, + 'wallet_id' => $wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $wallet->change_balance, + 'change' => $money, + 'after' => $wallet->change_balance + $money, + ); + $wallet->change_balance = $wallet->change_balance + $money; + $wallet->save(); + AccountLog::insertLog([ + 'user_id' => $wallet->user_id, + 'value' => $money, + 'currency' => $wallet->currency, + 'info' => '转账来自钱包的余额', + 'type' => AccountLog::LTC_IN, + ], $data_wallet1); + DB::commit(); + return $this->success('转账成功'); + } catch (\Exception $rex) { + DB::rollBack(); + return $this->error($rex); + } + } + public function sendLtcKMB() + { + $user_id = Users::getUserId(); + $account_number = Input::get('account_number', ''); + $money = Input::get('money', ''); + + if (empty($account_number) || empty($money) || $money < 0) { + return $this->error('参数错误'); + } + $wallet = UsersWallet::whereHas('currencyCoin', function ($query) { + $query->where('name', 'PB'); + })->where('user_id', $user_id)->first(); + if ($wallet->change_balance < $money) { + return $this->error('余额不足'); + } + + DB::beginTransaction(); + try { + + $data_wallet1 = array( + 'balance_type' => 1, + 'wallet_id' => $wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $wallet->change_balance, + 'change' => $money, + 'after' => $wallet->change_balance - $money, + ); + $wallet->change_balance = $wallet->change_balance - $money; + $wallet->save(); + AccountLog::insertLog([ + 'user_id' => $wallet->user_id, + 'value' => $money, + 'currency' => $wallet->currency, + 'info' => '转账余额至钱包', + 'type' => AccountLog::LTC_SEND, + ], $data_wallet1); + + $url = "http://walletapi.bcw.work/api/ltcGet?account_number=" . $account_number . "&money=" . $money; + $data = RPC::apihttp($url); + $data = @json_decode($data, true); + // var_dump($data);die; + if ($data["type"] != 'ok') { + DB::rollBack(); + return $this->error($data["message"]); + } + DB::commit(); + return $this->success('转账成功'); + } catch (\Exception $rex) { + DB::rollBack(); + return $this->error($rex->getMessage()); + } + } + public function PB() + { + $user_id = Users::getUserId(); + $wallet = UsersWallet::whereHas('currencyCoin', function ($query) { + $query->where('name', 'PB'); + })->where('user_id', $user_id)->first(); + return $this->success($wallet->change_balance); + } + public function flashAgainstList(Request $request) + { + $user_id = Users::getUserId(); + $left = Currency::where('is_match', 1)->get(); + foreach ($left as $k => $v) { + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $v->id)->first(); + if (empty($wallet)) { + $balance = 0; + } else { + $balance = $wallet->change_balance; + } + $v->balance = $balance; + $left[$k] = $v; + } + $right = Currency::where('is_micro', 1)->get(); + foreach ($right as $k => $v) { + $wallet = UsersWallet::where('user_id', $user_id)->where('currency', $v->id)->first(); + if (empty($wallet)) { + $balance = 0; + } else { + $balance = $wallet->change_balance; + } + $v->balance = $balance; + $right[$k] = $v; + } + return $this->success(['left' => $left, 'right' => $right]); + } + + public function flashAgainst(Request $request) + { + try { + $l_currency_id = $request->get('l_currency_id', ""); + $r_currency_id = $request->get('r_currency_id', ""); + $num = $request->get('num', 0); + + $user_id = Users::getUserId(); + if ($num <= 0) return $this->error('数量不能小于等于0'); + $p = $request->get('price', 0); + if ($p <= 0) return $this->error('价格不能小于等于0'); + + if (empty($l_currency_id) || empty($r_currency_id)) return $this->error('参数错误哦'); + + $left = Currency::where('id', $l_currency_id)->first(); + $right = Currency::where('id', $r_currency_id)->first(); + if (empty($left) || empty($right)) return $this->error('币种不存在'); + + //$absolute_quantity = $p * $num / $right->price; + $absolute_quantity = bc_div(bc_mul($p, $num), $right->price); + DB::beginTransaction(); + + $l_wallet = UsersWallet::where('currency', $l_currency_id)->where('user_id',$user_id)->lockForUpdate()->first(); + + if (empty($l_wallet)){ + + throw new \Exception('钱包不存在'); + } + + if ($l_wallet->change_balance < $num){ + + throw new \Exception('金额不足'); + } + + $flash_against = new FlashAgainst(); + $flash_against->user_id = $user_id; + $flash_against->price = $p; + $flash_against->market_price = $left->price; + $flash_against->num = $num; + $flash_against->status = 0; + $flash_against->left_currency_id = $l_currency_id; + $flash_against->right_currency_id = $r_currency_id; + $flash_against->create_time = time(); + $flash_against->absolute_quantity = $absolute_quantity; //实际数量 + $result = $flash_against->save(); + $result1=change_wallet_balance($l_wallet, 2, -$num, AccountLog::DEBIT_BALANCE_MINUS, '闪兑扣除余额'); + $result2=change_wallet_balance($l_wallet, 2, $num, AccountLog::DEBIT_BALANCE_ADD_LOCK, '闪兑增加锁定余额', true); + if($result1 !== true){ + throw new \Exception($result1); + } + if ($result2 !== true) { + throw new \Exception($result2); + } + + DB::commit(); + return $this->success('兑换成功'); + } catch (\Exception $e) { + DB::rollBack(); + return $this->error($e->getMessage() . '---' . $e->getLine()); + } + } + + public function myFlashAgainstList(Request $request) + { + $limit = $request->get('limit', 10); + $user_id = Users::getUserId(); + $list = FlashAgainst::orderBy('id', 'desc')->where('user_id', $user_id)->paginate($limit); + return $this->success($list); + } + + public function conversion(Request $request) + { + $form_currency_id = $request->get('form_currency', ''); + $to_currency_id = $request->get('to_currency', ''); + $balance_filed = 'legal_balance'; + $num = $request->get('num', ''); + if (empty($form_currency_id) || empty($to_currency_id) || empty($num)) { + return $this->error('参数错误'); + } + if($num <= 0){ + return $this->error('兑换数量必须大于0'); + } + $user_id = Users::getUserId(); + try { + DB::beginTransaction(); + $form_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $form_currency_id)->lockForUpdate()->first(); + $to_wallet = UsersWallet::where('user_id', $user_id)->where('currency', $to_currency_id)->lockForUpdate()->first(); + if(empty($form_wallet) || empty($to_wallet)){ + DB::rollBack(); + return $this->error('钱包不存咋'); + } + if ($form_wallet->$balance_filed < $num) { + DB::rollBack(); + return $this->error('余额不足'); + } + if (strtoupper($form_wallet->currency_name) == 'USDC') { + $fee = Setting::getValueByKey('currency_to_usdt_bmb_fee'); + $proportion = Setting::getValueByKey('currency_to_usdt_bmb'); + } elseif (strtoupper($form_wallet->currency_name) == UsersWallet::CURRENCY_DEFAULT) { + $fee = Setting::getValueByKey('currency_to_bmb_usdt_fee'); + $proportion = Setting::getValueByKey('currency_to_bmb_usdt'); + } + $totle_num_fee =bc_mul($num,$fee / 100); + $totle_num = bc_sub($num,$totle_num_fee); + $totle_num_sj = $proportion * $totle_num; + + + $res1=change_wallet_balance($form_wallet, 1, -$totle_num, AccountLog::WALLET_USDT_MINUS, $form_wallet->currency_name . '兑换,' . $to_wallet->currency_name . ',减少' . $form_wallet->currency_name . $totle_num); + + $res2=change_wallet_balance($form_wallet, 1, -$totle_num_fee, AccountLog::WALLET_USDT_BMB_FEE, $form_wallet->currency_name . '兑换,' . $to_wallet->currency_name . ',减少' . $form_wallet->currency_name . '手续费' . $totle_num_fee); + + $res3=change_wallet_balance($to_wallet, 1, $totle_num_sj, AccountLog::WALLET_BMB_ADD, $form_wallet->currency_name . '兑换,' . $to_wallet->currency_name . ',增加' . $to_wallet->currency_name . $totle_num_sj); + if($res1 !== true ){ + DB::rollBack(); + return $this->error($res1); + } + if($res2 !== true ){ + DB::rollBack(); + return $this->error($res2); + } + if($res3 !== true){ + DB::rollBack(); + return $this->error($res3); + } + + $conversion = new Conversion(); + $conversion->user_id = $user_id; + $conversion->create_time = time(); + $conversion->form_currency_id = $form_currency_id; + $conversion->to_currency_id = $to_currency_id; + $conversion->num = $num; + $conversion->fee = $totle_num_fee; + $conversion->sj_num = $totle_num_sj; + $conversion->save(); + DB::commit(); + return $this->success('兑换成功'); + } catch (\Exception $e) { + DB::rollBack(); + return $this->error($e->getMessage()); + } + } + + public function myConversion(Request $request) + { + $user_id = Users::getUserId(); + $limit = $request->get('limit', 10); + $list = Conversion::orderBy('id', 'desc')->where('user_id', $user_id)->paginate($limit); + return $this->success($list); + } + + public function conversionList() + { + $currency = Currency::where('name', 'USDC')->orWhere('name', UsersWallet::CURRENCY_DEFAULT)->get(); + return $this->success($currency); + } + public function conversionSet() + { + $fee = Setting::getValueByKey('currency_to_usdt_bmb_fee'); + $proportion = Setting::getValueByKey('currency_to_usdt_bmb'); + $data['usdt_bmb_fee'] = $fee; + $data['usdt_bmb_proportion'] = $proportion; + $fee1 = Setting::getValueByKey('currency_to_bmb_usdt_fee'); + $proportion1 = Setting::getValueByKey('currency_to_bmb_usdt'); + $data['bmb_usdt_fee'] = $fee1; + $data['bmb_usdt_proportion'] = $proportion1; + $usdt = Currency::where('name', 'USDC')->first(); + $bmb = Currency::where('name', UsersWallet::CURRENCY_DEFAULT)->first(); + $user_id = Users::getUserId(); + $balance_filed = 'legal_balance'; + $usdt_wallet = UsersWallet::where('currency', $usdt->id)->where('user_id', $user_id)->first(); + $data['user_balance'] = $usdt_wallet->$balance_filed; + $bmb_wallet = UsersWallet::where('currency', $bmb->id)->where('user_id', $user_id)->first(); + $data['bmb_balance'] = $bmb_wallet->$balance_filed; + return $this->success($data); + } + + //持险生币 + public function Insurancemoney() + { + + $user_id = Users::getUserId(); + $wallet = UsersWallet::where('lock_insurance_balance', '>', 0)->where('user_id', $user_id)->first(); + $data = []; + + $data['insurance_balance'] = $wallet->insurance_balance ?? 0; + + $data['lock_insurance_balance'] = $wallet->lock_insurance_balance ?? 0; + //累计生币 + $data['sum_balance'] = AccountLog::where('user_id', $user_id)->where('type', AccountLog::INSURANCE_MONEY)->sum('value'); + //可用数量 + $data['usabled_balance'] = 0; + + return $this->success($data); + } + + //持险生币日志 + public function Insurancemoneylogs() + { + + $user_id = Users::getUserId(); + $limit = Input::get('limit', 10); + + $result = AccountLog::where('user_id', $user_id)->where('type', AccountLog::INSURANCE_MONEY)->orderBy('id', 'desc')->paginate($limit); + + return $this->success($result); + } +} diff --git a/app/Http/Controllers/Api/WalletOneController.php b/app/Http/Controllers/Api/WalletOneController.php new file mode 100644 index 0000000..79aad79 --- /dev/null +++ b/app/Http/Controllers/Api/WalletOneController.php @@ -0,0 +1,305 @@ +error('两次密码不一致'); + } + + if (empty($user_id) || empty($memorizing_words) || empty($erc_address) || empty($password)) return $this->error("参数错误"); + + $user = Users::find($user_id); + if (empty($user)) return $this->error("用户未找到"); + + $waller = UsersWallet::where("user_id",$user_id)->first(); + if ($waller) return $this->error("钱包已添加,请勿重复添加"); + // $currency = Currency::all()->toArray(); + DB::beginTransaction(); + try { + $currency = Currency::all(); + $user->pay_password = $password; + $user->memorizing_words = $memorizing_words; + $user->save(); + // $address_url = config('wallet_api') . $user->id; + $address_url = '' . $user->id; + $address = RPC::apihttp($address_url); + $address = @json_decode($address, true); + // return $address_url; + foreach ($currency as $key => $value) { + $userWallet = new UsersWallet(); + $userWallet->user_id = $user->id; + if ($value->type == 'btc') { + $userWallet->address = $address["contentbtc"]; + $userWallet->eth_address = $erc_address; + } else { + $userWallet->eth_address = $btc_address; + $userWallet->address = $address["content"]; + } + $userWallet->currency = $value->id; + // $userWallet->memorizing_words = $memorizing_words; + + // $userWallet->address = $address; + // $userWallet->password = + $userWallet->create_time = time(); + $userWallet->save();//默认生成所有币种的钱包 + } + DB::commit(); + return $this->success("添加成功"); + } catch (\Exception $ex) { + DB::rollBack(); + return $this->error($ex->getMessage()); + } + + } + //钱包转交易所的方法 + //1111钱包的操作 + public function ltcSend(Request $request){ + $address = $request->input('address', ''); + $money = $request->input('money', ''); + $password = $request->input('password', ''); + $password = $request->input('currency_id', ''); + $user_id = Users::getUserId(Input::get("user_id")); + $user= Users::find($user_id); + $wallet = UsersWallet::where('user_id',$user_id)->first(); + if(empty($address)||empty($money)||$money<0||empty($wallet)){ + return $this->error('参数错误'); + } + if($wallet->password!=$password){ + return $this->error('支付密码错误'); + } + // $userWallet = UsersWallet::where('user_id',$user_id)->where('token','PB')->first(); + if($money>$userWallet->balance){ + return $this->error('余额不足'); + } + // $user = Users::find($user_id); + + // $key = md5(time()); + $set_url = Settings::getValueByKey('send_url',''); + if(empty($set_url)){ + return $this->error('参数错误'); + } + DB::beginTransaction(); + try{ + $userWallet->change_balance = $userWallet->change_balance-$money; + $userWallet->save(); + AccountLog::insertLog([ + 'user_id'=>$user_id, + 'value'=>$money, + 'info'=>'转账至交易所钱包', + 'type'=>AccountLog::LTC_SEND + ]); + + $url = $set_url."/api/getLtcKMB?address=" . $address . "&money=" . $money; + $data = RPC::apihttp($url); + $data = @json_decode($data, true); + if($data["type"]!='ok'){ + DB::rollBack(); + return $this->error($data["message"]); + } + DB::commit(); + return $this->success('转账成功'); + }catch(\Exception $rex){ + DB::rollBack(); + + return $this->error($rex); + } + } + //接收来自交易所的余额 + public function ltcGet(Request $request){ + $account_number = $request->input('account_number', ''); + $money = $request->input('money', ''); + // $key = $request->input('key', ''); + // if(md5(time())!=$key){ + // return $this->error('系统错误'); + // } + $user = Users::where('account_number',$account_number)->first(); + if(empty($user)) return $this->error('找不到用户'); + $userWallet = UsersWallet::where('user_id',$user->id)->first(); + if(empty($userWallet)) return $this->error('用户钱包未找到'); + DB::beginTransaction(); + try{ + $userWallet->balance = $userWallet->balance+$money; + $userWallet->save(); + AccountLog::insertLog([ + 'user_id'=>$user->id, + 'value'=>$money, + 'info'=>'接收来自交易所的转账', + 'type'=>AccountLog::LTC_IN + ]); + DB::commit(); + return $this->success('转账成功'); + }catch(\Exception $rex){ + DB::rollBack(); + + return $this->error($rex); + } + } + //钱包列表 + public function walletList(){ + $user_id = Users::getUserId(); + $currency = Currency::where('is_display', 1)->orderBy('sort', 'asc')->get(); + $userWallet = UsersWallet::where('user_id',$user_id)->first(); + if(empty($userWallet)){ + return $this->error('您还没有钱包'); + } + $list = []; + $total_cny = 0; + foreach($currency as $k=>$v){ + $list[$k]['id'] = $v->id; + $list[$k]['name'] = $v->name; + $list[$k]['logo'] = $v->logo; + $wallet = UsersWallet::where('user_id',$user_id)->where('currency',$v->id)->first(); + if(!empty($wallet)){ + $cny_price = Currency::getCnyPrice($v->id); + // $list[$k]['cny_price'] = $cny_price; + $list[$k]['balance'] = $wallet->change_balance; + $list[$k]['lock_balance'] = $wallet->lock_change_balance; + $list[$k]['cny_balance'] = bc_add($wallet->change_balance,$wallet->lock_change_balance,5)*$cny_price; + $total_cny += $list[$k]['cny_balance']; + }else{ + $list[$k]['balance'] = 0; + $list[$k]['lock_balance'] = 0; + $list[$k]['cny_balance'] = bc_add($wallet->change_balance,$wallet->lock_change_balance,5)*$cny_price; + $total_cny += $list[$k]['cny_balance']; + } + + } + // $cny_price = Currency::getCnyPrice(); + // $total = + return $this->success(['wallet'=>$list,'total_cny'=>$total_cny]); + } + public function moneyRechange(Request $request){ + // $company_eth_address = Setting::getValueByKey("company_eth_address"); + // return $this->success(array("company_eth_address"=>$company_eth_address)); + $user_id = Users::getUserId(); + $currency_id = $request->input('currency_id', ''); + if(empty($user_id)||empty($currency_id)) return $this->error('参数错误'); + $userWallet = UsersWallet::where('user_id',$user_id)->where('currency',$currency_id)->first(); + $company_eth_address = $userWallet->eth_address; + return $this->success(array("company_eth_address"=>$company_eth_address)); + + } + //转账 + public function walletChange(Request $request){ + $user_id = Users::getUserId(); + $currency_id = $request->input('id', ''); + $num = $request->input('number', ''); + $address = $request->input('address', ''); + $remarks = $request->input('remarks', ''); + $password = $request->input('password', ''); + if(empty($currency_id)||empty($num)||empty($address)||empty($remarks)||empty($password)){ + return $this->error('参数错误'); + } + $user = Users::find($user_id); + $wallet = UsersWallet::where('currency',$currency_id)->where('user_id',$user_id)->first(); + if($num>$wallet->change_balance) return $this->error('余额不足'); + if($num<=0) return $this->error('请输入正确的值'); + $to_wallet = UsersWallet::where('address',$address)->where('currency',$currency_id)->first(); + if(empty($to_wallet)) return $this->error('地址输入有误'); + if($to_wallet->currency!=$currency_id) return $this->error('地址输入有误1'); + if($to_wallet->user_id==$user_id) return $this->error('不能转账给自己'); + if($password!=$user->pay_password) return $this->error('支付密码错误'); + $to_user = Users::find($to_wallet->user_id); + + + DB::beginTransaction(); + try{ + $data_wallet1 = [ + 'balance_type' => 2, + 'wallet_id' => $wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $wallet->change_balance, + 'change' => -$num, + 'after' => bc_sub($wallet->change_balance, $num, 5), + ]; + AccountLog::insertLog([ + 'user_id' => $user_id, + 'value' => bc_mul($num, -1, 5), + 'info' => "向".$to_user->account_number."转账", + 'type' => AccountLog::CHANGEBALANCE, + 'currency' => $currency_id, + ],$data_wallet1); + $data_wallet2 = [ + 'balance_type' => 2, + 'wallet_id' => $to_wallet->id, + 'lock_type' => 0, + 'create_time' => time(), + 'before' => $to_wallet->change_balance, + 'change' => $num, + 'after' => bc_add($to_wallet->change_balance, $num, 5), + ]; + AccountLog::insertLog([ + 'user_id' => $to_wallet->user_id, + 'value' => bc_mul($num, 1, 5), + 'info' => "来自".$user->account_number."的转账", + 'type' => AccountLog::CHANGEBALANCE, + 'currency' => $currency_id, + ],$data_wallet2); + $wallet->change_balance = bc_sub($wallet->change_balance,$num,5); + $wallet->save(); + $to_wallet->change_balance= bc_add($wallet->change_balance,$num,5); + $to_wallet->save(); + DB::commit(); + return $this->success('转账成功'); + }catch(\Exception $rex){ + DB::rollback(); + return $this->error($rex); + } + } + public function accountList(){ + $user_id = Users::getUserId(); + $currency_id = Input::get('id', ''); + $limit = Input::get('limit','12'); + $page = Input::get('page','1'); + // if (empty($address)) return $this->error("参数错误"); + + // $user = Users::fi->first(); + // if (empty($user)) return $this->error("数据未找到"); + + $data = AccountLog::where("user_id",$user_id); + if(!empty($currency_id)){ + $data = $data->where('currency',$currency_id); + } + $data = $data->orderBy('id', 'DESC')->paginate($limit); + return $this->success(array( + "user_id"=>$user_id, + "data"=>$data->items(), + "limit"=>$limit, + "page"=>$page, + )); + } + public function getInfo(){ + $user_id = Users::getUserId(); + return $this->success(Users::find($user_id)); + } +}