fix: 全模块Critical安全修复 — 防重入+锁+精度+XSS
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AutoList;
|
||||
use App\CurrencyQuotation;
|
||||
use App\MarketHour;
|
||||
use App\Setting;
|
||||
use App\TransactionComplete;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Faker\Factory;
|
||||
use App\Users;
|
||||
use App\AiCurrency;
|
||||
use App\AiOrder;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoAiOrder extends Command
|
||||
{
|
||||
protected $signature = "auto_ai_order";
|
||||
protected $description = "AI量化订单";
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$nowday = date('Ymd',time());
|
||||
|
||||
// ->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AutoList;
|
||||
use App\CurrencyQuotation;
|
||||
use App\MarketHour;
|
||||
use App\Setting;
|
||||
use App\TransactionComplete;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Faker\Factory;
|
||||
use App\Users;
|
||||
use App\BalanceList;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoBalance extends Command
|
||||
{
|
||||
protected $signature = "auto_balance";
|
||||
protected $description = "用户资产汇总";
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$nowday = date('Y-m-d H:i:s',time());
|
||||
$list = Users::where('id','>',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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\C2cDeal;
|
||||
use App\C2cDealSend;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoCancelC2C extends Command
|
||||
{
|
||||
protected $signature = "auto_cancel_c2c";
|
||||
protected $description = "自动取消24小时C2C发布";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\C2cDeal;
|
||||
use App\C2cDealSend;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoCancelC2CDeal extends Command
|
||||
{
|
||||
protected $signature = "auto_cancel_c2c_deal";
|
||||
protected $description = "15分钟自动取消C2C交易";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\LegalDeal;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoCancelLegal extends Command
|
||||
{
|
||||
protected $signature = "auto_cancel_legal";
|
||||
protected $description = "自动取消 24 小时法币交易";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AutoList;
|
||||
use App\CurrencyQuotation;
|
||||
use App\MarketHour;
|
||||
use App\Setting;
|
||||
use App\TransactionComplete;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Faker\Factory;
|
||||
use App\Users;
|
||||
use App\DualCurrency;
|
||||
use App\DualOrder;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoDualOrder extends Command
|
||||
{
|
||||
protected $signature = "auto_dual_order";
|
||||
protected $description = "结算双币订单";
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$nowday = date('Ymd',time());
|
||||
|
||||
// ->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AutoList;
|
||||
use App\CurrencyQuotation;
|
||||
use App\MarketHour;
|
||||
use App\Setting;
|
||||
use App\TransactionComplete;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Faker\Factory;
|
||||
use App\Users;
|
||||
use App\DualCurrency;
|
||||
use App\DualOrder;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoLixi extends Command
|
||||
{
|
||||
protected $signature = "auto_lixi";
|
||||
protected $description = "结算量化本息";
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$nowday = date('Ymd',time());
|
||||
|
||||
// ->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AutoList;
|
||||
use App\CurrencyQuotation;
|
||||
use App\MarketHour;
|
||||
use App\Setting;
|
||||
use App\TransactionComplete;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Faker\Factory;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class AutoOrder extends Command
|
||||
{
|
||||
protected $signature = "auto_order {id : id}";
|
||||
protected $description = "机器人自动下单";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$id = $this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class BonusAlgorithm extends Command
|
||||
{
|
||||
protected $signature = "bonus_algorithm";
|
||||
protected $description = "奖金算法";
|
||||
protected $user_bonus = array();
|
||||
protected $ecology_bonus = array();
|
||||
public function handle()
|
||||
{
|
||||
$user_bonus = Setting::getValueByKey("user_bonus");
|
||||
$ecology_bonus = Setting::getValueByKey("ecology_bonus");
|
||||
if (empty($user_bonus) || empty($ecology_bonus)) {
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\C2cDeal;
|
||||
use App\Users;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\C2cDealSend;
|
||||
use App\Setting;
|
||||
use App\LegalDeal;
|
||||
class CancelC2ctime extends Command
|
||||
{
|
||||
protected $signature = "cancel:c2cdeal";
|
||||
protected $description = "c2c取消订单倒计时";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$this->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('执行成功');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\UsersWallet;
|
||||
use App\Setting;
|
||||
use App\Utils\RPC;
|
||||
use App\Currency;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class CollectToken extends Command
|
||||
{
|
||||
protected $signature = "collect_token{currency_id : id}";
|
||||
protected $description = "收集代币";
|
||||
protected $contract_address = "";
|
||||
protected $total_account_address = "";
|
||||
protected $total_account_key = "";
|
||||
protected $currency_type = "";
|
||||
protected $decimal_scale = 18;
|
||||
public function handle()
|
||||
{
|
||||
$currency_id = $this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Currency;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class ExecuteCurrency extends Command
|
||||
{
|
||||
protected $signature = "execute_currency {id : id}";
|
||||
protected $description = "上币执行脚本";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$id = $this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\CurrencyMatch;
|
||||
use App\UsersWallet;
|
||||
use Illuminate\Console\Command;
|
||||
use App\Follow;
|
||||
use App\Users;
|
||||
use App\LeverTransaction;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class FollowCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'follow';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '处理跟单';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
Follow::query()
|
||||
->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
|
||||
use App\MarketHour;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
defined('ACCESS_KEY') or define('ACCESS_KEY', 'e480c999-bgbfh5tv3f-7a172162-43c3b'); // 你的ACCESS_KEY
|
||||
|
||||
|
||||
class GHK extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'get_h_kline {period} {size}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '获取K线图数据';
|
||||
|
||||
private $url = 'https://api.huobi.pro';//'https://api.huobi.pro';
|
||||
private $api = '';
|
||||
public $api_method = '';
|
||||
public $req_method = '';
|
||||
public $period ;
|
||||
public $size;
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
global $argv;
|
||||
parent::__construct();
|
||||
// var_dump(ACCESS_KEY);exit;
|
||||
if(!array_key_exists(2,$argv) || ! array_key_exists(3,$argv)){
|
||||
return;
|
||||
}
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Currency;
|
||||
use App\UserChat;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
while (true) {
|
||||
try {
|
||||
echo "开始推送\r\n";
|
||||
$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[] = $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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline_Daily extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data_daily";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
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']) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline_FifteenMin extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data_fifteenmin";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
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']) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline_Hourly extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data_hourly";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
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']) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline_Monthly extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data_monthly";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
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']) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline_ThirtyMin extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data_thirtymin";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
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']) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline_Weekly extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data_weekly";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
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']) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
defined('ACCOUNT_ID') || define('ACCOUNT_ID', '50154012');
|
||||
defined('ACCESS_KEY') || define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14');
|
||||
defined('SECRET_KEY') || define('SECRET_KEY', '');
|
||||
class GetKline_FiveMin extends Command
|
||||
{
|
||||
protected $signature = "get_kline_data_fivemin";
|
||||
protected $description = "获取K线图数据";
|
||||
private $url = "https://api.huobi.br.com";
|
||||
private $api = "";
|
||||
public $api_method = "";
|
||||
public $req_method = "";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
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']) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Market;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
class GetMarket extends Command
|
||||
{
|
||||
protected $signature = "get_market";
|
||||
protected $description = "获取行情";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$opts = ["http" => ["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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\HistoricalData;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class HistoricalDatas extends Command
|
||||
{
|
||||
protected $signature = "historical_data";
|
||||
protected $description = "历史数据";
|
||||
public function handle()
|
||||
{
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$day = intval(date("d", time()));
|
||||
$week = date("w");
|
||||
$yesterday_start = date("Y-m-d", strtotime("-1 day"));
|
||||
$yesterday_start = strtotime($yesterday_start);
|
||||
$yesterday_end = $yesterday_start + 86400;
|
||||
$aaa = HistoricalData::insertData($yesterday_start, $yesterday_end);
|
||||
if ($week == "1") {
|
||||
$week_start = date("Y-m-d", strtotime("last Monday"));
|
||||
$week_start = strtotime($week_start);
|
||||
HistoricalData::insertData($week_start, time(), "week");
|
||||
}
|
||||
if ($day == 1) {
|
||||
$month_start = date("Y-m-d", strtotime("last month"));
|
||||
$month_start = strtotime($month_start);
|
||||
HistoricalData::insertData($month_start, time(), "month");
|
||||
}
|
||||
DB::commit();
|
||||
} catch (\Exception $ex) {
|
||||
DB::rollback();
|
||||
$this->comment($ex->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\MarketHour;
|
||||
use Elasticsearch\ClientBuilder;
|
||||
use App\CurrencyMatch;
|
||||
class ImportMarketFromEsearch extends Command
|
||||
{
|
||||
protected $signature = "market:import";
|
||||
protected $description = "Command description";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$from_host = ['http://mhy.happyawn.com:9200', '39.109.113.168:9200'];
|
||||
$to_host = ['45.192.181.101:9200'];
|
||||
$from_host = ['host' => '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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\LeverTransaction;
|
||||
use App\UsersWallet;
|
||||
use App\AccountLog;
|
||||
use App\Setting;
|
||||
class Insurancemoney extends Command
|
||||
{
|
||||
protected $signature = "insurance_money";
|
||||
protected $description = "持币生币";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$today = strtotime(date('Y-m-d'));
|
||||
$count = UsersWallet::where('lock_insurance_balance', '>', 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') . ' 全部执行完成');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\LhDepositOrder;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class LHDisptchInterest extends Command
|
||||
{
|
||||
protected $signature = "lhdispatch_interest";
|
||||
protected $description = "锁仓派息";
|
||||
protected $lock_daily_return = "";
|
||||
public function handle()
|
||||
{
|
||||
$res = LhDepositOrder::where([
|
||||
'status' => 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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class Locking extends Command
|
||||
{
|
||||
protected $signature = "locking";
|
||||
protected $description = "锁定任务";
|
||||
protected $lock_daily_return = "";
|
||||
public function handle()
|
||||
{
|
||||
$lock_daily_return = Setting::getValueByKey("lock_daily_return");
|
||||
if (empty($lock_daily_return)) {
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
class MakeWallet extends Command
|
||||
{
|
||||
protected $signature = "make:wallet {user_id? : user_id} {--operate=single : the operation type:all,single}";
|
||||
protected $description = "生成钱包";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$userId = $this->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('全部生成完成');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class MonitorEthLog extends Command
|
||||
{
|
||||
protected $signature = "monitor_eth_log";
|
||||
protected $description = "监听以太坊账号";
|
||||
protected $rate_exchange = 0;
|
||||
protected $last_hash = "";
|
||||
protected $company_eth_address = "";
|
||||
public function handle()
|
||||
{
|
||||
$this->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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\LeverTransaction;
|
||||
use App\UsersWallet;
|
||||
use App\AccountLog;
|
||||
class OvernightFee extends Command
|
||||
{
|
||||
protected $signature = "lever:overnight";
|
||||
protected $description = "杠杆交易隔夜费";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$today = strtotime(date('Y-m-d'));
|
||||
$count = LeverTransaction::where('create_time', '<', $today)->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') . ' 全部执行完成');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\UsersWallet;
|
||||
use App\Currency;
|
||||
class RegenerateWallet extends Command
|
||||
{
|
||||
protected $signature = "regenerate:wallet {id : id}";
|
||||
protected $description = "重新生成钱包";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$id = $this->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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
class RemoveQueue extends Command
|
||||
{
|
||||
protected $signature = "remove_queue";
|
||||
protected $description = "定期移除积压任务";
|
||||
public function handle()
|
||||
{
|
||||
$this->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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class ResetDatabase extends Command
|
||||
{
|
||||
protected $signature = "reset_database {force}";
|
||||
protected $description = "清理数据库";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$force = $this->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('命令错误!');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\DAO\FactprofitsDAO;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class ReturnProfit extends Command
|
||||
{
|
||||
protected $signature = "return:profit";
|
||||
protected $description = "返还杠杆交易亏损";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
|
||||
$aaa = new FactprofitsDAO();
|
||||
|
||||
$all = DB::table('lever_transaction')->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));
|
||||
}
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\MicroOrder;
|
||||
use App\UsersInsurance;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class ReturnServiceCharge extends Command
|
||||
{
|
||||
protected $signature = "return_service_charge";
|
||||
protected $description = "返还交易手续费用";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
$this->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') . "执行返还保险交易手续费成功!=========");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\TransactionComplete;
|
||||
use App\Transaction;
|
||||
use App\UserChat;
|
||||
use App\TransactionIn;
|
||||
use App\TransactionOut;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Faker\Factory;
|
||||
use Illuminate\Console\Command;
|
||||
use App\Robot as RobotModel;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
defined('ACCOUNT_ID') or define('ACCOUNT_ID', '50154012'); // 你的账户ID
|
||||
defined('ACCESS_KEY') or define('ACCESS_KEY', 'c96392eb-b7c57373-f646c2ef-25a14'); // 你的ACCESS_KEY
|
||||
defined('SECRET_KEY') or define('SECRET_KEY', ''); // 你的SECRET_KEY
|
||||
|
||||
class Robot extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'robot {id} {--mode=}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '匹配交易自动挂单机器人';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\Level;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\Setting;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class Test extends Command
|
||||
{
|
||||
protected $signature = "Testtest";
|
||||
protected $description = "测试";
|
||||
public function handle()
|
||||
{
|
||||
$this->comment("start");
|
||||
Users::rebate(357, 357, 3, 100, 1, 2);
|
||||
$this->comment("end");
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\TransferEths;
|
||||
use App\UsersWallet;
|
||||
use App\Setting;
|
||||
use App\Currency;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class TransferEth extends Command
|
||||
{
|
||||
protected $signature = "transfer_eth{currency_id : id}";
|
||||
protected $description = "批量转eth";
|
||||
protected $contract_address = "";
|
||||
protected $total_account_address = "";
|
||||
protected $total_account_key = "";
|
||||
protected $currency_type = "";
|
||||
protected $eth_transfer_value = 0.001;
|
||||
public function handle()
|
||||
{
|
||||
$currency_id = $this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\UsersWallet;
|
||||
use App\Jobs\UpdateBalance as UpdateBalanceJob;
|
||||
class UpdateBalance extends Command
|
||||
{
|
||||
protected $signature = "update_balance";
|
||||
protected $description = "更新用户余额";
|
||||
public function handle()
|
||||
{
|
||||
$this->comment("开始执行");
|
||||
UsersWallet::chunk(100, function ($wallets) {
|
||||
$wallets->each(function ($item, $key) {
|
||||
UpdateBalanceJob::dispatch($item)->onQueue('update:block:balance');
|
||||
});
|
||||
});
|
||||
$this->comment("执行完成");
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\Level;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\Setting;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class UpdateFund extends Command
|
||||
{
|
||||
protected $signature = "update_user_fund";
|
||||
protected $description = "更新资产";
|
||||
public function handle()
|
||||
{
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use App\Utils\RPC;
|
||||
use App\{Currency, LbxHash, UsersWallet};
|
||||
use App\DAO\BlockChain;
|
||||
class UpdateHashStatus extends Command
|
||||
{
|
||||
protected $signature = "update_hash_status";
|
||||
protected $description = "更新链上哈希状态";
|
||||
public function handle()
|
||||
{
|
||||
$datas = LbxHash::whereIn('type', [0, 2])->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Utils\RPC;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\HuobiSymbol;
|
||||
use Illuminate\Console\Command;
|
||||
use GuzzleHttp\Client;
|
||||
class UpdateHuobiSymbol extends Command
|
||||
{
|
||||
protected $signature = "update_Huobi_Symbol";
|
||||
protected $description = "更新火币交易对";
|
||||
public function handle()
|
||||
{
|
||||
$this->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");
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use App\{LeverTransaction};
|
||||
use App\Jobs\LeverClose;
|
||||
class UpdateLever extends Command
|
||||
{
|
||||
protected $signature = "remove_task";
|
||||
protected $description = "移除积压任务";
|
||||
public function handle()
|
||||
{
|
||||
$this->comment("开始任务");
|
||||
\Illuminate\Support\Facades\Redis::del('queues:lever:update');
|
||||
$this->comment("结束任务");
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\News;
|
||||
use App\UserReal;
|
||||
use Illuminate\Console\Command;
|
||||
class UpdateNews extends Command
|
||||
{
|
||||
protected $signature = "update_news";
|
||||
protected $description = "更新项目的新闻";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
protected $searches = ["cfmcoin" => "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();
|
||||
}
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\Users;
|
||||
class UpdateParent extends Command
|
||||
{
|
||||
protected $signature = "update:parent";
|
||||
protected $description = "更新用户上级";
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
public function handle()
|
||||
{
|
||||
Users::where('type', 1)->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('全部执行完成');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Illuminate\Console\Command;
|
||||
class UpdatePrivate extends Command
|
||||
{
|
||||
protected $signature = "update_private";
|
||||
protected $description = "更新私钥以及钱包地址";
|
||||
public function handle()
|
||||
{
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\Level;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\Setting;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
class UserLevel extends Command
|
||||
{
|
||||
protected $signature = "update_user_level";
|
||||
protected $description = "更新级别";
|
||||
public function handle()
|
||||
{
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\UserChat;
|
||||
use Illuminate\Console\Command;
|
||||
use Workerman\Connection\AsyncTcpConnection;
|
||||
use Workerman\Worker;
|
||||
use function foo\func;
|
||||
|
||||
class WebSocket extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'websocket {worker_command} {--mode=}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'websocket';
|
||||
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
// $class_name = config('websocket.client.callback_class');
|
||||
// $class_name = \App\Utils\Workerman\WorkerCallback::class;
|
||||
// $process_num = config('websocket.client.process_num');
|
||||
//// $process_num = 1;
|
||||
// $this->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];
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Workerman\Worker;
|
||||
class WebSocketClient extends Command
|
||||
{
|
||||
protected $signature = "websocket:client {worker_command} {--mode=}";
|
||||
protected $description = "websocket client";
|
||||
protected $worker;
|
||||
protected $events = ["onWorkerStart", "onConnect", "onMessage", "onClose", "onError", "onBufferFull", "onBufferDrain", "onWorkerStop", "onWorkerReload"];
|
||||
protected $callback_class;
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$class_name = config('websocket.client.callback_class');
|
||||
$process_num = config('websocket.client.process_num');
|
||||
$this->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];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Workerman\Worker;
|
||||
|
||||
class WebSocketClient extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'websocket:client {worker_command} {--mode=}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'websocket client';
|
||||
|
||||
protected $worker;
|
||||
|
||||
protected $events = [
|
||||
'onWorkerStart',
|
||||
'onConnect',
|
||||
'onMessage',
|
||||
'onClose',
|
||||
'onError',
|
||||
'onBufferFull',
|
||||
'onBufferDrain',
|
||||
'onWorkerStop',
|
||||
'onWorkerReload'
|
||||
];
|
||||
|
||||
protected $callback_class;
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$class_name = config('websocket.client.callback_class');
|
||||
$class_name = \App\Utils\Workerman\WorkerCallback::class;
|
||||
$process_num = config('websocket.client.process_num');
|
||||
// $process_num = 8;
|
||||
// $process_num = 1;
|
||||
$this->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];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Transaction;
|
||||
use App\Users;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
class AccountController extends Controller
|
||||
{
|
||||
|
||||
public function list()
|
||||
{
|
||||
$address = Users::getUserId(Input::get('address', ''));
|
||||
$limit = Input::get('limit', '12');
|
||||
$page = Input::get('page', '1');
|
||||
if (empty($address)) return $this->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Users;
|
||||
use App\News;
|
||||
use App\UserLevelModel;
|
||||
use App\AiCurrency;
|
||||
use App\AiOrder;
|
||||
use App\AiList;
|
||||
use App\UsersWallet;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\CurrencyQuotation;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
|
||||
//AI理财
|
||||
class AiController extends Controller
|
||||
{
|
||||
//显示理财页面
|
||||
public function index(Request $request){
|
||||
|
||||
$user_id =Users::getUserId();
|
||||
|
||||
|
||||
$user = Users::find($user_id);
|
||||
|
||||
$userLevel = $user['user_level'] > 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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
use App\Setting;
|
||||
use App\MicroOrder;
|
||||
use App\Users;
|
||||
|
||||
class ApiController extends Controller
|
||||
{
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
// if ($_init) {
|
||||
// $token = Token::getToken();
|
||||
// $this->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']);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,777 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use App\AccountLog;
|
||||
use App\LegalDealSend;
|
||||
use App\LhBankAccount;
|
||||
use App\LhBankAccountLog;
|
||||
use App\LhBankTeamMember;
|
||||
use App\LhDepositOrder;
|
||||
use App\LhDepositOrderLog;
|
||||
use App\LhLoanOrder;
|
||||
use App\Logic\LhBankProfitLogic;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Cache\RedisLock;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
|
||||
class BankController extends Controller
|
||||
{
|
||||
|
||||
public function test(){
|
||||
|
||||
$accountId = Input::get('id',171);
|
||||
LhBankProfitLogic::updateVipLevel($accountId);
|
||||
//
|
||||
//
|
||||
// LhBankProfitLogic::addInProcessingQueue(1);
|
||||
// LhBankProfitLogic::addInProcessingQueue(2);
|
||||
// LhBankProfitLogic::addInProcessingQueue(3);
|
||||
//
|
||||
// $res = LhBankProfitLogic::getProcessingQueue();
|
||||
//// var_dump($res);exit;
|
||||
// DB::beginTransaction();
|
||||
// try{
|
||||
// LhBankProfitLogic::saveDeposit($accountId,1000);
|
||||
// //存钱后更新M等级
|
||||
// LhBankProfitLogic::teamIncrement($accountId,1000);
|
||||
//
|
||||
// DB::commit();
|
||||
// }catch (\Exception $e){
|
||||
// DB::rollBack();
|
||||
// throw $e;
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function dispatchInterest(){
|
||||
//查询开始时间在今天以前,状态是1的 结息时间小于今天的订单
|
||||
|
||||
$res = LhDepositOrder::where([
|
||||
'status' => 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('还款成功');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use App\AccountLog;
|
||||
use App\LegalDealSend;
|
||||
use App\LhBankAccount;
|
||||
use App\LhBankAccountLog;
|
||||
use App\LhBankTeamMember;
|
||||
use App\LhDepositOrder;
|
||||
use App\LhDepositOrderLog;
|
||||
use App\LhLoanOrder;
|
||||
use App\Logic\LhBankProfitLogic;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Cache\RedisLock;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
use App\ReceivingBankCard;
|
||||
|
||||
|
||||
class BankInfoController extends Controller
|
||||
{
|
||||
|
||||
public function bankList(){
|
||||
$user_id = Users::getUserId();
|
||||
$list = ReceivingBankCard::all();
|
||||
return $this->success($list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use App\AccountLog;
|
||||
use App\LegalDealSend;
|
||||
use App\LhBankAccount;
|
||||
use App\LhBankAccountLog;
|
||||
use App\LhBankTeamMember;
|
||||
use App\LhDepositOrder;
|
||||
use App\LhDepositOrderLog;
|
||||
use App\LhLoanOrder;
|
||||
use App\Logic\LhBankProfitLogic;
|
||||
use App\Setting;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Cache\RedisLock;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
use App\{
|
||||
Address,
|
||||
Currency,
|
||||
UsersInsurance,
|
||||
InsuranceType,
|
||||
InsuranceClaimApply,
|
||||
Users,
|
||||
UserCashInfo,
|
||||
UserReal,
|
||||
UsersWallet,
|
||||
BindBox,
|
||||
BindBoxOrder,
|
||||
BindBoxQuotationLog,
|
||||
BindBoxCollect,
|
||||
BindBoxMarginLog,
|
||||
BindBoxRaityHouse,
|
||||
BindBoxSuccessOrder
|
||||
};
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use App\Service\RedisService;
|
||||
|
||||
class BindBoxController extends Controller
|
||||
{
|
||||
|
||||
|
||||
//获取艺术品列表
|
||||
public function getBoxList(Request $request){
|
||||
$user_id = Users::getUserId();
|
||||
|
||||
$page = $request->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 '完成';
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,992 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\C2cDeal;
|
||||
use App\C2cDealSend;
|
||||
// use App\Seller;
|
||||
use App\LegalDeal;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\UserReal;
|
||||
use App\UserCashInfo;
|
||||
|
||||
class C2cDealController extends Controller
|
||||
{
|
||||
|
||||
|
||||
|
||||
public function handle_one(Request $request)
|
||||
{
|
||||
$id = $request->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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,973 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\UserCashInfo;
|
||||
use Illuminate\Http\Request;
|
||||
use Session;
|
||||
use App\UserChat;
|
||||
use App\Users;
|
||||
use App\UserReal;
|
||||
use App\Token;
|
||||
use App\AccountLog;
|
||||
use App\UsersWallet;
|
||||
use App\UsersWalletcopy;
|
||||
use App\Bank;
|
||||
use App\IdCardIdentity;
|
||||
use App\Currency;
|
||||
use App\InviteBg;
|
||||
use App\Setting;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Utils\RPC;
|
||||
use App\DAO\UserDAO;
|
||||
use App\CandyTransfer;
|
||||
|
||||
class CandyTransferController extends Controller
|
||||
{
|
||||
|
||||
public function show_candynum(Request $request)
|
||||
{
|
||||
$user_id = Users::getUserId();
|
||||
$result['candy_number'] = Users::where('id', $user_id)->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());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\ChatLog;
|
||||
use App\Users;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use GatewayWorker\Lib\Gateway;
|
||||
|
||||
class ChatController extends Controller
|
||||
{
|
||||
//
|
||||
public $user_id;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
Gateway::$registerAddress = '127.0.0.1:2501';
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use App\CoinTrade;
|
||||
use App\Currency;
|
||||
use App\CurrencyMatch;
|
||||
use App\Logic\CoinTradeLogic;
|
||||
use App\Users;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class CoinTradeController extends Controller
|
||||
{
|
||||
public function submit(Request $request){
|
||||
$legal = $request->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('取消成功');
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Users;
|
||||
use App\Token;
|
||||
use Closure;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
use Illuminate\Support\Facades\App;
|
||||
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
public $user_id;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
// if ($_init) {
|
||||
// $token = Token::getToken();
|
||||
// $this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Rate;
|
||||
|
||||
class CrontabController
|
||||
{
|
||||
|
||||
//获取最新货币汇率 1天1次
|
||||
public function getRate(){
|
||||
|
||||
$rate_symbols = [
|
||||
'CNY',
|
||||
'HKD',
|
||||
'JPY',
|
||||
'KRW',
|
||||
'THB',
|
||||
'GBP',
|
||||
];
|
||||
$now_time = time();
|
||||
foreach ($rate_symbols as $rate_symbol){
|
||||
$this->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';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,991 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Service\RedisService;
|
||||
use App\Utils\RPC;
|
||||
use App\Currency;
|
||||
use App\CurrencyMatch;
|
||||
use App\TransactionComplete;
|
||||
use App\Users;
|
||||
use App\MarketHour;
|
||||
use App\CurrencyQuotation;
|
||||
use App\AreaCode;
|
||||
use App\UdunAddress;
|
||||
use App\UsersWallet;
|
||||
use App\WalletAddress;
|
||||
use App\Http\mode\Sina as sina;
|
||||
|
||||
class CurrencyController extends Controller
|
||||
{
|
||||
public function area_code()
|
||||
{
|
||||
$LHaaruJ = AreaCode::get()->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().'<br>';
|
||||
echo $sina->foreign_real().'<br>';
|
||||
echo $sina->etfreal().'<br>';
|
||||
echo $sina->gpreal().'<br>';
|
||||
/*
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use App\AccountLog;
|
||||
use App\CurrencyDepositOrder;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
|
||||
class CurrencyDepositController extends Controller
|
||||
{
|
||||
|
||||
public function dispatch(Request $request){
|
||||
$res = CurrencyDepositOrder::where([
|
||||
'status' => 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');
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use App\AccountLog;
|
||||
use App\CurrencyDepositOrder;
|
||||
use App\CurrencyProjectOrder;
|
||||
use App\CurrencyProject;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class CurrencyProjectController extends Controller
|
||||
{
|
||||
|
||||
public function processOrder(){
|
||||
$list = CurrencyProjectOrder::where('status',2)
|
||||
->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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Bank;
|
||||
use App\Menu;
|
||||
use App\FalseData;
|
||||
use App\Market;
|
||||
use App\Setting;
|
||||
use App\HistoricalData;
|
||||
use App\Users;
|
||||
use App\Utils\RPC;
|
||||
use App\DAO\UploaderDAO;
|
||||
|
||||
class DefaultController extends Controller
|
||||
{
|
||||
|
||||
public function falseData()
|
||||
{
|
||||
$limit = Input::get('limit', '12');
|
||||
$page = Input::get('page', '1');
|
||||
|
||||
$old = date("Y-m-d", strtotime("-1 day"));
|
||||
$old_time = strtotime($old);
|
||||
$time = strtotime(date("Y-m-d"));
|
||||
|
||||
$yesterday = FalseData::where('time', ">", $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);
|
||||
// }
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,389 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Users;
|
||||
use App\DualCurrency;
|
||||
use App\DualOrder;
|
||||
use App\UsersWallet;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\Defi;
|
||||
use App\DefiOrder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
|
||||
//双币理财
|
||||
class DefiController extends Controller
|
||||
{
|
||||
//显示理财页面
|
||||
public function index(Request $request){
|
||||
|
||||
$user_id = Users::getUserId();
|
||||
if(!$user_id){
|
||||
return $this->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Users;
|
||||
use App\UserLevelModel;
|
||||
use App\DualCurrency;
|
||||
use App\DualOrder;
|
||||
use App\DualList;
|
||||
use App\UsersWallet;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\CurrencyQuotation;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
|
||||
//双币理财
|
||||
class DualController extends Controller
|
||||
{
|
||||
//显示理财页面
|
||||
public function index(Request $request){
|
||||
|
||||
$user_id =Users::getUserId();
|
||||
|
||||
|
||||
$user = Users::find($user_id);
|
||||
|
||||
$userLevel = $user['user_level'] > 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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by Vscode
|
||||
* User: LDH
|
||||
* 投诉建议
|
||||
* */
|
||||
namespace App\Http\Controllers\Api;
|
||||
use Illuminate\Http\Request;
|
||||
use Session;
|
||||
use App\FeedBack;
|
||||
use App\CurrencyApplication;
|
||||
use App\Users;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class FeedBackController extends Controller
|
||||
{
|
||||
//反馈信息列表
|
||||
public function myFeedBackList(Request $request){
|
||||
$limit = Input::get('limit', 10);
|
||||
$page = Input::get('page', 1);
|
||||
$user_id = Users::getUserId();
|
||||
$feedBackList = FeedBack::where('user_id', $user_id)
|
||||
->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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Users;
|
||||
use App\LeverTransaction;
|
||||
use App\Follow;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class FollowController extends Controller
|
||||
{
|
||||
//跟单中-交易员列表
|
||||
public function index()
|
||||
{
|
||||
$user_id = 13600881;//Users::getUserId();
|
||||
$list = Users::query()
|
||||
->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\ChargeReq;
|
||||
use App\WalletAddress;
|
||||
use App\UserLevelModel;
|
||||
use App\UsersWallet;
|
||||
use App\AccountLog;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use PHPMailer\PHPMailer\Exception;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class IndexController extends Controller
|
||||
{
|
||||
protected function makeSubscribeTopic($topic_template, $param)
|
||||
{
|
||||
$need_param = [];
|
||||
$match_count = preg_match_all('/\$([a-zA-Z_]\w*)/', $topic_template, $need_param);
|
||||
if ($match_count > 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,400 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\InsuranceClaimApply;
|
||||
use App\InsuranceType;
|
||||
use App\MicroOrder;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\UsersInsurance;
|
||||
use App\UsersWallet;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class InsuranceController extends Controller
|
||||
{
|
||||
/**
|
||||
* 获取保险种类
|
||||
*/
|
||||
public function getInsuranceType()
|
||||
{
|
||||
$currency_id = request('currency_id',0);
|
||||
$currency = Currency::find($currency_id);
|
||||
if(!$currency){
|
||||
return $this->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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,981 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Setting;
|
||||
use App\AccountLog;
|
||||
use App\Currency;
|
||||
use App\CurrencyQuotation;
|
||||
use App\CurrencyMatch;
|
||||
use App\LeverTransaction;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\TransactionComplete;
|
||||
use App\TransactionIn;
|
||||
use App\TransactionOut;
|
||||
use App\Jobs\LeverClose;
|
||||
use App\LeverMultiple;
|
||||
use App\Events\LeverSubmitOrder;
|
||||
|
||||
class LeverController extends Controller
|
||||
{
|
||||
/**
|
||||
* 取交易信息
|
||||
*
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
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("参数错误:(");
|
||||
}
|
||||
$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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Session;
|
||||
use App\Agent;
|
||||
use App\UserCashInfo;
|
||||
use App\UserChat;
|
||||
use App\UserReal;
|
||||
use App\Users;
|
||||
use App\Token;
|
||||
use App\AccountLog;
|
||||
use App\UsersWallet;
|
||||
use App\Currency;
|
||||
use App\Utils\RPC;
|
||||
use App\DAO\UserDAO;
|
||||
use App\DAO\RewardDAO;
|
||||
use App\UserProfile;
|
||||
use App\LhBankAccount;
|
||||
use App\Setting;
|
||||
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
|
||||
|
||||
|
||||
// 模拟账户
|
||||
public function dologin()
|
||||
{
|
||||
|
||||
$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'){
|
||||
|
||||
// Token::clearToken($users->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('验证成功');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\{
|
||||
MailMessage,
|
||||
MailMessageUserLog,
|
||||
Users,
|
||||
UserChat
|
||||
};
|
||||
|
||||
class MailMessageController extends Controller
|
||||
{
|
||||
public function getCount(){
|
||||
$user_id = Users::getUserId();
|
||||
$count = Db::table('mail_message')
|
||||
->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\InsuranceClaimApply;
|
||||
use App\InsuranceRule;
|
||||
use App\Setting;
|
||||
use App\UsersInsurance;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use App\Logic\MicroTradeLogic;
|
||||
use App\Users;
|
||||
use App\CurrencyQuotation;
|
||||
use App\Currency;
|
||||
use App\MicroSecond;
|
||||
use App\UsersWallet;
|
||||
use App\MicroOrder;
|
||||
use App\MarketHour;
|
||||
use App\CurrencyMatch;
|
||||
use App\InsuranceType;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
class MicroOrderController extends Controller
|
||||
{
|
||||
|
||||
/**
|
||||
* 取允许支付的币种
|
||||
*
|
||||
* @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 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;//可以下单
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\InsuranceClaimApply;
|
||||
use App\InsuranceRule;
|
||||
use App\Setting;
|
||||
use App\UsersInsurance;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use App\Logic\MicroTradeLogic;
|
||||
use App\Users;
|
||||
use App\CurrencyQuotation;
|
||||
use App\Currency;
|
||||
use App\MicroSecond;
|
||||
use App\UsersWallet;
|
||||
use App\MicroOrder;
|
||||
use App\MarketHour;
|
||||
use App\CurrencyMatch;
|
||||
use App\InsuranceType;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
class MicroOrderController extends Controller
|
||||
{
|
||||
|
||||
// 获取订单状态
|
||||
public function getOrder(Request $request){
|
||||
$user_id = Users::getUserId();
|
||||
$orderId = $request->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"]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Requests;
|
||||
use App\News;
|
||||
use App\Setting;
|
||||
use App\NewsCategory;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class NewsController extends Controller
|
||||
{
|
||||
|
||||
public function kefu(Request $request)
|
||||
{
|
||||
|
||||
$mobile=Setting::getValueByKey("zxkf_url","");
|
||||
return $this->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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
|
||||
class NoticeController extends Controller
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
|
||||
|
||||
use App\Users;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class OptionalController extends Controller
|
||||
{
|
||||
public function add(Request $request)
|
||||
{
|
||||
$user_id = Users::getUserId();
|
||||
$currency_id = $request->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);
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use App\PayUserInfo;
|
||||
use App\Users;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class PayController extends Controller
|
||||
{
|
||||
public function pay(Request $request){
|
||||
$merchantNo = "3018220814001";
|
||||
$merchantOrderNo = uniqid();
|
||||
$countryCode = $request->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
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\Api;
|
||||
use App\PayUserInfo;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\AccountLog;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class PayNotifyController extends Controller
|
||||
{
|
||||
public function notify(){
|
||||
$json_raw = file_get_contents("php://input");
|
||||
$json_data = (array)json_decode($json_raw);
|
||||
|
||||
$orderNo = $json_data['orderNo'];
|
||||
$orderTime = $json_data['orderTime'];
|
||||
$orderAmount = $json_data['orderAmount'];
|
||||
$countryCode = $json_data['countryCode'];
|
||||
$paymentTime = $json_data['paymentTime'];
|
||||
$merchantOrderNo = $json_data['merchantOrderNo'];
|
||||
$paymentAmount = $json_data['paymentAmount'];
|
||||
$currencyCode = $json_data['currencyCode'];
|
||||
$paymentStatus = $json_data['paymentStatus'];
|
||||
$merchantNo = $json_data['merchantNo'];
|
||||
|
||||
$sign = $json_data['sign'];
|
||||
|
||||
$postdata = array(
|
||||
'orderNo' => $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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\PrizePoolcopy;
|
||||
use App\Users;
|
||||
use App\AccountLog;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use App\DAO\FactprofitsDAO;
|
||||
|
||||
class PrizePoolController extends Controller
|
||||
{
|
||||
public function test555()
|
||||
{
|
||||
$aa=new FactprofitsDAO();
|
||||
$aa::Profit_loss_release(1);
|
||||
}
|
||||
public function candyhistory()//通证奖励记录
|
||||
{
|
||||
$user_id = Users::getUserId();
|
||||
$prize_pool = PrizePoolcopy::where("to_user_id","=",$user_id)->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Currency;
|
||||
use App\Seller;
|
||||
use App\Bank;
|
||||
use App\Setting;
|
||||
use App\UsersWallet;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use App\UserReal;
|
||||
use App\Users;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\AccountLog;
|
||||
use App\Wallet;
|
||||
use App\WalletLog;
|
||||
|
||||
|
||||
|
||||
class SellerController extends Controller
|
||||
{
|
||||
public function lists(Request $request){
|
||||
$limit = $request->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]);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\DAO\Moducloud\SmsSingleSender;
|
||||
use App\DAO\SubmailMailSend;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use PHPMailer\PHPMailer\PHPMailer;
|
||||
use PHPMailer\PHPMailer\Exception;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class SmsController extends Controller
|
||||
{
|
||||
private $_sms_ip_check_expire_time = 60;
|
||||
|
||||
/**
|
||||
* 发送短信
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function send(Request $request)
|
||||
{
|
||||
$ALIYUN_SMS_AK = env("ALIYUN_SMS_AK");
|
||||
$ALIYUN_SMS_AS = env("ALIYUN_SMS_AS");
|
||||
$ALIYUN_SMS_SIGN_NAME = env("ALIYUN_SMS_SIGN_NAME");
|
||||
$ALIYUN_SMS_VARIABLE = env("ALIYUN_SMS_VARIABLE"); //内容变量
|
||||
$tplId = env('ALIYUN_SMS_CODE'); //模版ID 模版CODE 格式为 SMS_140736882
|
||||
|
||||
if (empty($tplId) || empty($ALIYUN_SMS_AK) || empty($ALIYUN_SMS_AS) || empty($ALIYUN_SMS_SIGN_NAME) || empty($ALIYUN_SMS_VARIABLE))
|
||||
return $this->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']}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,929 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Database\Events\TransactionCommitted;
|
||||
use Session;
|
||||
use App\UserChat;
|
||||
use App\AccountLog;
|
||||
use App\Transaction;
|
||||
use App\TransactionComplete;
|
||||
use App\TransactionIn;
|
||||
use App\TransactionOut;
|
||||
use App\TransactionLegal;
|
||||
use App\Users;
|
||||
use App\Currency;
|
||||
use App\Setting;
|
||||
use App\UsersWallet;
|
||||
use App\UserCashInfo;
|
||||
use App\UserReal;
|
||||
|
||||
class TransactionController extends Controller
|
||||
{
|
||||
|
||||
//正在买入记录
|
||||
public function TransactionInList()
|
||||
{
|
||||
$user_id = Users::getUserId();
|
||||
if (empty($user_id)) return $this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,305 @@
|
||||
<?php
|
||||
//钱包专用的控制器 交易所可以删掉这个控制器ldh
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Currency;
|
||||
use App\Ltc;
|
||||
use App\LtcBuy;
|
||||
use App\TransactionComplete;
|
||||
use App\NewsCategory;
|
||||
use App\Address;
|
||||
use App\AccountLog;
|
||||
use App\Setting;
|
||||
use App\Users;
|
||||
use App\UsersWallet;
|
||||
use App\UsersWalletOut;
|
||||
use App\WalletLog;
|
||||
use App\Utils\RPC;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Input;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Http\Requests;
|
||||
|
||||
class WalletOneController extends Controller
|
||||
{
|
||||
public function add(){
|
||||
$user_id = Users::getUserId();
|
||||
// $token = Input::get("token",'');
|
||||
$memorizing_words = Input::get("memorizing_words","");
|
||||
$erc_address = Input::get("address","");
|
||||
$btc_address = Input::get("contentbtc","");
|
||||
// $wallet_name = Input::get("wallet_name","");
|
||||
$password_prompt = Input::get("password_prompt","");
|
||||
$password = Input::get("password","");
|
||||
if($password!=$password_prompt){
|
||||
return $this->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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user