raw($messageText, function ($message) use ($recipients, $title) { $message->subject($title); $message->to($recipients); }); } catch (Throwable $t) { Log::error('-------- Mail not sent -----------'); Log::error($t->getMessage()); } // return $this->successResponse("mail envoye"); } public function sendPushNotificationToUser($user_code, $message, $data = null, $date = null) { try { $client = new \GuzzleHttp\Client([ 'base_uri' => env('NOTIFICATION_SERVICE_URL'), ]); $headers = [ 'Authorization' => env('NOTIFICATION_SERVICE_KEY'), ]; $body = new \stdClass(); $body->user_code = $user_code; $body->message = $message; $body->data = $data; try { $body->date = ($date instanceof \DateTime) ? $date->format('Y-m-d H:i:s') : $date; } catch (Throwable $t) { Log::error($t->getMessage()); $body->date = $date; } $promise = $client->requestAsync('POST', '/onesignal/pushToUser', ['json' => $body, 'headers' => $headers])->then(); // function (ResponseInterface $res) { // echo $res->getStatusCode() . "\n"; // }, // function (RequestException $e) { // echo $e->getMessage() . "\n"; // echo $e->getRequest()->getMethod(); // } // ); $promise->wait(); // return $response->getBody()->getContents(); } catch (Throwable $t) { Log::error('-------- User notification not sent-----------'); Log::error($t->getMessage()); } } public function sendPushNotificationToAgent($agent_code, $message, $data = null, $date = null) { try { $client = new \GuzzleHttp\Client([ 'base_uri' => env('NOTIFICATION_SERVICE_URL'), ]); $headers = [ 'Authorization' => env('NOTIFICATION_SERVICE_KEY'), ]; $body = new \stdClass(); $body->agent_code = $agent_code; $body->message = $message; $body->data = $data; try { $body->date = ($date instanceof \DateTime) ? $date->format('Y-m-d H:i:s') : $date; } catch (Throwable $t) { Log::error($t->getMessage()); $body->date = $date; } $promise = $client->requestAsync('POST', '/onesignal/pushToAgent', ['json' => $body, 'headers' => $headers])->then(); $promise->wait(); } catch (Throwable $t) { Log::error('-------- Agent notification not sent-----------'); Log::error($t->getMessage()); } } public function checkPassword($password, $encrypted_password, $salt) { $encrypted_password_to_check = base64_encode(sha1($password . $salt, true) . $salt); return $encrypted_password_to_check == $encrypted_password; } public function hashSSHA($string) { $salt = sha1(rand()); $salt = substr($salt, 0, 10); $encrypted = base64_encode(sha1($string . $salt, true) . $salt); $hash = array("salt" => $salt, "encrypted" => $encrypted); return $hash; } public function getCountryName($id_country) { return Country::findOrFail($id_country)->name; } public function getNetworkName($id_network) { return Network::findOrFail($id_network)->name; } public function toMoneyWithNetwork($amount, $id_network) { $currency = collect(DB::select('SELECT cu.code FROM networks n INNER JOIN countries c ON c.id = n.country_id INNER JOIN currencies cu ON cu.id = c.idCurrency WHERE n.id = :id', ['id' => $id_network]))->first(); $money = Money::of(round($amount, 2), $currency ? $currency->code : 'XAF', new AutoContext()); return $money->formatTo(app()->getLocale()); } public function toMoney($amount, $id_country) { $country = Country::findOrFail($id_country); $money = Money::of(round($amount, 2), $country->currency->code, new AutoContext()); return $money->formatTo(app()->getLocale()); } public function toMoneyWithCurrencyCode($amount, $currency_code) { $money = Money::of(round($amount, 2), $currency_code, new AutoContext()); return $money->formatTo(app()->getLocale()); } private function convertMoney($amount, $init_country, $final_country) { // set to whatever your rates are relative to $baseCurrency = 'USD'; // use your own credentials, or re-use your existing PDO connection $pdo = new PDO('mysql:host=' . env('DB_HOST') . ';dbname=' . env('DB_DATABASE'), env('DB_USERNAME'), env('DB_PASSWORD')); $configuration = new PDOProviderConfiguration(); $configuration->tableName = 'exchange_rate'; $configuration->exchangeRateColumnName = 'exchange_rate'; $configuration->targetCurrencyColumnName = 'target_currency'; $configuration->sourceCurrencyCode = $baseCurrency; // this provider loads exchange rates from your database $provider = new PDOProvider($pdo, $configuration); // this provider calculates exchange rates relative to the base currency $provider = new BaseCurrencyProvider($provider, $baseCurrency); // this currency converter can now handle any currency pair $converter = new CurrencyConverter($provider); $init_country = Country::findOrFail($init_country); $final_country = Country::findOrFail($final_country); $init_money = Money::of(round($amount, 2), $init_country->currency->code, new AutoContext()); return $converter->convert($init_money, $final_country->currency->code, RoundingMode::DOWN); } public function toMoneyWithCurrency($amount, $init_country, $final_country) { return $this->convertMoney($amount, $init_country, $final_country)->formatTo(app()->getLocale()); } public function toMoneyAmount($amount, $init_country, $final_country) { return $this->convertMoney($amount, $init_country, $final_country)->getAmount()->toFloat(); } public function toUSDAmount($amount, $init_country, $final_currency_code = 'USD') { // set to whatever your rates are relative to $baseCurrency = 'USD'; // use your own credentials, or re-use your existing PDO connection $pdo = new PDO('mysql:host=' . env('DB_HOST') . ';dbname=' . env('DB_DATABASE'), env('DB_USERNAME'), env('DB_PASSWORD')); $configuration = new PDOProviderConfiguration(); $configuration->tableName = 'exchange_rate'; $configuration->exchangeRateColumnName = 'exchange_rate'; $configuration->targetCurrencyColumnName = 'target_currency'; $configuration->sourceCurrencyCode = $baseCurrency; // this provider loads exchange rates from your database $provider = new PDOProvider($pdo, $configuration); // this provider calculates exchange rates relative to the base currency $provider = new BaseCurrencyProvider($provider, $baseCurrency); // this currency converter can now handle any currency pair $converter = new CurrencyConverter($provider); $init_country = Country::findOrFail($init_country); $init_money = Money::of(round($amount, 2), $init_country->currency->code, new AutoContext()); return $converter->convert($init_money, $final_currency_code, RoundingMode::DOWN)->getAmount()->toFloat(); } // public function getTransactionID(){ // $d = new DateTime(); // $first = str_replace(['-',':'], '',$d->format("y-m-d H:i:s.u")); // return str_replace(' ' ,'.',$first); // } public function getCurrency($id_country) { $cc = CountriesCurrency::findOrFail($id_country); return $cc->currency_code; } public function arrayPaginator($array, Request $request) { $page = $request->query('page', 1); $perPage = 10; $offset = ($page * $perPage) - $perPage; return new LengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array), $perPage, $page, ['path' => $request->url(), 'query' => $request->query()]); } public function array_has_dupes($array) { // streamline per @Felix return count($array) !== count(array_unique($array)); } //Calcul des taxes public function calculateTax(array $taxes, $frais) { $sommeTaux = 0; $sommeFixe = 0; foreach ($taxes as $tax) { if ($tax->type == '%') $sommeTaux += $tax->valeur; if ($tax->type == 'fixe') $sommeFixe += $tax->valeur; } return ($frais * $sommeTaux / 100) + $sommeFixe; } public function checkMyIdentification($id) { $identification = Identification::where('id_user', $id)->first(); if (isset($identification)) { if ($identification->status == 0) return $this->errorResponse(trans('errors.validation_identification_required')); else return $identification; } else { return $this->errorResponse(trans('errors.identification_required')); } } public function generateGroupCode($length = 8) { $characters = '23456789ABCDEFGHJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } public function generateTransactionCode($length = 12) { $characters = '23456789ABCDEFGHJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } // Fonction de tri par date public function sortFunction($a, $b) { return strtotime($b->date_creation) - strtotime($a->date_creation); } public function refundAllNanoCredit() { // \Log::info('cron refund credit --'); $credits = UsersDemandesCredit::where('etat', 'VALIDE')->where('date_remboursement_prevu', '<=', Carbon::today())->get(); foreach ($credits as $demande_credit) { $user = User::findOrFail($demande_credit->id_user); $walletUser = WalletsUser::where('idUser', $demande_credit->id_user)->firstOrFail(); $this->refundNanoCredit($demande_credit, $user, $walletUser); } } public function refundNanoCredit(UsersDemandesCredit $demande_credit, User $user, WalletsUser $walletUser) { $init_country = $user->network->country->id; $montantDejaRembourse = $demande_credit->montant_rembourse; $montantCreditRestant = $user->balance_credit; $montantARembourser = ($montantCreditRestant > $walletUser->balance) ? $walletUser->balance : $montantCreditRestant; $quota = $montantARembourser / ($montantDejaRembourse + $montantCreditRestant); if ($quota == 0) { // Solde egale zero donc pas de remboursement $message = trans('messages.reload_your_account'); $title = trans('messages.failed_nano_credit_refunded'); } else { $partialRefund = false; $user->balance_credit -= $montantARembourser; $walletUser->balance -= $montantARembourser; $demande_credit->montant_rembourse += $montantARembourser; $resteARembourser = $user->balance_credit; if ($resteARembourser == 0) $demande_credit->etat = 'REMBOURSE'; else { $partialRefund = true; $demande_credit->partiellement_rembourse = true; } if ($demande_credit->type_caution == 'individuel') { // Repartition des interet entre agents $walletAgent = Wallet::findOrFail($demande_credit->id_wallet_agent); $network_agent = NetworksAgent::findOrFail($walletAgent->id_networkAgent); $config = ConfigWallet::where('id_network', $network_agent->network_id)->firstOrFail(); // Recuperation des wallets hyperviseur et superviseur $codeGenerer = CodeGenerer::findOrFail($network_agent->codeGenerer_id); $superviseur = AgentPlus::where('code_membre', $codeGenerer->code_parrain)->firstOrFail(); $hyperviseur = AgentPlus::where('code_membre', $superviseur->code_parrain)->firstOrFail(); $wallet_agent_sup = WalletAgent::where('agent_id', $superviseur->id)->firstOrFail(); $wallet_agent_hyp = WalletAgent::where('agent_id', $hyperviseur->id)->firstOrFail(); $walletSuperviseur = Wallet::findOrFail($wallet_agent_sup->wallet_id); $walletHyperviseur = Wallet::findOrFail($wallet_agent_hyp->wallet_id); $walletAgent->balance_com += floatval($demande_credit->interet * $quota * $config->taux_com_ag_nano_credit / 100); $walletSuperviseur->balance_com += floatval($demande_credit->interet * $quota * $config->taux_com_sup_nano_credit / 100); $walletHyperviseur->balance_com += floatval($demande_credit->interet * $quota * $config->taux_com_hyp_nano_credit / 100); $walletAgent->save(); $walletSuperviseur->save(); $walletHyperviseur->save(); } if ($demande_credit->type_caution == 'groupe') { // Recuperation des wallets hyperviseur et superviseur $group = InfosUsersGroup::findOrFail($user->group_id); $walletHyper = WalletAgent::where('category', 'hyper')->where('network_id', $group->id_network)->firstOrFail(); $walletHyper = Wallet::findOrFail($walletHyper->wallet_id); $walletHyper->balance_princ += $montantARembourser * $quota; $walletHyper->balance_com += $demande_credit->interet * $quota; $walletHyper->save(); } $demande_credit->date_remboursement = $this->getCurrentTime($init_country); $demande_credit->montant = $resteARembourser; $walletUser->save(); $user->save(); $demande_credit->save(); $message = trans('messages.successful_nano_credit_demand_refunded', ['id_demand' => $demande_credit->id_demande, 'amount' => $this->toMoney($montantARembourser, $init_country), 'duration' => $demande_credit->duree_mois, 'net' => $this->toMoney($montantARembourser - $demande_credit->interet * $quota - $demande_credit->taxe * $quota, $init_country), 'fees' => $this->toMoney($demande_credit->interet * $quota, $init_country), 'tax' => $this->toMoney($demande_credit->taxe * $quota, $init_country)]); $title = (!$partialRefund) ? trans('messages.successful_nano_credit_refunded') : trans('messages.successful_nano_credit_partially_refunded'); } $this->sendMail($user->email, $title, $message); return $title . "\n" . $message; } //Envoyer la trame au reseau payeur externe public function sendFrame($paying_network_url, WalletIlinkTransaction $transaction, $code_retrait = null) { $client = new \GuzzleHttp\Client(); $trame = new \stdClass(); $trame->ID = $transaction->id_transaction; if (isset($transaction->id_wallet_user)) { $wallet_user = collect(DB::select("SELECT * FROM wallet_user WHERE id_wallet = :id", ['id' => $transaction->id_wallet_user]))->first(); $identification = Identification::where('id_user', $wallet_user->id)->firstOrFail(); $trame->id_emetteur = $wallet_user->user_code; $trame->type_document_emetteur = $identification->identity_document; $trame->id_document_emetteur = $identification->id_identity_document; $trame->prenom_emetteur = $identification->firstname; $trame->nom_emetteur = $identification->lastname; $trame->email_emetteur = $wallet_user->email; } else { $trame->type_document_emetteur = $transaction->type_document_emetteur; $trame->id_document_emetteur = $transaction->id_document_emetteur; $trame->prenom_emetteur = $transaction->prenom_emetteur; $trame->nom_emetteur = $transaction->nom_emetteur; $trame->email_emetteur = $transaction->email_emetteur; } $trame->id_destinataire = $transaction->id_destinataire; $trame->type_document_destinataire = $transaction->type_document_destinataire; $trame->id_document_destinataire = $transaction->id_document_destinataire; $trame->montant = $transaction->montant_net_final_country; $trame->montant_commission = $transaction->part_reseau_payeur_final_country; if ($code_retrait) $trame->code_retrait = $code_retrait; $trame->currency = CountriesCurrency::findOrFail($transaction->final_country)->currency_code; return $client->request('POST', $paying_network_url, ['json' => $trame]); // return $response->getBody()->getContents(); } // Verification du code IBAN // 0 si code invalide // 1 si le pays ne correspond pas // 2 si le code la banque est incorrect // 3 si tout est ok public function checkIBAN($iban, $country_code, $bank_code = null) { // Normalize input (remove spaces and make upcase) $iban = strtoupper(str_replace(' ', '', $iban)); if (preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $iban)) { $country = substr($iban, 0, 2); if ($country != $country_code) return 1; // $check = intval(substr($iban, 2, 2)); $code_bank = substr($iban, 4, 4); if ($code_bank != $bank_code) return 2; // $account = substr($iban, 4); // // To numeric representation // $search = range('A', 'Z'); // foreach (range(10, 35) as $tmp) // $replace[] = strval($tmp); // $numstr = str_replace($search, $replace, $account . $country . '00'); // // // Calculate checksum // $checksum = intval(substr($numstr, 0, 1)); // for ($pos = 1; $pos < strlen($numstr); $pos++) { // $checksum *= 10; // $checksum += intval(substr($numstr, $pos, 1)); // $checksum %= 97; // } // return ((98 - $checksum) == $check) ? 3 : 0; return 3; } else return 0; } // Obtenir l'heure en fonction du pays de l'utilisateur public function getCurrentTime($id_country) { $country = Country::find($id_country); $country_code = isset($country) ? $country->code_country : 'GA'; $timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code); $date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime(); return $date->format('Y-m-d H:i:s'); } // Obtenir l'heure en fonction du code du pays de l'utilisateur public function getCurrentTimeByCountryCode($country_code = 'GA') { $timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code); $date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime(); return $date->format('Y-m-d H:i:s'); } // Verifier l'identification d'un utilisateur à partir de son id public function checkUserIdentification($id_user) { $identification = Identification::where('id_user', $id_user)->first(); if (isset($identification)) { if ($identification->status == 0) return $this->errorResponse(trans('errors.validation_user_identification_required')); else return $identification; } else { return $this->errorResponse(trans('errors.user_identification_required')); } } }