Linux vps-61133.fhnet.fr 4.9.0-19-amd64 #1 SMP Debian 4.9.320-2 (2022-06-30) x86_64
Apache/2.4.25 (Debian)
Server IP : 93.113.207.21 & Your IP : 216.73.216.35
Domains :
Cant Read [ /etc/named.conf ]
User : www-data
Terminal
Auto Root
Create File
Create Folder
Localroot Suggester
Backdoor Destroyer
Readme
/
var /
www /
html /
bdc.bdcloud.fr /
custom /
stancer /
lib /
Delete
Unzip
Name
Size
Permission
Date
Action
stancer.lib.php
50.52
KB
-rwxr-x---
2023-04-04 16:13
stancer_stancer_payments.lib.php
3.61
KB
-rwxr-x---
2023-04-04 16:13
stancer_stancer_payouts.lib.php
3.6
KB
-rwxr-x---
2023-04-04 16:13
Save
Rename
<?php /* Copyright (C) 2023 Eric Seigne <eric.seigne@cap-rel.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * \file stancer/lib/stancer.lib.php * \ingroup stancer * \brief Library files with common functions for Stancer */ dol_include_once('/stancer/backport/functions.php'); require_once DOL_DOCUMENT_ROOT."/core/lib/company.lib.php"; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"; require_once DOL_DOCUMENT_ROOT."/contact/class/contact.class.php"; require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; require_once DOL_DOCUMENT_ROOT.'/includes/php-iban/oophp-iban.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT."/commande/class/commande.class.php"; dol_include_once('/stancer/vendor/autoload.php'); dol_include_once('/stancer/class/companypaymentmodestancer.class.php'); dol_include_once('/stancer/class/stancer_payments.class.php'); dol_include_once('/stancer/class/stancer_payouts.class.php'); $stancer = Stancer\Config::init([stancer_get_public_key(), stancer_get_private_key()]); if (isset($conf->global->STANCER_IS_PROD)) { $stancer->setMode(Stancer\Config::LIVE_MODE); } else { $stancer->setMode(Stancer\Config::TEST_MODE); } /** * get stancer public key * * @return [type] [return description] */ function stancer_get_public_key() { global $conf; if (isset($conf->global->STANCER_IS_PROD)) { return $conf->global->STANCER_PROD_PUBLIC_KEY ?? ''; } else { return $conf->global->STANCER_TEST_PUBLIC_KEY ?? ''; } } /** * get stancer private key * * @return [type] [return description] */ function stancer_get_private_key() { global $conf; if (isset($conf->global->STANCER_IS_PROD)) { return $conf->global->STANCER_PROD_PRIVATE_KEY ?? ''; } else { return $conf->global->STANCER_TEST_PRIVATE_KEY ?? ''; } } /** * Prepare admin pages header * * @return array */ function stancerAdminPrepareHead() { global $langs, $conf; // global $db; // $extrafields = new ExtraFields($db); // $extrafields->fetch_name_optionals_label('myobject'); $langs->loadLangs(array("stancer@stancer")); $h = 0; $head = array(); $head[$h][0] = dol_buildpath("/stancer/admin/setup.php", 1); $head[$h][1] = $langs->trans("StancerSettingsMenu"); $head[$h][2] = 'StancerSettingsMenu'; $h++; /* $head[$h][0] = dol_buildpath("/stancer/admin/myobject_extrafields.php", 1); $head[$h][1] = $langs->trans("ExtraFields"); $nbExtrafields = is_countable($extrafields->attributes['myobject']['label']) ? count($extrafields->attributes['myobject']['label']) : 0; if ($nbExtrafields > 0) { $head[$h][1] .= ' <span class="badge">' . $nbExtrafields . '</span>'; } $head[$h][2] = 'myobject_extrafields'; $h++; */ $head[$h][0] = dol_buildpath("/stancer/admin/sepa.php", 1); $head[$h][1] = $langs->trans("StancerSEPAMenu"); $head[$h][2] = 'StancerSEPAMenu'; $h++; $head[$h][0] = dol_buildpath("/stancer/admin/test.php", 1); $head[$h][1] = $langs->trans("Test"); $head[$h][2] = 'test'; $h++; $head[$h][0] = dol_buildpath("/stancer/admin/about.php", 1); $head[$h][1] = $langs->trans("About"); $head[$h][2] = 'about'; $h++; // Show more tabs from modules // Entries must be declared in modules descriptor with line //$this->tabs = array( // 'entity:+tabname:Title:@stancer:/stancer/mypage.php?id=__ID__' //); // to add new tab //$this->tabs = array( // 'entity:-tabname:Title:@stancer:/stancer/mypage.php?id=__ID__' //); // to remove a tab complete_head_from_modules($conf, $langs, null, $head, $h, 'stancer@stancer'); complete_head_from_modules($conf, $langs, null, $head, $h, 'stancer@stancer', 'remove'); return $head; } /** * add customer on Stancer if needed * * @return string stancerID */ function stancerAddCustomerIfNeeded($socid) { global $db, $conf, $user, $langs; $error = 0; $customerID = null; $societe = new Societe($db); $socresult = $societe->fetch($socid); if ($socresult) { $customer = new Stancer\Customer(); if ($societe->email) { $customer->setEmail($societe->email); } if ($societe->phone) { if (substr($societe->phone, 0, 1) == '+') { $customer->setMobile($societe->phone); } } $customer->setName($societe->name); try { $customerID = trim($customer->send(), '"'); dol_syslog("Stancer create customer : " . $societe->email . ", " . $societe->name, LOG_DEBUG); //print "<p>Creation du client chez Stancer : uuid=" . json_encode($customer) . "</p>"; } catch (Exception $e) { $message = json_encode($e->getMessage()); // print "<p>Erreur de création du client : " . $message . "</p>"; dol_syslog("Stancer Info (client déjà existant) : " . $societe->email . ", " . $message, LOG_INFO); $matches = array(); preg_match('/.*\((cust_\w+)\).*/', $message, $matches); if (is_array($matches) && isset($matches[1])) { $customerID = $matches[1]; } else { setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); } dol_syslog("Stancer récupération de l'id du client : " . $societe->email . ", " . $customerID, LOG_DEBUG); // print "<p>Récupération de l'id du client : " . $customerID . "</p>"; } if ($customerID) { $data = [ 'socid' => $socid, 'fk_soc' => $socid, 'bank' => null, 'label' => 'stancer-card', 'stancer_account' => $db->escape($customerID), 'last_four' => 0000, 'number' => 0000, 'proprio' => $societe->name, 'exp_date_month' => "", 'exp_date_year' => "", 'cvn' => null, 'datec' => dol_now(), 'default_rib' => 0, 'type' => 'card', 'entity' => $conf->entity, 'country_code' => $societe->country_code, 'status' => 1, ]; $compPayModeId = stancerAddCompanyPaymentModeifNeeded($data); } } return $customerID; } /** * Create SEPA entry on stancer account if needed * * @param int $socid dolibarr soc id * @param array $data data to use * * @return string stancer sepaID */ function stancerAddSEPAIfNeeded($socid, $data) { global $db, $conf, $user, $langs; $sepaID = $resSEPA = null; $error = 0; $customerID = stancerAddCustomerIfNeeded($socid); $sepa = new Stancer\Sepa(); $societe = new Societe($db); $socresult = $societe->fetch($socid); if ($socresult && !empty($data['iban'])) { $sepa->setIban($data['iban']); $sepa->setName($societe->name); if (!empty($data['bic'])) { $sepa->setBic($data['bic']); } $sepa->setMandate($data['mandate']); $sepa->setDateMandate($data['date_mandate']); try { $resSEPA = $sepa->send(); if ($resSEPA) { $sepaID = $sepa->getId(); $bic = $sepa->getBic(); $country = $sepa->getCountry(); dol_syslog("Stancer create SEPA (id #$sepaID; bic=$bic, country=$country) is OK for : " . $societe->name, LOG_DEBUG); } else { dol_syslog("Stancer create SEPA is ERROR for : " . $societe->name, LOG_DEBUG); } } catch (Exception $e) { $message = json_encode($e->getMessage()); $matches = array(); preg_match('/.*\((sepa_\w+)\).*/', $message, $matches); if (is_array($matches) && isset($matches[1])) { $sepaID = $matches[1]; } else { setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); dol_syslog("Stancer erreur de création du SEPA : " . json_encode($sepa), LOG_ERR); dol_syslog("Stancer erreur de création du SEPA : " . $message, LOG_ERR); } dol_syslog("Stancer récupération de l'id du sepa : " . $societe->email . ", " . $sepaID, LOG_DEBUG); } if (null !== $sepaID) { $json = $sepa->populate()->get(); dol_syslog("Stancer resSEPA ok, sepaID = $sepaID json=" . json_encode($json), LOG_DEBUG); if(null === $json) { dol_syslog("Stancer Création du SEPA error 1 ...", LOG_ERR); //TODO SEPA ERROR } else { $data = [ 'socid' => $socid, 'fk_soc' => $socid, 'bank' => $data['bank'], 'label' => 'stancer-sepa', 'stancer_account' => $db->escape($customerID), 'stancer_object_ref' => $db->escape($sepaID), 'bic' => $sepa->getBic(), 'last_four' => $sepa->getLast4(), 'rum' => $sepa->getMandate(), 'number' => 0000, 'proprio' => $societe->name, 'exp_date_month' => "", 'exp_date_year' => "", 'cvn' => null, 'datec' => dol_now(), 'iban_prefix' => $sepa->getIban(), 'default_rib' => 0, 'type' => 'ban', 'entity' => $conf->entity, 'country_code' => $sepa->getCountry(), 'status' => 1, ]; $compPayModeId = stancerAddCompanyPaymentModeifNeeded($data); if ($compPayModeId < 0) { dol_syslog("Stancer Création du compte client err ...", LOG_ERR); // print "<p>Création du compte client err</p>"; // dol_print_error($db); } else { dol_syslog("Stancer Création du compte client ok ...", LOG_DEBUG); } // print json_encode($companypaymentmode); } } } return $sepaID; } /** * Mutualisation du code permettant de créer ou mettre à jour un CompanyPaymentModeStancer * * @param [type] $data [$data description] * * @return [type] [return description] */ function stancerAddCompanyPaymentModeifNeeded($data) { global $db, $conf, $user, $langs; $result = 0; $companypaymentmode = new CompanyPaymentModeStancer($db); $res = $companypaymentmode->fetch(0, '', 0, '', " AND fk_soc = " . $db->escape($data['socid']) . " AND label = '" . $db->escape($data['label']) . "'"); if ($res) { dol_syslog("Stancer Un compte existe déjà dans dolibarr rib (sepa)", LOG_DEBUG); $result = $companypaymentmode->id; // print "<p>Un compte existe déjà dans dolibarr rib</p>"; // detection si un champ est modifié -> update nécessaire $update = false; foreach ($data as $key => $val) { if ($companypaymentmode->$key != $val) { $update = true; $companypaymentmode->$key = $val; } } if ($update) { dol_syslog("stancerAddCompanyPaymentModeifNeeded update is needed ...", LOG_DEBUG); $res = $companypaymentmode->update($user); } } else { //set data foreach ($data as $key => $val) { $companypaymentmode->$key = $val; } dol_syslog("stancerAddCompanyPaymentModeifNeeded create object ...", LOG_ERR); $result = $companypaymentmode->create($user); } return $result; } /** * common check before starting payment process * * @param [type] $object [$object description] * * @return [type] [return description] */ function stancerCommonFilterBeforePay($object) { global $db, $langs; // print json_encode($object); if (!in_array($object->element, ['facture', 'commande', 'invoice', 'order'])) { dol_syslog("stancerCommonFilterBeforePay object is not an invoice or an order (element != facture | commande), current type of object is " . $object->element, LOG_DEBUG); $message = $langs->trans("Payment object is not an invoice or an order"); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); return -1; } if ($object->element == 'facture') { if ($object->paye != '0') { dol_syslog("stancerCommonFilterBeforePay invoice status paye is not 0, paye=" . $object->paye, LOG_DEBUG); $message = $langs->trans("Payment object is already paid"); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); return -2; } //disabled // $account = new Account($db); // if ($account->fetch($object->fk_account) > 0) { // //Only in case of automatic payments ? // // if ($account->ref != 'STANCER') { // // dol_syslog("stancerCommonFilterBeforePay invoice payment destination account is not STANCER", LOG_DEBUG); // // $message = $langs->trans("Payment bank account target for that object is not Stancer"); // // setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); // // return -3; // // } // } else { // dol_syslog("stancerCommonFilterBeforePay invoice payment destination account is not defined, please choose STANCER", LOG_DEBUG); // $message = $langs->trans("Payment bank account target for that object is not Stancer"); // setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); // return -3; // } } elseif ($object->element == 'commande') { if ($object->status != Commande::STATUS_VALIDATED) { dol_syslog("stancerCommonFilterBeforePay order status not validated : " . $object->status, LOG_DEBUG); $message = $langs->trans("Payment order is not validated / ready for pay"); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); return -4; } } stancerAddCustomerIfNeeded($object->socid); return 0; } /** * un a payment with Card * * @param [type] $object [$object description] * * @return [type] [return description] */ function stancerCardstartPayWithRedirect($object, $parameters, $forceAmount = null) { global $db, $conf, $user, $langs, $mysoc; $res = stancerCommonFilterBeforePay($object); if ($res < 0) { return $res; } // if ($object->mode_reglement_code != 'CB') { // $message = $langs->trans("Payment mode is not CB"); // setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); // dol_syslog("stancerCardstartPayWithRedirect payment mode is not set to CB", LOG_DEBUG); // return -4; // } if (empty($forceAmount)) { $amountToPay = $object->total_ttc * 100; } else { $amountToPay = $forceAmount * 100; } $socid = $object->socid; $societe = new Societe($db); $socresult = $societe->fetch($socid); if ($socresult) { $customerID = ''; //recherche si on a un moyen de paiement pour cette societe chez stancer $companypaymentmode = new CompanyPaymentModeStancer($db); $res = $companypaymentmode->fetch(0, '', 0, '', " AND type = 'card' AND label = 'stancer-card' AND fk_soc = '".$db->escape($socid)."'"); if ($res) { dol_syslog("Stancer pay by card : " . json_encode($companypaymentmode), LOG_DEBUG); //dans stancer_account on a le customerid stancer $customerID = $companypaymentmode->stancer_account; //note: customerID could be null -> then try to create / update account just after } if (empty($customerID)) { //creation du compte client si besoin - grosse différence avec SEPA c'est possible ici de le faire au vol $customerID = stancerAddCustomerIfNeeded($socid); } //warning si on fait 3 paiements de 50€ pour une facture le TAG sera identique et stancer refusera les paiements // -> ajout de .SEQ=X dans le tag dans la fonction stancerMakeTAG $tag = (empty($parameters['tag']) ? GETPOST("ref", 'alpha') : $parameters['tag']); if (empty($tag)) { $tag = stancerMakeTAG($object); } $source = (empty($parameters['source']) ? GETPOST("source", 'alpha') : $parameters['s']); if (empty($source) && $object->element == "facture") { $source = 'invoice'; } $securekey = (empty($parameters['securekey']) ? GETPOST("securekey", 'alpha') : $parameters['securekey']); dol_syslog("Stancer pay : " . $object->ref . ", tag is $tag", LOG_INFO); $public_key = stancer_get_public_key(); $args = base64_encode('tag='.$tag.'&source='.$source.'&ref='.$object->ref.'&securekey='.$securekey); $urlretour = DOL_MAIN_URL_ROOT.'/custom/stancer/public/paymentback.php?s='.$args; $customer = new Stancer\Customer($customerID); $sp = new Stancer_payments($db); //y a t il déjà un paiement initié qui n'a pas été jusqu'au bout ? en ce cas il faut le réutiliser $resSP = $sp->fetch('', null, null, $tag); $mustCreate = true; $mustNewUUID = false; if ($resSP > 0) { if ($sp->isPaid()) { dol_syslog("Stancer error, that unique ref id is already paid ! ($tag)", LOG_ERR); print "<p>".$langs->trans("ErrorStancer") . ':<br />' . $langs->trans("StancerAlreadyPaid", $mysoc->name) . "</p>"; print "<p>".$langs->trans("ErrorStancerPleaseContactBy") . "</p><ul>"; print "<li>".$langs->trans("ErrorStancerPleaseContactByPhone", $mysoc->phone) . "</li>"; print "<li>".$langs->trans("ErrorStancerPleaseContactByMail", $mysoc->email) ."</li>"; print "<li>".$langs->trans("ErrorStancerPleaseUniqueID", $sp->unique_id) ."</li>"; print "</ul></p>"; exit; } elseif($sp->canBeReused()) { // sauf s'il y a une dispute ou un conflit en cours ! dol_syslog("A previous Stancer process could be reused ($tag) ");// . json_encode($sp)); $payment = new Stancer\Payment($sp->stancer_id); if (empty($sp->card)) { $mustCreate = false; } else { //une carte existe déjà ? c'est que le paiement a été tenté mais a foiré //il faut créer un nouveau uuid malheureusement :-( $mustNewUUID = true; dol_syslog(" previous card " . json_encode($card) . " so try to reset card ..."); } } } if($mustCreate) { $payment = new Stancer\Payment(); if ($mustNewUUID) { $tag .= ".UID=" . $sp->getNextNumRef(); } //create payment $payment->setAmount($amountToPay); $payment->setCurrency($object->multicurrency_code); $payment->setCustomer($customer); $payment->setOrderId($object->ref); $payment->setUniqueId($tag); $payment->setDescription(substr($langs->transnoentitiesnoconv("StancerPaymentOrderRef", $object->ref), -64)); //warning: max size is 64 if (strpos($urlretour, 'https://') !== 0) { //Message d'info pas de https dol_syslog("Stancer error, back url is not https : " . $urlretour, LOG_ERR); } else { $payment->setReturnUrl($urlretour); } //3DS via leur page de paiement il faut uniquement activer l'option $payment->setAuth(true); } try { $pid = $payment->send(); dol_syslog("Stancer card pay avant auth : $pid", LOG_DEBUG); //save pid into dolibarr for urlback $_SESSION["stancer_payment_id"] = $payment->getId(); $_SESSION['currencyCodeType'] = $object->multicurrency_code; $data = [ 'stancer_id' => $payment->getId(), 'amount' => $payment->getAmount(), 'currency' => $payment->getCurrency(), 'description' => $payment->getDescription(), 'order_id' => $payment->getOrderId(), 'unique_id' => $tag, 'method' => $payment->getMethod(), 'card' => $payment->getCard(), 'sepa' => $payment->getSepa(), 'customer' => $payment->getCustomer(), 'refunds' => $payment->getRefunds(), 'status' => $payment->getStatus(), 'response' => $payment->getResponse(), 'capture' => $payment->getCapture(), // 'created' => $payment->getCreated(), // 'date_bank' => $payment->getDateBank(), 'return_url' => $payment->getReturnUrl(), 'live_mode' => isset($conf->global->STANCER_IS_PROD) ? true : false, 'fk_soc' => $socid, ]; $sp->fillDataArray($data); $res = $sp->create($user, true); if ($res) { //then switch to payment url $url = "https://payment.stancer.com/" . $public_key . "/" . $payment->id . "?lang=fr"; // print "<p><a href='" .$url . "'>Clic on link</a></p>"; dol_syslog("Stancer card Stancer_payments ok, prepare redirect to $url", LOG_DEBUG); // Si aucun en-tête n'a été envoyé, envoyons-en un if (!headers_sent()) { header("Location: " . $url); exit; } else { print '<script type="text/javascript" language="javascript">' . "\n"; print "window.location = '" . $url . "'" . "\n"; print "</script>" . "\n"; } // print '<form action="' . $url . '" method="GET" name="redirect_pay">'; // print '</form>' . "\n"; // print '<script type="text/javascript" language="javascript">' . "\n"; // print ' document.redirect_pay.submit();' . "\n"; // print '</script>' . "\n"; // print "<p>" . $langs->trans("STANCER_REDIRECT") . "<a href='" . $url . "'>Stancer Payment</a></p>"; } else { dol_syslog("Stancer card Stancer_payments error", LOG_ERR); } } catch (Exception $e) { // print "<p>Erreur : " . $e->getMessage() . "</p>"; dol_syslog("Stancer pay error (1) : " . json_encode($e->getMessage()), LOG_DEBUG); dol_syslog("Stancer pay error (1), object was " . json_encode($payment), LOG_DEBUG); $message = "Stancer error : " . json_encode($e->getMessage()); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); $error = -5; } } return $error; } /** * run a payment with SEPA * * @param [type] $object invoice to pay * * @return [type] [return description] */ function stancerSEPAstartPay($object) { global $db, $conf, $user, $langs; $res = stancerCommonFilterBeforePay($object); if ($res < 0) { return $res; } if ($object->mode_reglement_code != 'PRE') { $message = $langs->trans("Payment mode is not SEPA"); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); dol_syslog("stancerSEPAstartPay payment mode is not PRE", LOG_DEBUG); return -4; } $socid = $object->socid; $societe = new Societe($db); $socresult = $societe->fetch($socid); if ($socresult) { //recherche si on a un moyen de paiement sepa pour cette societe chez stancer $companypaymentmode = new CompanyPaymentModeStancer($db); $res =$companypaymentmode->fetch(0, '', 0, '', " AND type = 'ban' AND label = 'stancer-sepa' AND fk_soc = '".$db->escape($socid)."'"); if ($res) { dol_syslog("Stancer pay by SEPA : " . json_encode($object), LOG_DEBUG); dol_syslog("Stancer pay by SEPA : " . $object->ref, LOG_INFO); //warning si on fait 3 paiements de 50€ pour une facture le TAG sera identique et stancer refusera les paiements // -> ajout de .SEQ=X dans le tag dans la fonction stancerMakeTAG $tag = stancerMakeTAG($object); $sp = new Stancer_payments($db); //Vérification que nous n'avons pas déjà un SEPA en cours .... $resSP = $sp->fetch('', null, null, $tag); if ($resSP) { dol_syslog("Stancer SEPA error (transaction already started)", LOG_DEBUG); $url = "<a href='" . dol_buildpath('/stancer/stancer_payments_list.php', 2).'?search_stancer_id='.$sp->stancer_id . "'>"; $message = $langs->transnoentitiesnoconv("StancerSEPAalreadyInProgress", $url, '</a>'); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); return; } $numref = $sp->getNextNumRef(); //dans stancer_account on a le customerid stancer $customer = new Stancer\Customer($companypaymentmode->stancer_account); // print "<p>customer is " . $customer->getName() . " ::" . $companypaymentmode->stancer_account . " </p>"; // dans stancer_object_ref se trouve l'info du mandat créé chez stancer $sepa = new \Stancer\Sepa($companypaymentmode->stancer_object_ref); dol_syslog("Stancer SEPA is : " . json_encode($sepa) . " and TAG=$tag", LOG_DEBUG); //create payment $payment = new Stancer\Payment(); $payment->setAmount($object->total_ttc * 100); $payment->setCurrency($object->multicurrency_code); $payment->setCustomer($customer); $payment->setOrderId($object->ref); $payment->setUniqueId($tag); $payment->setDescription(substr($langs->transnoentitiesnoconv("StancerPaymentOrderRef", $object->ref), -64)); //warning: max size is 64 $payment->setSepa($sepa); try { $pid = $payment->send(); dol_syslog("Stancer PID is : " . json_encode($pid), LOG_DEBUG); dol_syslog("Stancer payment is : " . json_encode($payment), LOG_DEBUG); dol_syslog("Stancer pay avant auth(5) : $pid", LOG_DEBUG); $data = [ 'stancer_id' => $payment->getId(), 'amount' => $payment->getAmount(), 'currency' => $payment->getCurrency(), 'description' => $payment->getDescription(), 'order_id' => $payment->getOrderId(), 'unique_id' => $tag, 'method' => $payment->getMethod(), 'card' => $payment->getCard(), 'sepa' => $payment->getSepa(), 'customer' => $payment->getCustomer(), 'refunds' => $payment->getRefunds(), 'status' => $payment->getStatus(), 'response' => $payment->getResponse(), 'capture' => $payment->getCapture(), // 'created' => $payment->getCreated(), // 'date_bank' => $payment->getDateBank(), 'return_url' => $payment->getReturnUrl(), 'live_mode' => isset($conf->global->STANCER_IS_PROD) ? true : false, 'fk_soc' => $socid, ]; $sp->fillDataArray($data); $res = $sp->create($user, true); if ($res) { $message = $langs->trans("Nice, Stancer SEPA payement is engaged !"); setEventMessages($langs->trans("Stancer"), $message, 'mesgs'); } else { $message = $langs->trans("Error on Stancer SEPA!"); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); dol_syslog("Stancer pay SEPA error save (1)" . json_encode($res), LOG_DEBUG); } } catch (Exception $e) { // print "<p>Erreur : " . $e->getMessage() . "</p>"; dol_syslog("Stancer pay SEPA error(1)" . json_encode($e->getMessage()), LOG_DEBUG); $message = $langs->trans("Error on Stancer SEPA payment request !"); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); } } else { dol_syslog("Stancer pay SEPA error, CompanyPaymentModeStancer does not exists", LOG_DEBUG); $message = $langs->trans("StancerSEPAisNotConfiguredForThatCustomer"); setEventMessages($langs->trans("ErrorStancer"), $message, 'errors'); } } } function sancerShowOnlineIBANLinkForCustomer($socid, $name) { $url = stancerGetOnlineIBANLinkForCustomer($socid, $name); $out .= '<div class="urllink"><input type="text" id="onlinepaymenturl" class="quatrevingtpercentminusx" value="'.$url.'">'; $out .= '<a class="" href="'.$url.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe', 'class="paddingleft"').'</a>'; $out .= '</div>'; $out .= ajax_autoselect("onlinepaymenturl", 0); return $out; } /** * Return string with full Url * * @param int $mode 0=True url, 1=Url formated with colors * @param string $type Type of URL ('free', 'order', 'invoice', 'contractline', 'member', 'boothlocation', ...) * @param string $ref Ref of object * @param int $amount Amount (required and used for $type='free' only) * @param string $freetag Free tag (required and used for $type='free' only) * @param string $localorexternal 0=Url for browser, 1=Url for external access * @return string Url string */ function stancerGetOnlineIBANLinkForCustomer($socid, $name) { global $conf, $dolibarr_main_url_root; $out = $entity = ''; $tst = "SEPA-$socid-$name-".$conf->global->PAYMENT_SECURITY_TOKEN; $securekey = dol_hash($tst, 1); $out = "socid=$socid&action=stancerSEPA&securekey=".$securekey; dol_syslog("stancer stat securekey is from $tst"); // For multicompany if (!empty($out) && !empty($conf->multicompany->enabled)) { $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities $entity .= "&e=".$conf->entity; //entity in clear for main dolibarr code } return DOL_MAIN_URL_ROOT.'/custom/stancer/public/sepa-iban.php?s=' . base64_encode($out) . $entity; } /** * create a tag from object * * @param [type] $object [$object description] * * @return [type] [return description] */ function stancerMakeTAG($object) { $tag = ''; if ($object->element == 'facture') { $tag .= 'INV='.$object->id; } elseif ($object->element == 'commande') { $tag .= 'ORD='.$object->id; } //if ($source == 'organizedeventregistration') { // $fulltag = 'ATT='.$attendee->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); //if ($source == 'boothlocation') // $fulltag = 'BOO='.GETPOST("booth").'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); //membres (association) // $fulltag = 'MEM='.$member->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); //don // $fulltag = 'DON='.$don->ref.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); //lignes de contrat // }elseif($object->element == 'contrat') { // $fulltag = 'COL='.$contractline->id.'.CON='.$contract->id.'.CUS='.$contract->thirdparty->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); // } // $FULLTAG .= ($FULLTAG ? '.' : '').'PM='.$paymentmethod; $tag .= '.CUS='.$object->thirdparty->id; //facture peut-être payée en plusieurs fois ? pour savoir ça il suffit de demander combien il reste à payer if ($object->element == 'facture') { $numPaiement = 0; $totalpaye = $object->getSommePaiement(); $totalcreditnotes = $object->getSumCreditNotesUsed(); $totaldeposits = $object->getSumDepositsUsed(); $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); if ($resteapayer != price2num($object->total_ttc)) { $list = $object->getListOfPayments(); $numPaiement = count($list); // print "<p>FACTURE : $ref reste à payer $resteapayer num=$numPaiement</p>"; } if ($numPaiement > 0 && (strpos($tag, 'SEQ=') === false)) { $tag .= '.SEQ=' . $numPaiement; } } if (strlen($tag) < 36) { return $tag; } else { dol_syslog("Stancer error : TAG generator is to long (36 chars max)", DOL_ERR); return ""; } } /** * add a line on bank account with Stancer fees * * @param $ref référence a ajouter sur la description * @param $totalamount montant total du paiement * @param $fk_account id du compte bancaire * @param $stancer_id id stancer * * @return [type] [return description] */ function stancerAddPaimentFeeOnBank($ref, $totalamount, $fk_account, $stancer_id, $date = null) { global $db, $conf, $user; $db->begin(); $error=0; if (empty($date)) { $date = dol_now(); } $amount = $totalamount; if ($totalamount > 0) { $amount = 0 - $totalamount; } include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($db); $result = $acc->fetch($fk_account); if ($result < 0) { $error++; return -1; } // $db->begin(); $label = "(StancerFees)"; if($ref != '') { $label .= " " . $ref; }elseif(!empty($date)) { $label .= " " . $date; } //duplicate ! $sql = "SELECT count(*) as count FROM ".MAIN_DB_PREFIX."bank WHERE num_chq='" . $db->escape($stancer_id) . "' AND fk_account='" . $db->escape($fk_account) ."' AND amount=" . $db->escape($amount) . ""; $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); if ($obj->count > 0) { dol_syslog("stancerAddPaimentFeeOnBank duplicate : " . $obj->count); } else { dol_syslog("stancerAddPaimentFeeOnBank insert : $stancer_id, label=$label"); // Insert payment into llx_bank $bank_line_id = $acc->addline( $date, 'PRE', // Payment mode code ('CB', 'CHQ' or 'VIR' for example). Use payment id if not defined for backward compatibility. $label, $amount, // Sign must be positive when we receive money (customer payment), negative when you give money (supplier invoice or credit note) $stancer_id, '', $user, '', '', '', null ); } } // // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) // //if (! $error && $label != '(WithdrawalPayment)') // if (!$error) { // $linkaddedforthirdparty = array(); // foreach ($this->amounts as $key => $value) { // We should have invoices always for same third party but we loop in case of. // if ($mode == 'payment') { // $fac = new Facture($this->db); // $fac->fetch($key); // $fac->fetch_thirdparty(); // if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty // $result = $acc->add_url_line( // $bank_line_id, // $fac->thirdparty->id, // DOL_URL_ROOT.'/comm/card.php?socid=', // $fac->thirdparty->name, // 'company' // ); // if ($result <= 0) { // dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror()); // } // $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty // } // } // if ($mode == 'payment_supplier') { // $fac = new FactureFournisseur($this->db); // $fac->fetch($key); // $fac->fetch_thirdparty(); // if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty // $result = $acc->add_url_line( // $bank_line_id, // $fac->thirdparty->id, // DOL_URL_ROOT.'/fourn/card.php?socid=', // $fac->thirdparty->name, // 'company' // ); // if ($result <= 0) { // dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror()); // } // $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty // } // } // } // } // // Add link 'WithdrawalPayment' in bank_url // if (!$error && $label == '(WithdrawalPayment)') { // $result = $acc->add_url_line( // $bank_line_id, // $this->id_prelevement, // DOL_URL_ROOT.'/compta/prelevement/card.php?id=', // $this->num_payment, // 'withdraw' // ); // } // // Add link 'InvoiceRefused' in bank_url // if (! $error && $label == '(InvoiceRefused)') { // $result=$acc->add_url_line( // $bank_line_id, // $this->id_prelevement, // DOL_URL_ROOT.'/compta/prelevement/card.php?id=', // $this->num_prelevement, // 'withdraw' // ); // } // if (!$error && !$notrigger) { // // Appel des triggers // $result = $this->call_trigger('PAYMENT_ADD_TO_BANK', $user); // if ($result < 0) { // $error++; // } // // Fin appel triggers // } // } else { // $this->error = $acc->error; // $error++; // } if (!$error) { $db->commit(); } else { $db->rollback(); } if (!$error) { return 1; } else { return -1; } } function stancerAddTransfertFromAccountToAccount($accountfrom, $accountto, $dateo, $label, $amount, $amountto, $stancer_id) { global $langs, $db, $user; $langs->load("errors"); $error = 0; dol_syslog(("Stancer stancerAddTransfertFromAccountToAccount add transfert date=$dateo label=$label, amount=$amount, amountto=$amountto, id stancer=$stancer_id")); if (!$label) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Description")), null, 'errors'); } if (!$amount) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors'); } if (!$accountfrom) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("TransferFrom")), null, 'errors'); } if (!$accountto) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("TransferTo")), null, 'errors'); } if (!$error) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; if ($accountto->currency_code == $accountfrom->currency_code) { $amountto = $amount; } else { if (!$amountto) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AmountTo")), null, 'errors'); } } if ($amountto < 0) { $error++; setEventMessages($langs->trans("AmountMustBePositive"), null, 'errors'); } if ($accountto->id == $accountfrom->id) { $error++; setEventMessages($langs->trans("ErrorFromToAccountsMustDiffers"), null, 'errors'); } //duplicates ? $sql = "SELECT count(*) as count FROM ".MAIN_DB_PREFIX."bank WHERE num_chq='" . $db->escape($stancer_id) . "'"; $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); if ($obj->count > 0) { dol_syslog("stancerAddTransfertFromAccountToAccount duplicate : $sql :: " . $obj->count); $error++; } } if (empty($error)) { $db->begin(); $bank_line_id_from = 0; $bank_line_id_to = 0; $result = 0; // By default, electronic transfert from bank to bank $typefrom = 'VIR'; $typeto = 'VIR'; if (!$error) { $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, price2num(-1 * $amount), $stancer_id, '', $user); } if (!($bank_line_id_from > 0)) { $error++; } if (!$error) { $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, $amountto, $stancer_id, '', $user); } if (!($bank_line_id_to > 0)) { $error++; } if (!$error) { $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'); } if (!($result > 0)) { $error++; } if (!$error) { $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'); } if (!($result > 0)) { $error++; } if (!$error) { $mesg = $langs->trans("TransferFromToDone", '{s1}', '{s2}', $amount, $langs->transnoentitiesnoconv("Currency".$conf->currency)); $mesg = str_replace('{s1}', '<a href="bankentries_list.php?id='.$accountfrom->id.'&sortfield=b.datev,b.dateo,b.rowid&sortorder=desc">'.$accountfrom->label.'</a>', $mesgs); $mesg = str_replace('{s2}', '<a href="bankentries_list.php?id='.$accountto->id.'">'.$accountto->label.'</a>', $mesgs); setEventMessages($mesgs, null, 'mesgs'); $db->commit(); } else { setEventMessages($accountfrom->error.' '.$accountto->error, null, 'errors'); $db->rollback(); } } } } /** * do stancer payment on an object * * @param [type] $object object, invoice, order ... * @param [type] $data array of data * * @return int < 0 on error */ function stancerAddPaymentOnObject($object, $data) { global $langs, $db, $user, $conf; $error = 0; dol_syslog("stancerRefreshAllPayments add payment on =" . json_encode($object) . " data = " . json_encode($data)); //avoid duplicate ? $sql = "SELECT count(*) as count FROM ".MAIN_DB_PREFIX."paiement WHERE num_paiement='" . $db->escape($data['payment_id']) . "'"; $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); if ($obj->count > 0) { dol_syslog("stancerAddPaymentOnObject duplicate : " . $obj->count); return -1; } } //no amount -> no payment -> return if (empty($data['FinalPaymentAmt'])) { dol_syslog("stancerAddPaymentOnObject amount empty, early return", LOG_WARNING); return -2; } if (empty($data['date'])) { dol_syslog("stancerAddPaymentOnObject date error, early return", LOG_WARNING); return -3; } if (empty($object->id)) { dol_syslog("stancerAddPaymentOnObject object id is null (maybe stancer account configured on more than one dolibarr)", LOG_WARNING); return -4; } $db->begin(); $bankaccountid = $conf->global->STANCER_BANK_ACCOUNT_FOR_PAYMENTS; if (empty($conf->banque->enabled) || empty($bankaccountid)) { $postactionmessages[] = 'Setup of bank account to use in module Stancer was not set.'; $ispostactionok = -1; $error++; return $error; } // Creation of payment line $paiement = new Paiement($db); $paiement->datepaye = $data['date']; $paiement->amounts = array($object->id => price2num($data['FinalPaymentAmt'])); $paiement->paiementid = $data['paymentTypeId']; $paiement->num_payment = $data['payment_id']; $paiement->note_public = 'Online payment '.dol_print_date($data['date'], 'standard').' from '.$data['ipaddress']; $paiement->ext_payment_id = $data['TRANSACTIONID']; $paiement->ext_payment_site = $data['service']; $paiement->comment = $data['paymentmethod']; $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents if ($paiement_id < 0) { $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors); $ispostactionok = -1; $error++; } else { $postactionmessages[] = 'Payment created'; $ispostactionok = 1; } $label = $data['label']; $ref = $data['ref'] ?? ''; //add ref on label if($ref != '' && strpos($ref, $label)) { $label .= " " . $ref; } $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', ''); if ($result < 0) { $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors); $ispostactionok = -1; $error++; } else { $postactionmessages[] = 'Bank transaction of payment created'; $ispostactionok = 1; } //erics debug // print "<p>facture avant commit/rollback : $error</p>"; // print json_encode($postactionmessages); // print json_encode($object); if (!$error) { $db->commit(); //erics add new line on bank account for Stancer Fees ? //or in stancer listing ? // if ($conf->global->STANCER_ADD_FEES == 'PAYMENT') { // $fees= $data["FinalFees"] / 100; // $ref = $data['date']; // dol_syslog("STANCER_ADD_FEES is on each PAYMENT in paymentback.php ...."); // $resAddPaiment = stancerAddPaimentFeeOnBank($ref, $fees, $bankaccountid, $data['payment_id'], $data['date']); // if ($resAddPaiment < 0) { // dol_syslog("stancerAddPaimentFeeOnBank error for " .$object->ref, LOG_ERR); // } // } } else { $db->rollback(); } return $error; } /** * extract informations from TAG then return dolibarr object (invoice / order ...) * * @param [type] $tag dolibarr tag * * @return [type] [return description] */ function getObjectFromTag($tag) { global $langs, $db, $user, $conf; $object = null; $tmptag = dolExplodeIntoArray($tag, '.', '='); if (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) { $object = new Facture($db); $result = $object->fetch($tmptag['INV']); if ($result) { return $object; } } return $object; } /** re télécharge tous les paiements et fais le job * (mutualisation entre payments_list et cron) */ function stancerRefreshAllPayments() { dol_syslog("stancerRefreshAllPayments"); global $langs, $db, $user, $conf; $output = new StdClass(); $output->error=''; $output->message=''; $sp = new Stancer_payments($db); //Refresh sur un historique de 2 mois max ? try { $list = Stancer\Payment::list(['created' => time() - (3600*24*31*2), 'start'=>0, 'limit' => (int) stancerGetNumberOfItemToGet()]); foreach ($list as $payment) { $res = $sp->fetch(null, null, $payment->getId()); $sp->fillData($payment); // print "res is $res<br />"; //object exist in database ? if ($res) { // print "<p>update " . $sp->fk_soc . "</p>"; $res2 = $sp->update($user); } else { // print "<p>create $uuid</p>"; $res2 = $sp->create($user); } //Il faudrait vérifier sur la banque que toutes les entrées s'y trouvent, probablement code a mutualiser avec le cron //erics add new line on bank account for Stancer Fees $method = $payment->getMethod(); if ($method == "card") { $paymentType = "CB"; } elseif ($method == "sepa") { $paymentType = "PRE"; } $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1); $ipaddress = '127.0.0.1'; $service = 'stancer'; $paymentmethod = 'stancer'; //TODO : peut etre autre chose que des factures (adhesion par ex) $label = '(CustomerInvoicePayment)'; //en attendant que fee soit proposé par un accesseur $json = $payment->populate()->get(); $datebank = $payment->getDateBank(); $obj = getObjectFromTag($payment->getUniqueId()); if ($obj) { if (empty($datebank)) { $datebank = new DateTime('@'.$json['date_paym']); } $amount = (int) $payment->getAmount(); if ($datebank && ($amount > 0)) { $date = (string) $datebank->format("Y-m-d"); $data = [ 'payment_id' => $payment->getId(), 'date' => $date, 'FinalPaymentAmt' => ($amount / 100), 'paymentTypeId' => $paymentTypeId, 'ipaddress' => $ipaddress, 'TRANSACTIONID' => $payment->getId(), 'service' => $service, 'paymentmethod' => $paymentmethod, 'label' => $label, 'FinalFees' => $json['fee'] / 100, 'ref' => $obj->ref ]; $error = stancerAddPaymentOnObject($obj, $data); } else { dol_syslog("stancerRefreshAllPayments do not insert paiement : amount=$amount, date=" . json_encode($datebank)); $output->error = "stancerRefreshAllPayments do not insert paiement for " .$obj->ref . ", amount=$amount"; } if ($conf->global->STANCER_ADD_FEES == 'PAYMENT') { $json = $payment->populate()->get(); $fees= ($json['fee'] / 100); $ref = $obj->ref; if (!empty($json['date_bank'])) { $dateo = (string) $payment->getDateBank()->format("Y-m-d"); } else { $dateo = (string) $payment->getCreationDate()->format("Y-m-d"); } $bankaccountid = $conf->global->STANCER_BANK_ACCOUNT_FOR_PAYMENTS; dol_syslog("STANCER_ADD_FEES is on each PAYMENT in paymentback.php ...."); $resAddPaiment = stancerAddPaimentFeeOnBank($ref, $fees, $bankaccountid, $payment->getId(),$dateo); if ($resAddPaiment < 0) { $output->error = "stancerRefreshAllPayments error on stancerAddPaimentFeeOnBank for " .$obj->ref; } } } else { dol_syslog("stancerRefreshAllPayments there is no object from tag"); $output->error = "stancerRefreshAllPayments can't find an object from tag " . json_encode($json); } } } catch (Exception $e) { dol_syslog("stancerRefreshAllPayments exception occurs : " . $e->getMessage(), LOG_ERR); $output->error = "stancerRefreshAllPayments exception occurs " . $e->getMessage(); // $request = $e->getRequest() ?? ''; // dol_syslog("stancerRefreshAllPayments exception debug for Stancer Staff : method=" . $request->getMethod() . " :: uri=" . (string) $request->getUri(), LOG_ERR); // dol_syslog("stancerRefreshAllPayments exception debug for Stancer Staff : body=" . json_encode($request->getBody()), LOG_ERR); } return $output; } /** re télécharge tous les virements et fais le job * (mutualisation entre payouts_list et cron) */ function stancerRefreshAllPayouts() { global $langs, $db, $user, $conf; $error = 0; $output = new StdClass(); $output->error=''; $output->message=''; $accountStancer = new Account($db); $accountMainBank = new Account($db); $result = $accountStancer->fetch($conf->global->STANCER_BANK_ACCOUNT_FOR_PAYMENTS); if ($result < 0) { $error++; $output->error = "error STANCER_BANK_ACCOUNT_FOR_PAYMENTS is not defined"; return $output; } $result = $accountMainBank->fetch($conf->global->STANCER_BANK_MAIN_ACCOUNT_FOR_PAYOUTS); if ($result < 0) { $error++; $output->error = "error STANCER_BANK_MAIN_ACCOUNT_FOR_PAYOUTS is not defined"; return $output; } $sp = new Stancer_payouts($db); //Refresh sur un historique de 4 mois max ? try { $list = Stancer\Payout::list(['created' => time() - (3600*24*31*4), 'start'=>0, 'limit' => (int) stancerGetNumberOfItemToGet()]); foreach ($list as $payout) { $res = $sp->fetch(null, null, $payout->getId()); $sp->fillData($payout); //object exist in database ? if ($res) { $res2 = $sp->update($user); } else { $res2 = $sp->create($user); } $label = "(BankTransfer)"; //Ajout des virements de compte à compte ... //joel astuce $json = $payout->populate()->get(); $amount = $json['payments']['amount']; if ($amount > 0) { $amount = $amount / 100; } $dateo = null; $date = $payout->getDateBank(); //si pas de date banque c'est que le transfert n'est pas encore terminé if ($date && ($amount > 0)) { $dateo = (string) $date->format("Y-m-d"); dol_syslog("Add stancerAddTransfertFromAccountToAccount $dateo"); stancerAddTransfertFromAccountToAccount($accountStancer, $accountMainBank, $dateo, $label, $amount, $amount, $payout->getId()); // erics add new line on bank account for Stancer Fees if ($conf->global->STANCER_ADD_FEES == 'PAYOUT') { $fees= $payout->getFees() / 100; $dateo = (string) $payout->getDatePayment()->format("Y-m-d"); $ref = $bankaccountid = $conf->global->STANCER_BANK_ACCOUNT_FOR_PAYMENTS; dol_syslog("STANCER_ADD_FEES is on each PAYOUT in stancer_payouts_list.php ...."); $resAddPaiment = stancerAddPaimentFeeOnBank($ref, $fees, $bankaccountid, $payout->getId(), $dateo); if ($resAddPaiment < 0) { $output->error = "error on stancerAddPaimentFeeOnBank for " .$ref; } } } else { dol_syslog("stancerRefreshAllPayouts date or amount error"); $output->error = "refreshall error on date=" . json_encode($date) . " or amount=$amount"; } } } catch (Exception $e) { dol_syslog("stancerRefreshAllPayouts exception occurs : " . $e->getMessage(), LOG_ERR); $output->error = "stancerRefreshAllPayouts exception occurs " . $e->getMessage(); } return $output; } function stancerGetNumberOfItemToGet() { global $conf; $nb = 20; if (!empty($conf->global->STANCER_NUMBER_OF_ITEMS_TO_SYNC)) { $num = (int) $conf->global->STANCER_NUMBER_OF_ITEMS_TO_SYNC; if (is_int($num) && $num > 0 && $num < 100) { $nb = $num; } } return $nb; } function stancerSendMail($to, $subject, $message) { global $conf, $langs; $from = $conf->global->MAILING_EMAIL_FROM; if (empty(trim($from)) || empty(trim($to))) { dol_syslog("stancerSendMail early return, from=$from or to=$to is empty", LOG_DEBUG); return; } $ishtml = dol_textishtml($message); $realsubject = html_entity_decode('[Stancer/Dolibarr] ' . $subject); $realmessage = "<p>" .$langs->trans('StancerMailHello') . "</p>\n"; $realmessage .= "<p>" . $message . "</p>\n"; $realmessage .= $langs->trans('StancerMailGoodBye'); $realmessage .= "<br />\n<br />\n--<br />\n"; $realmessage .= "<p>" .$langs->trans('StancerMailSignature') . "</p>"; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($realsubject, $to, $from, $realmessage, array(), array(), array(), '', '', 0, $ishtml); $result = $mailfile->sendfile(); if ($result) { dol_syslog("stancerSendMail sent to ".$to, LOG_DEBUG); } else { dol_syslog("stancerSendMail Failed to send EMail to ".$to, LOG_ERR); } }