Skip to content

Instantly share code, notes, and snippets.

@Biciato
Created January 20, 2020 18:24
Show Gist options
  • Save Biciato/34faf68a31ce01453c54d5d93538963f to your computer and use it in GitHub Desktop.
Save Biciato/34faf68a31ce01453c54d5d93538963f to your computer and use it in GitHub Desktop.
NioxController
<?php
namespace App\Http\Controllers;
use App\ExchangeWallets;
use App\NioxDeposit;
use App\NioxWithdrawal;
use App\Plan;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class NioxController extends Controller
{
protected $fee = 0.01;
public function __construct()
{
parent::__construct();
$this->middleware('pagamento', ['except'=>['callback', 'afterCallback']]);
}
public function getToken()
{
//Pega a chave e o segredo e cria um base64
$key = 'd6d1850405';
$secret = '759ed1db54cf2a1';
$base64 = base64_encode($key . ':' . $secret . ':' . date('Y-m-d H:i:s'));
//Inicia a curl
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://eth.b2binpay.com/api/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic " . $base64,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//Caso tenha algum erro no curl
if ($err) {
\Log::info($err);
return ['error' => $err];
} else {
$response = json_decode($response, true);
//Caso tenha algum erro de resposta da API
if (isset($response['error'])) {
\Log::info($response['error']);
return ['error' => 'Estamos com problemas. Por favor tente mais tarde'];
} else {
return ['token' => $response['access_token']];
}
}
}
public function paymentOrder($token, $amount)
{
//Manda a ordem de pagamento
$curl = curl_init();
//Token da carteira pra ETH para a ordem de pagamento
$wallet = '1162';
//Tempo de expiração para a transação
$lifetime = '0';
//O sistema aceita qualquer valor a ser pago, mas é necessário setar algum valor
$amount = '1';
//Para a identificação quando retornar o valor para o sistema
$tracking_id = $this->generate_tracking('NioxDeposit');
//Retorno do status do pagamento
$callback = 'https://bo.wioxi.com/niox/callback';
curl_setopt_array($curl, array(
CURLOPT_URL => "https://eth.b2binpay.com/api/v1/pay/bills",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "wallet=" . $wallet . "&amount=" . $amount . "&callback_url=" . $callback . "&tracking_id=" . $tracking_id . "&unique_id=3" . "&lifetime=" . $lifetime,
CURLOPT_HTTPHEADER => array(
"authorization: Bearer " . $token,
"content-type: application/x-www-form-urlencoded",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
//retorna em caso de algum tipo de erro no curl
\Log::info($err);
return $err;
} else {
$response = json_decode($response, true);
if (isset($response['error'])) {
//retorn em caso de algum tipo de erro na API
\Log::info($response);
return $response['error'];
} else {
//Retorna o json
return $response;
}
}
}
public function withdrawal($token, $amount, $address)
{
//Manda o saque
$curl = curl_init();
//Token da carteira NIOX para o saque
$wallet = '543';
//Qual moeda será o saque
$currency = 'NIOX';
//Para a identificação quando retornar o valor para o sistema
$tracking_id = $this->generate_tracking('NioxWithdrawal');
//E necessário colocar um número positivo para identifcação no sistema, sem repetição
$unique_id = $this->getUniqueId();
//Callback
$callback = 'https://bo.wioxi.com/niox/callback';
curl_setopt_array($curl, array(
CURLOPT_URL => "https://gw.b2binpay.com/api/v1/virtualwallets/withdraws",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "virtual_wallet_id=" . $wallet . "&address=" . $address . "&amount=" . $amount . "&currency=" . $currency . "&tracking_id=" . $tracking_id . "&unique_id=" . $unique_id . "&callback_url=" . $callback,
CURLOPT_HTTPHEADER => array(
"authorization: Bearer " . $token,
"content-type: application/x-www-form-urlencoded",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
\Log::info($err['error']);
//retorna em caso de algum tipo de erro no curl
return ['error' => $err];
} else {
$response = json_decode($response, true);
if (isset($response['error'])) {
//retorn em caso de algum tipo de erro na API
\Log::info($response['error']);
return ['error' => $response['error']];
} else {
//Retorna o json
return $response;
}
}
}
public function calcFee($amount)
{
$user = auth()->user();
$token = $this->getToken();
if (isset($token['error'])) {
return ['success' => false, 'error' => 'Teste novamente mais tarde'];
} else {
$token = $token['token'];
$fee = $this->requestWithdrawal($token);
echo $fee;
\Log::info(strval($fee));
$rate = 0;
$pow = 0;
$fee = json_decode($fee, true);
foreach ($fee['data'] as $key => $value) {
if ($value['to']['alpha'] == 'ETH') {
$rate = intval($value['rate']);
$pow = $value['pow'];
}
}
$i = pow($rate / 10, 1 / $pow);
echo $i;
exit();
}
$fee = $this->fee;
$fee = $amount * $fee;
$total = $amount + $fee;
\Log::info("FEE_SEND_CALC: NSD Fee {$fee} - to: {$user->id} - value: " . $amount);
return ['total' => $total, 'partial' => $fee];
}
public function requestQuotation($token)
{
//Inicia a curl
/*$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://gw.b2binpay.com/api/v1/rates/deposit/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer " . $token,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
return $response;*/
}
public function requestWithdrawal($token)
{
//Inicia a curl
/*$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://gw.b2binpay.com/api/v1/rates/withdraw/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer " . $token,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
return $response;*/
}
public function deposit(Request $request)
{
$user = auth()->user();
/*$secret = '6LdKtqsUAAAAAFpZOl05ykOTnHWP73GG6EsS9HD_';
$remoteip = $_SERVER['REMOTE_ADDR'];
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$result_json = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $request->captcha . '&remoteip=' . $remoteip, false, stream_context_create($arrContextOptions));
$result = json_decode($result_json, true);
if(!$result['success'])
{
echo json_encode(['success'=>false, 'error'=>'Tente novamente mais tarde']);
exit();
}*/
$user_wallet = $user->exchangeWallets()->byCurrency(2)->first();
//Verifica o Google Authenticator
if (!$user->google_auth) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.wallet_googlt_auth')]);
exit();
}
$w = $user->exchangeWallets()->byCurrency(2)->first();
if (!$w) {
return $this->respond(['success' => false, 'error' => \Lang::get('exchange.you-need_wallet')]);
}
//Começa o processo com a B2BinPay
//Pega a chave da API temporária, dura 10 minutos
$token = $this->getToken();
if (isset($token['error'])) {
//retorna em caso de algum tipo de erro
return ['success' => false, 'error' => $token['error']];
exit();
} else {
//Pega o token XD
$token = $token['token'];
$order = $this->paymentOrder($token, $request->amount);
if (isset($order['error'])) {
echo json_encode(['success' => false, 'error' => $order['error']]);
exit();
}
//Caso seja string, é erro
if (is_string($order)) {
echo json_encode(['success' => false, 'error' => $order]);
exit();
}
$QRCode = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . $order['data']['address'];
$url = $order['data']['url'];
$address = $order['data']['address'];
$user->createNiox($order, 'deposit');
echo json_encode(['success' => true, 'data' => ['qr_code' => $QRCode, 'url' => $url, 'address' => $address]]);
}
}
public function verifyInternalTransfer($request)
{
$user = auth()->user();
\Log::info($request);
//Verifica se o endereço está no sistema
$internal_address = NioxDeposit::where('address', $request->address)->first();
//se for null é porque não está no sistema, retorna false e faz o processo da B2BinPay
if (is_null($internal_address)) {
return false;
} else if ($user->id == $internal_address->user_id) {
//Se for do mesmo usuário, passa para o processo da B2BinPay
return false;
} else {
$sum_total = $user->nioxWithdrawal()->where('created_at', '>=', date('Y-m-d'))->where('trans_env', 'internal')->sum('amount_no_fee');
$sum_total = is_null($sum_total) ? 0 : $sum_total;
if($sum_total >= 100000000)
{
return -1;
}
$sum = $sum_total + $request->amount_no_fee;
if($sum > 100000000) {
$total = 100000000 - $sum_total;
return floatval($total);
}
try {
//Primeiro prepara o usuário que vai sacar
//Cria o nosso hash
$transaction = $this->getHashInternalTransaction();
//Prepara o array que vai para a criação do saque
$withdrawal = [];
$withdrawal['data'] = [];
$withdrawal['data']['address'] = $request->address;
$withdrawal['data']['tracking_id'] = null;
$withdrawal['data']['unique_id'] = null;
$withdrawal['data']['transaction'] = $transaction;
$withdrawal['data']['status'] = 10;
$withdrawal['data']['trans_env'] = 'internal';
$create = $user->createNiox($withdrawal, 'withdrawal', 'internal', $request->amount, $request->amount_no_fee, $request->description);
} catch (Exception $e) {
\Log::info($e);
return json_encode(['success' => false, 'error' => $e]);
exit();
}
return 'sim';
}
}
public function externalTransfer($request)
{
$user = auth()->user();
//Primeiro prepara o usuário que vai sacar
//Para a identificação quando retornar o valor para o sistema
$tracking_id = $this->generate_tracking('NioxWithdrawal');
//E necessário colocar um número positivo para identifcação no sistema, sem repetição
$unique_id = $this->getUniqueId();
//Prepara o array que vai para a criação do saque
$withdrawal = [];
$withdrawal['data'] = [];
$withdrawal['data']['address'] = $request->address;
$withdrawal['data']['tracking_id'] = $tracking_id;
$withdrawal['data']['unique_id'] = $unique_id;
$withdrawal['data']['transaction'] = null;
$withdrawal['data']['status'] = 11;
$withdrawal['data']['description'] = $request->description;
$create = $user->createNiox($withdrawal, 'withdrawal', 'external', $request->amount, $request->amount_no_fee, $request->description);
}
public function automaticWithdrawal(Request $request)
{
$user = auth()->user();
/*$user_wallet = $user->exchangeWallets()->byCurrency(2)->first();
$secret = '6LdKtqsUAAAAAFpZOl05ykOTnHWP73GG6EsS9HD_';
$remoteip = $_SERVER['REMOTE_ADDR'];
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$result_json = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $request->captcha . '&remoteip=' . $remoteip, false, stream_context_create($arrContextOptions));
$result = json_decode($result_json, true);
if(!$result['success'])
{
echo json_encode(['success'=>false, 'error'=>'Tente novamente mais tarde']);
exit();
}*/
// Checks if user changed amount
if ($this->isAmountFeeChanged($request->amount_no_fee, $request->amount)) {
return response()->json(['success' => false, 'error' => \Lang::get('exchange.withdrawal-try-again')], 500);
}
//Verifica o Google Authenticator
if (!$user->google_auth) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.wallet_googlt_auth')]);
exit();
}
$w = $user->exchangeWallets()->byCurrency(2)->first();
if (!$w) {
return $this->respond(['success' => false, 'error' => \Lang::get('exchange.you-need_wallet')]);
}
if (!$user->contracts()->active()->first()) {
return $this->respond(['success' => false, 'error' => \Lang::get('exchange.u_need_contract')]);
}
//Verifica se o saldo é menor que 100
if ($request->amount_no_fee < 100) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.100-niox')]);
exit();
}
//Verifica se o saldo é maior que 1,000,000
if ($request->amount_no_fee > 100000000) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.only-make-transactions')]);
exit();
}
/*$exceptions_id = [63170, 615, 12245, 12298, 10239, 12400, 12381, 10182, 17360];
if (in_array($user->id, $exceptions_id)) {
if ($request->amount_no_fee > 500000) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.only-make-transactions')]);
exit();
}
} else {
if ($request->amount_no_fee > 50000) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.only-make-transactions')]);
exit();
}
}*/
//Verifica se tem saldo
$balance = $user->fakeBalances()->where('currency_id', 2)->first();
$balance = $balance->balance ? $balance->balance : 0;
if ($balance < $request->amount) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.insufficient-funds')]);
exit();
}
if ($request->amount == 0) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.withdrawal-try-again')]);
exit();
}
######## USUÁRIOS QUE NÃO PODEM FAZER SAQUE NO MOMENTO ########
$users_no = [30481, 27174];
if (in_array($user->id, $users_no)) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.withdrawal-try-again')]);
exit();
}
######## USUÁRIOS QUE NÃO PODEM FAZER SAQUE NO MOMENTO ########
//Verifica o PIN
$pin = $user->pin;
if (!$pin || !$request->has('pin') || !\Hash::check($request->pin, $pin)) {
return json_encode(['success' => false, 'error' => \Lang::get('exchange.correct-pin')]);
}
//Pega as duas primeiras letras do endereço
$str = substr($request->address, 0, 2);
//Senão for 0x, não é carteira Ethereum e não vai funcionar
if ($str != '0x') {
return json_encode(['success' => false, 'error' => \Lang::get('exchange.incorrect-address')]);
exit();
}
//Verifica quantos saques tem no dia, se já tiver 5 não deixa fazer
$withdrawals_day = $user->nioxWithdrawal()->where('created_at', '>=', date('Y-m-d'))->count();
if ($user->id != 20539) {
if ($withdrawals_day >= 5) {
echo response()->json(['success' => false, 'error' => \Lang::get('exchange.limit-withdrawals')]);
exit();
}
/*if (in_array($user->id, $exceptions_id)) {
if ($withdrawals_day >= 20) {
echo response()->json(['success' => false, 'error' => \Lang::get('exchange.limit-withdrawals')]);
exit();
}
} else {
if ($withdrawals_day >= 5) {
echo response()->json(['success' => false, 'error' => \Lang::get('exchange.limit-withdrawals')]);
exit();
}
}*/
}
//Verifica se o endereço já está no nosso banco, então criamos uma transação interna
$internal_address = $this->verifyInternalTransfer($request);
//Se for int, é a valor máximo que o usuário pode sacar hoje
if(is_float($internal_address)){
return $this->respond(['success'=>false, 'error'=>'You have reached your 1,000,000 NIOX limit today (internal withdraw). Try to withdraw '. $internal_address .' Niox.']);
}
//Se for -1 é pq já atingiu o limite hoje
if($internal_address == -1)
{
return $this->respond(['success'=>false, 'error'=>'You have reached your 1,000,000 NIOX limit today (internal withdraw).']);
}
//Se for true, o processo já foi feito e pode finalizar o processo
if ($internal_address == 'sim') {
return $this->respond(['success' => true, 'message' => \Lang::get('exchange.internal-transfer')]);
}
//Verifica se as transações externas estão em manutenção
if (file_exists('withdraw.txt')) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.withdrawal-try-again')]);
exit();
}
$sum_total = $user->nioxWithdrawal()->where('created_at', '>=', date('Y-m-d'))->where('trans_env', 'external')->sum('amount_no_fee');
$sum_total = is_null($sum_total) ? 0 : $sum_total;
$exceptions_id = [615, 20459, 36508, 36514, 20539];
if(in_array($user->id, $exceptions_id))
{
if($sum_total >= 10000000)
{
return $this->respond(['success'=>false, 'error'=>'You have reached your 10,000,000 NIOX limit today (withdraw external).']);
}
$sum = $sum_total + $request->amount_no_fee;
if($sum > 10000000) {
$total = 10000000 - $sum_total;
return $this->respond(['success'=>false, 'error'=>'You have reached your 10,000,000 NIOX limit today (withdraw external). Try to withdraw '. $total .' Niox.']);
}
}
else
{
$totalPerWeek = collect($user->nioxWithdrawal()->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->whereUserId(36526)->get())
->sum('amount_no_fee');
if($totalPerWeek >= 3000000)
{
return $this->respond(['success'=>false, 'error'=>'You have reached your 3,000,000 NIOX limit today (withdraw external).']);
}
$sum = $totalPerWeek + $request->amount_no_fee;
if($sum > 3000000) {
$total = 3000000 - $totalPerWeek;
return $this->respond(['success'=>false, 'error'=>'You have reached your 3,000,000 NIOX limit today (withdraw external). Try to withdraw '. $total .' Niox.']);
}
}
if (in_array($user->id, $exceptions_id)) {
if ($request->amount_no_fee > 10000000) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.only-make-transactions')]);
exit();
}
} else {
if ($request->amount_no_fee > 500000) {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.only-make-transactions')]);
exit();
}
}
//Verifica se o saque externo é maior que 15 mil, ele vai primeiro para uam aprovação
if ($request->amount_no_fee >= 500000) {
$external = $this->externalTransfer($request);
echo json_encode(['success' => true, 'message' => \Lang::get('exchange.external-transfer')]);
exit();
}
//Começa o processo com a B2BinPay
//Pega a chave da API temporária, dura 10 minutos
$token = $this->getToken();
if (isset($token['error'])) {
//retorna em caso de algum tipo de erro
echo json_encode(['success' => false, 'error' => $token['error']]);
exit();
} else {
//Pega o token XD
$token = $token['token'];
$withdrawal = $this->withdrawal($token, $request->amount_no_fee, $request->address);
if (isset($withdrawal['error'])) {
if ($withdrawal['error'] == 'RESULT_WITHDRAW_ERROR_TEMPORARY_NO_FUNDS') {
//Coloca em manutenção de saque externo
if (!file_exists('withdraw.txt')) {
$myfile = fopen("withdraw.txt", "w") or die("Unable to open file!");
$arq = true;
fwrite($myfile, $arq);
fclose($myfile);
}
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.withdrawal-try-again')]);
exit();
}
echo json_encode(['success' => false, 'error' => $withdrawal['error']]);
exit();
}
//Caso seja string, é erro
if (is_string($withdrawal)) {
if ($withdrawal == 'RESULT_WITHDRAW_ERROR_TEMPORARY_NO_FUNDS') {
echo json_encode(['success' => false, 'error' => \Lang::get('exchange.withdrawal-try-again')]);
exit();
}
echo json_encode(['success' => false, 'error' => $withdrawal]);
exit();
}
$withdrawal['data']['description'] = $request->description;
$create = $user->createNiox($withdrawal, 'withdrawal', 'external', $request->amount, $request->amount_no_fee, $request->description);
echo json_encode(['success' => true, 'data' => $withdrawal, 'message' => \Lang::get('exchange.success-withdrawal')]);
}
}
public function callback(Request $request)
{
echo 'OK';
\Log::info($_REQUEST);
if ($_SERVER['HTTP_X_FORWARDED_FOR'] == '2a01:4f8:c0c:4e15::2' || $_SERVER['HTTP_CF_IPCOUNTRY'] == 'DE') {
$this->afterCallback($_REQUEST);
} else {
\Log::info('TENTATIVA DE ACESSO:');
\Log::info($_SERVER);
\Log::info($_REQUEST);
}
}
public function afterCallback($data)
{
if (strpos($data['tracking_id'], 'DP-') !== false) {
try {
//Primeiro procura se ela está no sistema
$tracking_id = isset($data['tracking_id']) ? $data['tracking_id'] : '';
$deposit = NioxDeposit::where('tracking_id', $tracking_id)->firstOrFail();
//Pega o valor atual desse endereço
$actual_amount = 0;
//Pega o valor total desta chamada
$amount = 0;
$expired = '';
//Se o callback não retorna transactions é só um aviso, caso tenha é um aviso de tentativa/pagamento
if (isset($data['transactions'])) {
//Pega o json de transactions que tem no sistema
$json_transactions = !empty($deposit->transactions) ? json_decode($deposit->transactions, true) : array();
foreach ($data['transactions'] as $key => $value) {
//Verifica se o retorno é um erro ou não
if ($value['status'] >= 1) {
//Verifica se a transação já foi computada, senão pega o valor e salva junto com as outras para o novo json
if (!in_array($value['transaction'], $json_transactions)) {
//Faz as conta do valor que foi pago
$pow = pow(10, intval($value['pow']));
$amount += floatval($value['amount']) / floatval($pow);
//Adiciona o endereço da transação
array_push($json_transactions, $value['transaction']);
}
}
}
//Pra ter certeza que caso ocorra um callback não salve saldo zerado, pois não teve atualização na transação
if ($amount > 0) {
//Adiciona ao valor total pago do endereço
$actual_amount = (!is_null($deposit->amount)) ? $amount + $deposit->amount : $amount;
//Verifica se o endereço é expiravel
$expired = !empty($data['expired']) ? $data['expired'] : null;
// Atualizar Saldo, com o valor desta chamada
$user = User::where('id', $deposit->user_id)->first();
$balance = $user->fakeBalances()->where('currency_id', 2)->first();
$previous_balance = $balance->balance;
$balance->increment('balance', $amount);
//Atualiza os outros dados no banco
NioxDeposit::where('tracking_id', $tracking_id)->update([
'amount' => $actual_amount,
'status' => $data['status'],
'expired' => $expired,
'transactions' => json_encode($json_transactions),
'date_payment' => $data['created'],
]);
$user->NioxHistory()->create([
'type' => 'Deposit',
'niox_id' => $deposit->id,
'amount' => $amount,
'previous_balance' => $previous_balance,
'new_balance' => $balance->balance,
'trans_env' => 'external',
]);
}
} else {
//Se o status for -1 é apenas um aviso que o endereço foi expirado, não precisa fazer nada
if ($data['status'] == -1) {
exit();
} else {
//Verifica se o endereço é expiravel
$expired = !empty($data['expired']) ? $data['expired'] : null;
NioxDeposit::where('tracking_id', $data['tracking_id'])->update([
'status' => $data['status'],
'expired' => $expired,
]);
}
}
} catch (Exception $e) {
\Log::info(strval(json_encode($data)));
\Log::info('Erro Callback Niox: ' . $e);
}
}
if (strpos($data['tracking_id'], 'SQ-') !== false) {
try {
//Primeiro procura se ela está no sistema
$tracking_id = isset($data['tracking_id']) ? $data['tracking_id'] : '';
$withdrawal = NioxWithdrawal::where('tracking_id', $tracking_id)->firstOrFail();
//Pega o valor aqui, se não for uma atualização positiva já temos o valor salvo no banco
$amount = $withdrawal->amount;
/*if ($data['status'] == -2) {
//Pega a carteira para a retirada do dinheiro
$user = User::where('id', $withdrawal->user_id)->first();
$balance = $user->fakeBalances()->where('currency_id', 2)->first();
$balance->increment('balance', $amount);
}*/
//É porque deu erro na transação e depois retomou o processo
/*if($data['status'] >= 1 && $withdrawal->status == -2)
{
//Pega a carteira para a retirada do dinheiro
$user = User::where('id', $withdrawal->user_id)->first();
$balance = $user->fakeBalances()->where('currency_id', 2)->first();
$balance->decrement('balance', $amount);
\Log::info('NIOX RETIRADO NOVAMENTE: '. $amount . ' user_id: '. $data['tracking_id']);
}*/
//Atualiza os outros dados no banco
NioxWithdrawal::where('tracking_id', $tracking_id)->update([
'status' => $data['status'],
'transaction' => isset($data['transaction']) ? $data['transaction'] : null,
]);
} catch (Exception $e) {
\Log::info(strval(json_encode($data)));
\Log::info('Erro Callback Niox: ' . $e);
}
}
}
public function generate_tracking($model)
{
$tracking_id = '';
do {
$now = strtotime('now');
$rand = rand(1, 1000);
$string = ($model == 'NioxDeposit') ? 'DP' : 'SQ';
$tracking_id = $string . '-' . $now . '-' . $rand;
if ($model == 'NioxDeposit') {
$search = NioxDeposit::where('tracking_id', $tracking_id)->first();
} else {
$search = NioxWithdrawal::where('tracking_id', $tracking_id)->first();
}
} while (!is_null($search));
return $tracking_id;
}
public function getHashInternalTransaction()
{
$init_hash = 'NX';
$hash = '';
do {
$now = strtotime('now');
$alphabet = 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$random = implode($pass);
$hash = $init_hash . $now . $random;
$search = NioxWithdrawal::whereJsonContains('address', $hash);
} while (is_null($search));
return $hash;
}
public function getUniqueId()
{
$unique_id = hexdec(uniqid());
do {
$search = NioxWithdrawal::where('unique_id', $unique_id)->first();
} while (!is_null($search));
return $unique_id;
}
public function isAmountFeeChanged($amountWithoutFee, $amountWithFee) {
$amountParsed = floatval($amountWithoutFee);
$val = $amountParsed + ($amountParsed * 0.01);
return $val !== floatval($amountWithFee);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment