paymentok.php 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  1. <?php
  2. /* Copyright (C) 2001-2002 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2006-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2021 Waël Almoman <info@almoman.com>
  6. * Copyright (C) 2021 Maxime Demarest <maxime@indelog.fr>
  7. * Copyright (C) 2021 Dorian Vabre <dorian.vabre@gmail.com>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. /**
  23. * \file htdocs/public/payment/paymentok.php
  24. * \ingroup core
  25. * \brief File to show page after a successful payment on a payment line system.
  26. * The payment was already really recorded. So an error here must send warning to admin but must still infor user that payment is ok.
  27. * This page is called by payment system with url provided to it completed with parameter TOKEN=xxx
  28. * This token and session can be used to get more informations.
  29. */
  30. if (!defined('NOLOGIN')) {
  31. define("NOLOGIN", 1); // This means this output page does not require to be logged.
  32. }
  33. if (!defined('NOCSRFCHECK')) {
  34. define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
  35. }
  36. if (!defined('NOIPCHECK')) {
  37. define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
  38. }
  39. if (!defined('NOBROWSERNOTIF')) {
  40. define('NOBROWSERNOTIF', '1');
  41. }
  42. // For MultiCompany module.
  43. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
  44. // TODO This should be useless. Because entity must be retrieve from object ref and not from url.
  45. $entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1));
  46. if (is_numeric($entity)) {
  47. define("DOLENTITY", $entity);
  48. }
  49. require '../../main.inc.php';
  50. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  51. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  52. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
  53. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
  54. if (!empty($conf->paypal->enabled)) {
  55. require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
  56. require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php';
  57. }
  58. $langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal"));
  59. // Clean parameters
  60. if (!empty($conf->paypal->enabled)) {
  61. $PAYPAL_API_USER = "";
  62. if (!empty($conf->global->PAYPAL_API_USER)) {
  63. $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER;
  64. }
  65. $PAYPAL_API_PASSWORD = "";
  66. if (!empty($conf->global->PAYPAL_API_PASSWORD)) {
  67. $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD;
  68. }
  69. $PAYPAL_API_SIGNATURE = "";
  70. if (!empty($conf->global->PAYPAL_API_SIGNATURE)) {
  71. $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE;
  72. }
  73. $PAYPAL_API_SANDBOX = "";
  74. if (!empty($conf->global->PAYPAL_API_SANDBOX)) {
  75. $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX;
  76. }
  77. $PAYPAL_API_OK = "";
  78. if ($urlok) {
  79. $PAYPAL_API_OK = $urlok;
  80. }
  81. $PAYPAL_API_KO = "";
  82. if ($urlko) {
  83. $PAYPAL_API_KO = $urlko;
  84. }
  85. $PAYPALTOKEN = GETPOST('TOKEN');
  86. if (empty($PAYPALTOKEN)) {
  87. $PAYPALTOKEN = GETPOST('token');
  88. }
  89. $PAYPALPAYERID = GETPOST('PAYERID');
  90. if (empty($PAYPALPAYERID)) {
  91. $PAYPALPAYERID = GETPOST('PayerID');
  92. }
  93. }
  94. $FULLTAG = GETPOST('FULLTAG');
  95. if (empty($FULLTAG)) {
  96. $FULLTAG = GETPOST('fulltag');
  97. }
  98. $source = GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha');
  99. $ref = GETPOST('ref');
  100. $suffix = GETPOST("suffix", 'aZ09');
  101. $membertypeid = GETPOST("membertypeid", 'int');
  102. // Detect $paymentmethod
  103. $paymentmethod = '';
  104. $reg = array();
  105. if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) {
  106. $paymentmethod = $reg[1];
  107. }
  108. if (empty($paymentmethod)) {
  109. dol_print_error(null, 'The back url does not contains a parameter fulltag that should help us to find the payment method used');
  110. exit;
  111. }
  112. dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLTAG=".$FULLTAG." REQUEST_URI=".$_SERVER["REQUEST_URI"], LOG_DEBUG, 0, '_payment');
  113. $validpaymentmethod = array();
  114. if (!empty($conf->paypal->enabled)) {
  115. $validpaymentmethod['paypal'] = 'paypal';
  116. }
  117. if (!empty($conf->paybox->enabled)) {
  118. $validpaymentmethod['paybox'] = 'paybox';
  119. }
  120. if (!empty($conf->stripe->enabled)) {
  121. $validpaymentmethod['stripe'] = 'stripe';
  122. }
  123. // Security check
  124. if (empty($validpaymentmethod)) {
  125. accessforbidden('', 0, 0, 1);
  126. }
  127. $ispaymentok = false;
  128. // If payment is ok
  129. $PAYMENTSTATUS = $TRANSACTIONID = $TAXAMT = $NOTE = '';
  130. // If payment is ko
  131. $ErrorCode = $ErrorShortMsg = $ErrorLongMsg = $ErrorSeverityCode = '';
  132. $object = new stdClass(); // For triggers
  133. $error = 0;
  134. /*
  135. * Actions
  136. */
  137. /*
  138. * View
  139. */
  140. $now = dol_now();
  141. dol_syslog("Callback url when a payment was done. query_string=".(dol_escape_htmltag($_SERVER["QUERY_STRING"]) ?dol_escape_htmltag($_SERVER["QUERY_STRING"]) : '')." script_uri=".(dol_escape_htmltag($_SERVER["SCRIPT_URI"]) ?dol_escape_htmltag($_SERVER["SCRIPT_URI"]) : ''), LOG_DEBUG, 0, '_payment');
  142. $tracepost = "";
  143. foreach ($_POST as $k => $v) {
  144. $tracepost .= "{$k} - {$v}\n";
  145. }
  146. dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment');
  147. $head = '';
  148. if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) {
  149. $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
  150. }
  151. $conf->dol_hide_topmenu = 1;
  152. $conf->dol_hide_leftmenu = 1;
  153. $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
  154. llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);
  155. // Show message
  156. print '<span id="dolpaymentspan"></span>'."\n";
  157. print '<div id="dolpaymentdiv" class="center">'."\n";
  158. // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo)
  159. // Define logo and logosmall
  160. $logosmall = $mysoc->logo_small;
  161. $logo = $mysoc->logo;
  162. $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix;
  163. if (!empty($conf->global->$paramlogo)) {
  164. $logosmall = $conf->global->$paramlogo;
  165. } elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) {
  166. $logosmall = $conf->global->ONLINE_PAYMENT_LOGO;
  167. }
  168. //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
  169. // Define urllogo
  170. $urllogo = '';
  171. $urllogofull = '';
  172. if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
  173. $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
  174. $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
  175. } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
  176. $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
  177. $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
  178. }
  179. // Output html code for logo
  180. if ($urllogo) {
  181. print '<div class="backgreypublicpayment">';
  182. print '<div class="logopublicpayment">';
  183. print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
  184. print '>';
  185. print '</div>';
  186. if (empty($conf->global->MAIN_HIDE_POWERED_BY)) {
  187. print '<div class="poweredbypublicpayment opacitymedium right"><a class="poweredbyhref" href="https://www.dolibarr.org?utm_medium=website&utm_source=poweredby" target="dolibarr" rel="noopener">'.$langs->trans("PoweredBy").'<br><img class="poweredbyimg" src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>';
  188. }
  189. print '</div>';
  190. }
  191. if (!empty($conf->global->MAIN_IMAGE_PUBLIC_PAYMENT)) {
  192. print '<div class="backimagepublicpayment">';
  193. print '<img id="idMAIN_IMAGE_PUBLIC_PAYMENT" src="'.$conf->global->MAIN_IMAGE_PUBLIC_PAYMENT.'">';
  194. print '</div>';
  195. }
  196. print '<br><br><br>';
  197. if (!empty($conf->paypal->enabled)) {
  198. if ($paymentmethod == 'paypal') { // We call this page only if payment is ok on payment system
  199. if ($PAYPALTOKEN) {
  200. // Get on url call
  201. $onlinetoken = $PAYPALTOKEN;
  202. $fulltag = $FULLTAG;
  203. $payerID = $PAYPALPAYERID;
  204. // Set by newpayment.php
  205. $paymentType = $_SESSION['PaymentType'];
  206. $currencyCodeType = $_SESSION['currencyCodeType'];
  207. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  208. // From env
  209. $ipaddress = $_SESSION['ipaddress'];
  210. dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
  211. // Validate record
  212. if (!empty($paymentType)) {
  213. dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment');
  214. $resArray = getDetails($onlinetoken);
  215. //var_dump($resarray);
  216. $ack = strtoupper($resArray["ACK"]);
  217. if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
  218. // Nothing to do
  219. dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
  220. } else {
  221. dol_syslog("Call to GetExpressCheckoutDetails return error: ".json_encode($resArray), LOG_WARNING, '_payment');
  222. }
  223. dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
  224. $resArray2 = confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag);
  225. //var_dump($resarray);
  226. $ack = strtoupper($resArray2["ACK"]);
  227. if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
  228. dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
  229. $object->source = $source;
  230. $object->ref = $ref;
  231. $object->payerID = $payerID;
  232. $object->fulltag = $fulltag;
  233. $object->resArray = $resArray2;
  234. // resArray was built from a string like that
  235. // TOKEN=EC%2d1NJ057703V9359028&TIMESTAMP=2010%2d11%2d01T11%3a40%3a13Z&CORRELATIONID=1efa8c6a36bd8&ACK=Success&VERSION=56&BUILD=1553277&TRANSACTIONID=9B994597K9921420R&TRANSACTIONTYPE=expresscheckout&PAYMENTTYPE=instant&ORDERTIME=2010%2d11%2d01T11%3a40%3a12Z&AMT=155%2e57&FEEAMT=5%2e54&TAXAMT=0%2e00&CURRENCYCODE=EUR&PAYMENTSTATUS=Completed&PENDINGREASON=None&REASONCODE=None
  236. $PAYMENTSTATUS = urldecode($resArray2["PAYMENTSTATUS"]); // Should contains 'Completed'
  237. $TRANSACTIONID = urldecode($resArray2["TRANSACTIONID"]);
  238. $TAXAMT = urldecode($resArray2["TAXAMT"]);
  239. $NOTE = urldecode($resArray2["NOTE"]);
  240. $ispaymentok = true;
  241. } else {
  242. dol_syslog("Call to DoExpressCheckoutPayment return error: ".json_encode($resArray2), LOG_WARNING, 0, '_payment');
  243. //Display a user friendly Error on the page using any of the following error information returned by PayPal
  244. $ErrorCode = urldecode($resArray2["L_ERRORCODE0"]);
  245. $ErrorShortMsg = urldecode($resArray2["L_SHORTMESSAGE0"]);
  246. $ErrorLongMsg = urldecode($resArray2["L_LONGMESSAGE0"]);
  247. $ErrorSeverityCode = urldecode($resArray2["L_SEVERITYCODE0"]);
  248. }
  249. } else {
  250. $ErrorCode = "SESSIONEXPIRED";
  251. $ErrorLongMsg = "Session expired. Can't retreive PaymentType. Payment has not been validated.";
  252. $ErrorShortMsg = "Session expired";
  253. dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
  254. dol_print_error('', 'Session expired');
  255. }
  256. } else {
  257. $ErrorCode = "PAYPALTOKENNOTDEFINED";
  258. $ErrorLongMsg = "The parameter PAYPALTOKEN was not defined. Payment has not been validated.";
  259. $ErrorShortMsg = "Parameter PAYPALTOKEN not defined";
  260. dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
  261. dol_print_error('', 'PAYPALTOKEN not defined');
  262. }
  263. }
  264. }
  265. if (!empty($conf->paybox->enabled)) {
  266. if ($paymentmethod == 'paybox') {
  267. $ispaymentok = true; // We call this page only if payment is ok on payment system
  268. }
  269. }
  270. if (!empty($conf->stripe->enabled)) {
  271. if ($paymentmethod == 'stripe') {
  272. $ispaymentok = true; // We call this page only if payment is ok on payment system
  273. }
  274. }
  275. // If data not provided from back url, search them into the session env
  276. if (empty($ipaddress)) {
  277. $ipaddress = $_SESSION['ipaddress'];
  278. }
  279. if (empty($TRANSACTIONID)) {
  280. $TRANSACTIONID = $_SESSION['TRANSACTIONID'];
  281. }
  282. if (empty($FinalPaymentAmt)) {
  283. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  284. }
  285. if (empty($paymentType)) {
  286. $paymentType = $_SESSION["paymentType"];
  287. }
  288. if (empty($currencyCodeType)) {
  289. $currencyCodeType = $_SESSION['currencyCodeType'];
  290. }
  291. $fulltag = $FULLTAG;
  292. $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
  293. dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG_DEBUG, 0, '_payment');
  294. // Make complementary actions
  295. $ispostactionok = 0;
  296. $postactionmessages = array();
  297. if ($ispaymentok) {
  298. // Set permission for the anonymous user
  299. if (empty($user->rights->societe)) {
  300. $user->rights->societe = new stdClass();
  301. }
  302. if (empty($user->rights->facture)) {
  303. $user->rights->facture = new stdClass();
  304. }
  305. if (empty($user->rights->adherent)) {
  306. $user->rights->adherent = new stdClass();
  307. $user->rights->adherent->cotisation = new stdClass();
  308. }
  309. $user->rights->societe->creer = 1;
  310. $user->rights->facture->creer = 1;
  311. $user->rights->adherent->cotisation->creer = 1;
  312. if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) {
  313. // Validate member
  314. // Create subscription
  315. // Create complementary actions (this include creation of thirdparty)
  316. // Send confirmation email
  317. $defaultdelay = 1;
  318. $defaultdelayunit = 'y';
  319. // Record subscription
  320. include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  321. include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
  322. include_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
  323. $adht = new AdherentType($db);
  324. $object = new Adherent($db);
  325. $result1 = $object->fetch((int) $tmptag['MEM']);
  326. $result2 = $adht->fetch($object->typeid);
  327. dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment');
  328. if ($result1 > 0 && $result2 > 0) {
  329. $paymentTypeId = 0;
  330. if ($paymentmethod == 'paybox') {
  331. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  332. }
  333. if ($paymentmethod == 'paypal') {
  334. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  335. }
  336. if ($paymentmethod == 'stripe') {
  337. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  338. }
  339. if (empty($paymentTypeId)) {
  340. if (empty($paymentType)) {
  341. $paymentType = 'CB';
  342. }
  343. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  344. }
  345. dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType, LOG_DEBUG, 0, '_payment');
  346. // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
  347. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  348. // Security protection:
  349. if (empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { // If we didn't allow members to choose their membership amount (if free amount is allowed, no need to check)
  350. if ($object->status == $object::STATUS_DRAFT) { // If the member is not yet validated, we check that the amount is the same as expected.
  351. $typeid = $object->typeid;
  352. // Set amount for the subscription:
  353. // - First check the amount of the member type.
  354. $amountbytype = $adht->amountByType(1); // Load the array of amount per type
  355. $amountexpected = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
  356. // - If not found, take the default amount
  357. if (empty($amountexpected) && !empty($conf->global->MEMBER_NEWFORM_AMOUNT)) {
  358. $amountexpected = $conf->global->MEMBER_NEWFORM_AMOUNT;
  359. }
  360. if ($amountexpected && $amountexpected != $FinalPaymentAmt) {
  361. $error++;
  362. $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') differs from value expected for membership ('.$amountexpected.'). May be a hack to try to pay a different amount ?';
  363. $postactionmessages[] = $errmsg;
  364. $ispostactionok = -1;
  365. dol_syslog("Failed to validate member (bad amount check): ".$errmsg, LOG_ERR, 0, '_payment');
  366. }
  367. }
  368. }
  369. // Security protection:
  370. if (!empty($conf->global->MEMBER_MIN_AMOUNT)) {
  371. if ($FinalPaymentAmt < $conf->global->MEMBER_MIN_AMOUNT) {
  372. $error++;
  373. $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') is lower than the minimum allowed ('.$conf->global->MEMBER_MIN_AMOUNT.'). May be a hack to try to pay a different amount ?';
  374. $postactionmessages[] = $errmsg;
  375. $ispostactionok = -1;
  376. dol_syslog("Failed to validate member (amount lower than minimum): ".$errmsg, LOG_ERR, 0, '_payment');
  377. }
  378. }
  379. // Security protection:
  380. if ($currencyCodeType && $currencyCodeType != $conf->currency) { // Check that currency is the good one
  381. $error++;
  382. $errmsg = 'Value of currencyCodeType ('.$currencyCodeType.') differs from value expected for membership ('.$conf->currency.'). May be a hack to try to pay a different amount ?';
  383. $postactionmessages[] = $errmsg;
  384. $ispostactionok = -1;
  385. dol_syslog("Failed to validate member (bad currency check): ".$errmsg, LOG_ERR, 0, '_payment');
  386. }
  387. if (! $error) {
  388. // We validate the member (no effect if it is already validated)
  389. $result = ($object->status == $object::STATUS_EXCLUDED) ? -1 : $object->validate($user); // if membre is excluded (status == -2) the new validation is not possible
  390. if ($result < 0 || empty($object->datevalid)) {
  391. $error++;
  392. $errmsg = $object->error;
  393. $postactionmessages[] = $errmsg;
  394. $postactionmessages = array_merge($postactionmessages, $object->errors);
  395. $ispostactionok = -1;
  396. dol_syslog("Failed to validate member: ".$errmsg, LOG_ERR, 0, '_payment');
  397. }
  398. }
  399. // Subscription informations
  400. $datesubscription = $object->datevalid;
  401. if ($object->datefin > 0) {
  402. $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
  403. }
  404. $datesubend = null;
  405. if ($datesubscription && $defaultdelay && $defaultdelayunit) {
  406. $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
  407. // the new end date of subscription must be in futur
  408. while ($datesubend < $now) {
  409. $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
  410. $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
  411. }
  412. $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
  413. }
  414. $paymentdate = $now;
  415. $amount = $FinalPaymentAmt;
  416. $label = 'Online subscription '.dol_print_date($now, 'standard').' using '.$paymentmethod.' from '.$ipaddress.' - Transaction ID = '.$TRANSACTIONID;
  417. // Payment informations
  418. $accountid = 0;
  419. if ($paymentmethod == 'paybox') {
  420. $accountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  421. }
  422. if ($paymentmethod == 'paypal') {
  423. $accountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  424. }
  425. if ($paymentmethod == 'stripe') {
  426. $accountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  427. }
  428. if ($accountid < 0) {
  429. $error++;
  430. $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
  431. $postactionmessages[] = $errmsg;
  432. $ispostactionok = -1;
  433. dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
  434. }
  435. $operation = $paymentType; // Payment mode code
  436. $num_chq = '';
  437. $emetteur_nom = '';
  438. $emetteur_banque = '';
  439. // Define default choice for complementary actions
  440. $option = '';
  441. if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
  442. $option = 'bankviainvoice';
  443. } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) {
  444. $option = 'bankdirect';
  445. } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
  446. $option = 'invoiceonly';
  447. }
  448. if (empty($option)) {
  449. $option = 'none';
  450. }
  451. $sendalsoemail = 1;
  452. // Record the subscription then complementary actions
  453. $db->begin();
  454. // Create subscription
  455. if (!$error) {
  456. dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
  457. $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
  458. if ($crowid <= 0) {
  459. $error++;
  460. $errmsg = $object->error;
  461. $postactionmessages[] = $errmsg;
  462. $ispostactionok = -1;
  463. } else {
  464. $postactionmessages[] = 'Subscription created (id='.$crowid.')';
  465. $ispostactionok = 1;
  466. }
  467. }
  468. if (!$error) {
  469. dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
  470. $autocreatethirdparty = 1; // will create thirdparty if member not yet linked to a thirdparty
  471. $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
  472. if ($result < 0) {
  473. dol_syslog("Error ".$object->error." ".join(',', $object->errors), LOG_DEBUG, 0, '_payment');
  474. $error++;
  475. $postactionmessages[] = $object->error;
  476. $postactionmessages = array_merge($postactionmessages, $object->errors);
  477. $ispostactionok = -1;
  478. } else {
  479. if ($option == 'bankviainvoice') {
  480. $postactionmessages[] = 'Invoice, payment and bank record created';
  481. dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
  482. }
  483. if ($option == 'bankdirect') {
  484. $postactionmessages[] = 'Bank record created';
  485. dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
  486. }
  487. if ($option == 'invoiceonly') {
  488. $postactionmessages[] = 'Invoice recorded';
  489. dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
  490. }
  491. $ispostactionok = 1;
  492. // If an invoice was created, it is into $object->invoice
  493. }
  494. }
  495. if (!$error) {
  496. if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
  497. $thirdparty_id = $object->fk_soc;
  498. dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
  499. $service = 'StripeTest';
  500. $servicestatus = 0;
  501. if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
  502. $service = 'StripeLive';
  503. $servicestatus = 1;
  504. }
  505. $stripeacc = null; // No Oauth/connect use for public pages
  506. $thirdparty = new Societe($db);
  507. $thirdparty->fetch($thirdparty_id);
  508. include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
  509. $stripe = new Stripe($db);
  510. //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
  511. $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
  512. if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
  513. dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
  514. try {
  515. global $stripearrayofkeysbyenv;
  516. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
  517. if (preg_match('/^pi_/', $TRANSACTIONID)) {
  518. // This may throw an error if not found.
  519. $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
  520. } else {
  521. // This throw an error if not found
  522. $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
  523. }
  524. if ($chpi) {
  525. $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
  526. if (empty($stripecu)) {
  527. // This include the INSERT
  528. $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
  529. // Link this customer to the payment intent
  530. if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
  531. \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
  532. }
  533. } else {
  534. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
  535. $sql .= " VALUES (".((int) $object->fk_soc).", '', '".$db->escape($stripecu)."', 'stripe', '".$db->escape($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])."', ".((int) $servicestatus).", ".((int) $conf->entity).", '".$db->idate(dol_now())."', 0)";
  536. $resql = $db->query($sql);
  537. if (!$resql) { // should not happen
  538. $error++;
  539. $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
  540. dol_syslog($errmsg, LOG_ERR, 0, '_payment');
  541. $postactionmessages[] = $errmsg;
  542. $ispostactionok = -1;
  543. }
  544. }
  545. } else { // should not happen
  546. $error++;
  547. $errmsg = 'Failed to retreive paymentintent or charge from id';
  548. dol_syslog($errmsg, LOG_ERR, 0, '_payment');
  549. $postactionmessages[] = $errmsg;
  550. $ispostactionok = -1;
  551. }
  552. } catch (Exception $e) { // should not happen
  553. $error++;
  554. $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
  555. dol_syslog($errmsg, LOG_ERR, 0, '_payment');
  556. $postactionmessages[] = $errmsg;
  557. $ispostactionok = -1;
  558. }
  559. }
  560. }
  561. }
  562. if (!$error) {
  563. $db->commit();
  564. } else {
  565. $db->rollback();
  566. }
  567. // Send email to member
  568. if (!$error) {
  569. dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
  570. // Send confirmation Email
  571. if ($object->email && $sendalsoemail) {
  572. $subject = '';
  573. $msg = '';
  574. // Send subscription email
  575. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  576. $formmail = new FormMail($db);
  577. // Set output language
  578. $outputlangs = new Translate('', $conf);
  579. $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
  580. // Load traductions files required by page
  581. $outputlangs->loadLangs(array("main", "members"));
  582. // Get email content from template
  583. $arraydefaultmessage = null;
  584. $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
  585. if (!empty($labeltouse)) {
  586. $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
  587. }
  588. if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  589. $subject = $arraydefaultmessage->topic;
  590. $msg = $arraydefaultmessage->content;
  591. }
  592. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
  593. // Create external user
  594. if (!empty($conf->global->ADHERENT_CREATE_EXTERNAL_USER_LOGIN)) {
  595. $infouserlogin = '';
  596. $nuser = new User($db);
  597. $tmpuser = dol_clone($object);
  598. $result = $nuser->create_from_member($tmpuser, $object->login);
  599. $newpassword = $nuser->setPassword($user, '');
  600. if ($result < 0) {
  601. $outputlangs->load("errors");
  602. $postactionmessages[] = 'Error in create external user : '.$nuser->error;
  603. } else {
  604. $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
  605. $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
  606. }
  607. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
  608. }
  609. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  610. $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
  611. $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
  612. // Attach a file ?
  613. $file = '';
  614. $listofpaths = array();
  615. $listofnames = array();
  616. $listofmimes = array();
  617. if (is_object($object->invoice)) {
  618. $invoicediroutput = $conf->facture->dir_output;
  619. $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
  620. $file = $fileparams['fullname'];
  621. $listofpaths = array($file);
  622. $listofnames = array(basename($file));
  623. $listofmimes = array(dol_mimetype($file));
  624. }
  625. $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
  626. $result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
  627. if ($result < 0) {
  628. $errmsg = $object->error;
  629. $postactionmessages[] = $errmsg;
  630. $ispostactionok = -1;
  631. } else {
  632. if ($file) {
  633. $postactionmessages[] = 'Email sent to member (with invoice document attached)';
  634. } else {
  635. $postactionmessages[] = 'Email sent to member (without any attached document)';
  636. }
  637. // TODO Add actioncomm event
  638. }
  639. }
  640. }
  641. } else {
  642. $postactionmessages[] = 'Failed to get a valid value for "amount paid" or "payment type" to record the payment of subscription for member '.$tmptag['MEM'].'. May be payment was already recorded.';
  643. $ispostactionok = -1;
  644. }
  645. } else {
  646. $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
  647. $ispostactionok = -1;
  648. }
  649. } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
  650. // Record payment
  651. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  652. $object = new Facture($db);
  653. $result = $object->fetch((int) $tmptag['INV']);
  654. if ($result) {
  655. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  656. $paymentTypeId = 0;
  657. if ($paymentmethod == 'paybox') {
  658. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  659. }
  660. if ($paymentmethod == 'paypal') {
  661. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  662. }
  663. if ($paymentmethod == 'stripe') {
  664. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  665. }
  666. if (empty($paymentTypeId)) {
  667. if (empty($paymentType)) {
  668. $paymentType = 'CB';
  669. }
  670. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  671. }
  672. // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
  673. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  674. $db->begin();
  675. // Creation of payment line
  676. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  677. $paiement = new Paiement($db);
  678. $paiement->datepaye = $now;
  679. if ($currencyCodeType == $conf->currency) {
  680. $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  681. } else {
  682. $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
  683. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  684. $ispostactionok = -1;
  685. $error++; // Not yet supported
  686. }
  687. $paiement->paiementid = $paymentTypeId;
  688. $paiement->num_payment = '';
  689. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
  690. $paiement->ext_payment_id = $TRANSACTIONID;
  691. $paiement->ext_payment_site = $service;
  692. if (!$error) {
  693. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  694. if ($paiement_id < 0) {
  695. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  696. $ispostactionok = -1;
  697. $error++;
  698. } else {
  699. $postactionmessages[] = 'Payment created';
  700. $ispostactionok = 1;
  701. }
  702. }
  703. if (!$error && !empty($conf->banque->enabled)) {
  704. $bankaccountid = 0;
  705. if ($paymentmethod == 'paybox') {
  706. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  707. } elseif ($paymentmethod == 'paypal') {
  708. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  709. } elseif ($paymentmethod == 'stripe') {
  710. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  711. }
  712. if ($bankaccountid > 0) {
  713. $label = '(CustomerInvoicePayment)';
  714. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  715. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  716. }
  717. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  718. if ($result < 0) {
  719. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  720. $ispostactionok = -1;
  721. $error++;
  722. } else {
  723. $postactionmessages[] = 'Bank transaction of payment created';
  724. $ispostactionok = 1;
  725. }
  726. } else {
  727. $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
  728. $ispostactionok = -1;
  729. $error++;
  730. }
  731. }
  732. if (!$error) {
  733. $db->commit();
  734. } else {
  735. $db->rollback();
  736. }
  737. } else {
  738. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type" ('.$paymentType.') to record the payment of invoice '.$tmptag['INV'].'. May be payment was already recorded.';
  739. $ispostactionok = -1;
  740. }
  741. } else {
  742. $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
  743. $ispostactionok = -1;
  744. }
  745. } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
  746. include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
  747. $object = new Commande($db);
  748. $result = $object->fetch((int) $tmptag['ORD']);
  749. if ($result) {
  750. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  751. $paymentTypeId = 0;
  752. if ($paymentmethod == 'paybox') $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  753. if ($paymentmethod == 'paypal') $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  754. if ($paymentmethod == 'stripe') $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  755. if (empty($paymentTypeId)) {
  756. if (empty($paymentType)) $paymentType = 'CB';
  757. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  758. }
  759. // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
  760. if (!empty($conf->facture->enabled)) {
  761. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0 ) {
  762. include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  763. $invoice = new Facture($db);
  764. $result = $invoice->createFromOrder($object, $user);
  765. if ($result > 0) {
  766. $object->classifyBilled($user);
  767. $invoice->validate($user);
  768. // Creation of payment line
  769. include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  770. $paiement = new Paiement($db);
  771. $paiement->datepaye = $now;
  772. if ($currencyCodeType == $conf->currency) {
  773. $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  774. } else {
  775. $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
  776. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  777. $ispostactionok = -1;
  778. $error++;
  779. }
  780. $paiement->paiementid = $paymentTypeId;
  781. $paiement->num_payment = '';
  782. $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
  783. $paiement->ext_payment_id = $TRANSACTIONID;
  784. $paiement->ext_payment_site = '';
  785. if (!$error) {
  786. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  787. if ($paiement_id < 0) {
  788. $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
  789. $ispostactionok = -1;
  790. $error++;
  791. } else {
  792. $postactionmessages[] = 'Payment created';
  793. $ispostactionok = 1;
  794. }
  795. }
  796. if (!$error && !empty($conf->banque->enabled)) {
  797. $bankaccountid = 0;
  798. if ($paymentmethod == 'paybox') $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  799. elseif ($paymentmethod == 'paypal') $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  800. elseif ($paymentmethod == 'stripe') $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  801. if ($bankaccountid > 0) {
  802. $label = '(CustomerInvoicePayment)';
  803. if ($object->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  804. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  805. if ($result < 0) {
  806. $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
  807. $ispostactionok = -1;
  808. $error++;
  809. } else {
  810. $postactionmessages[] = 'Bank transaction of payment created';
  811. $ispostactionok = 1;
  812. }
  813. } else {
  814. $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
  815. $ispostactionok = -1;
  816. $error++;
  817. }
  818. }
  819. if (!$error) {
  820. $db->commit();
  821. } else {
  822. $db->rollback();
  823. }
  824. } else {
  825. $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
  826. $ispostactionok = -1;
  827. }
  828. } else {
  829. $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type" (' . $paymentType . ') to record the payment of order ' . $tmptag['ORD'] . '. May be payment was already recorded.';
  830. $ispostactionok = -1;
  831. }
  832. } else {
  833. $postactionmessages[] = 'Invoice module is not enable';
  834. $ispostactionok = -1;
  835. }
  836. } else {
  837. $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
  838. $ispostactionok = -1;
  839. }
  840. } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
  841. include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
  842. $don = new Don($db);
  843. $result = $don->fetch((int) $tmptag['DON']);
  844. if ($result) {
  845. $paymentTypeId = 0;
  846. if ($paymentmethod == 'paybox') {
  847. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  848. }
  849. if ($paymentmethod == 'paypal') {
  850. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  851. }
  852. if ($paymentmethod == 'stripe') {
  853. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  854. }
  855. if (empty($paymentTypeId)) {
  856. if (empty($paymentType)) {
  857. $paymentType = 'CB';
  858. }
  859. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  860. }
  861. // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
  862. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  863. $db->begin();
  864. // Creation of paiement line for donation
  865. include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
  866. $paiement = new PaymentDonation($db);
  867. if ($currencyCodeType == $conf->currency) {
  868. $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with donation
  869. } else {
  870. // PaymentDonation does not support multi currency
  871. $postactionmessages[] = 'Payment donation can\'t be payed with diffent currency than '.$conf->currency;
  872. $ispostactionok = -1;
  873. $error++; // Not yet supported
  874. }
  875. $paiement->fk_donation = $don->id;
  876. $paiement->datepaid = $now;
  877. $paiement->paymenttype = $paymentTypeId;
  878. $paiement->num_payment = '';
  879. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
  880. $paiement->ext_payment_id = $TRANSACTIONID;
  881. $paiement->ext_payment_site = $service;
  882. if (!$error) {
  883. $paiement_id = $paiement->create($user, 1);
  884. if ($paiement_id < 0) {
  885. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  886. $ispostactionok = -1;
  887. $error++;
  888. } else {
  889. $postactionmessages[] = 'Payment created';
  890. $ispostactionok = 1;
  891. if ($totalpayed >= $don->getRemainToPay()) $don->setPaid($don->id);
  892. }
  893. }
  894. if (!$error && !empty($conf->banque->enabled)) {
  895. $bankaccountid = 0;
  896. if ($paymentmethod == 'paybox') {
  897. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  898. } elseif ($paymentmethod == 'paypal') {
  899. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  900. } elseif ($paymentmethod == 'stripe') {
  901. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  902. }
  903. if ($bankaccountid > 0) {
  904. $result = $paiement->addPaymentToBank($user, 'payment_donation', '(DonationPayment)', $bankaccountid, '', '');
  905. if ($result < 0) {
  906. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  907. $ispostactionok = -1;
  908. $error++;
  909. } else {
  910. $postactionmessages[] = 'Bank transaction of payment created';
  911. $ispostactionok = 1;
  912. }
  913. } else {
  914. $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
  915. $ispostactionok = -1;
  916. $error++;
  917. }
  918. }
  919. if (!$error) {
  920. $db->commit();
  921. } else {
  922. $db->rollback();
  923. }
  924. } else {
  925. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type" ('.$paymentType.') to record the payment of donation '.$tmptag['DON'].'. May be payment was already recorded.';
  926. $ispostactionok = -1;
  927. }
  928. } else {
  929. $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
  930. $ispostactionok = -1;
  931. }
  932. // TODO send email with acknowledgment for the donation
  933. // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
  934. } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
  935. // Record payment for registration to an event for an attendee
  936. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  937. $object = new Facture($db);
  938. $result = $object->fetch($ref);
  939. if ($result) {
  940. $paymentTypeId = 0;
  941. if ($paymentmethod == 'paybox') {
  942. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  943. }
  944. if ($paymentmethod == 'paypal') {
  945. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  946. }
  947. if ($paymentmethod == 'stripe') {
  948. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  949. }
  950. if (empty($paymentTypeId)) {
  951. if (empty($paymentType)) {
  952. $paymentType = 'CB';
  953. }
  954. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  955. }
  956. // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
  957. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  958. $resultvalidate = $object->validate($user);
  959. if ($resultvalidate < 0) {
  960. $postactionmessages[] = 'Cannot validate invoice';
  961. $ispostactionok = -1;
  962. $error++; // Not yet supported
  963. } else {
  964. $db->begin();
  965. // Creation of payment line
  966. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  967. $paiement = new Paiement($db);
  968. $paiement->datepaye = $now;
  969. if ($currencyCodeType == $conf->currency) {
  970. $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  971. } else {
  972. $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
  973. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  974. $ispostactionok = -1;
  975. $error++; // Not yet supported
  976. }
  977. $paiement->paiementid = $paymentTypeId;
  978. $paiement->num_payment = '';
  979. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
  980. $paiement->ext_payment_id = $TRANSACTIONID;
  981. $paiement->ext_payment_site = $service;
  982. if (!$error) {
  983. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  984. if ($paiement_id < 0) {
  985. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  986. $ispostactionok = -1;
  987. $error++;
  988. } else {
  989. $postactionmessages[] = 'Payment created';
  990. $ispostactionok = 1;
  991. }
  992. }
  993. if (!$error && !empty($conf->banque->enabled)) {
  994. $bankaccountid = 0;
  995. if ($paymentmethod == 'paybox') {
  996. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  997. } elseif ($paymentmethod == 'paypal') {
  998. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  999. } elseif ($paymentmethod == 'stripe') {
  1000. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  1001. }
  1002. if ($bankaccountid > 0) {
  1003. $label = '(CustomerInvoicePayment)';
  1004. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  1005. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  1006. }
  1007. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  1008. if ($result < 0) {
  1009. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1010. $ispostactionok = -1;
  1011. $error++;
  1012. } else {
  1013. $postactionmessages[] = 'Bank transaction of payment created';
  1014. $ispostactionok = 1;
  1015. }
  1016. } else {
  1017. $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
  1018. $ispostactionok = -1;
  1019. $error++;
  1020. }
  1021. }
  1022. if (!$error) {
  1023. // Validating the attendee
  1024. $attendeetovalidate = new ConferenceOrBoothAttendee($db);
  1025. $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
  1026. if ($resultattendee < 0) {
  1027. $error++;
  1028. setEventMessages(null, $attendeetovalidate->errors, "errors");
  1029. } else {
  1030. $attendeetovalidate->validate($user);
  1031. $attendeetovalidate->amount = $FinalPaymentAmt;
  1032. $attendeetovalidate->date_subscription = dol_now();
  1033. $attendeetovalidate->update($user);
  1034. }
  1035. }
  1036. if (!$error) {
  1037. $db->commit();
  1038. } else {
  1039. setEventMessages(null, $postactionmessages, 'warnings');
  1040. $db->rollback();
  1041. }
  1042. if (! $error) {
  1043. // Sending mail
  1044. $thirdparty = new Societe($db);
  1045. $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
  1046. if ($resultthirdparty < 0) {
  1047. setEventMessages(null, $attendeetovalidate->errors, "errors");
  1048. } else {
  1049. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1050. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1051. $formmail = new FormMail($db);
  1052. // Set output language
  1053. $outputlangs = new Translate('', $conf);
  1054. $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
  1055. // Load traductions files required by page
  1056. $outputlangs->loadLangs(array("main", "members"));
  1057. // Get email content from template
  1058. $arraydefaultmessage = null;
  1059. $labeltouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT;
  1060. if (!empty($labeltouse)) {
  1061. $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $labeltouse, 1, '');
  1062. }
  1063. if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  1064. $subject = $arraydefaultmessage->topic;
  1065. $msg = $arraydefaultmessage->content;
  1066. }
  1067. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
  1068. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  1069. $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
  1070. $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
  1071. $sendto = $attendeetovalidate->email;
  1072. $from = $conf->global->MAILING_EMAIL_FROM;
  1073. $urlback = $_SERVER["REQUEST_URI"];
  1074. $ishtml = dol_textishtml($texttosend); // May contain urls
  1075. $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml);
  1076. $result = $mailfile->sendfile();
  1077. if ($result) {
  1078. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1079. } else {
  1080. dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
  1081. }
  1082. }
  1083. }
  1084. }
  1085. } else {
  1086. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type" ('.$paymentType.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
  1087. $ispostactionok = -1;
  1088. }
  1089. } else {
  1090. $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
  1091. $ispostactionok = -1;
  1092. }
  1093. } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
  1094. // Record payment for booth or conference
  1095. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1096. $object = new Facture($db);
  1097. $result = $object->fetch($ref);
  1098. if ($result) {
  1099. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  1100. $paymentTypeId = 0;
  1101. if ($paymentmethod == 'paybox') {
  1102. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  1103. }
  1104. if ($paymentmethod == 'paypal') {
  1105. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  1106. }
  1107. if ($paymentmethod == 'stripe') {
  1108. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  1109. }
  1110. if (empty($paymentTypeId)) {
  1111. if (empty($paymentType)) {
  1112. $paymentType = 'CB';
  1113. }
  1114. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  1115. }
  1116. // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
  1117. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  1118. $resultvalidate = $object->validate($user);
  1119. if ($resultvalidate < 0) {
  1120. $postactionmessages[] = 'Cannot validate invoice';
  1121. $ispostactionok = -1;
  1122. $error++; // Not yet supported
  1123. } else {
  1124. $db->begin();
  1125. // Creation of payment line
  1126. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  1127. $paiement = new Paiement($db);
  1128. $paiement->datepaye = $now;
  1129. if ($currencyCodeType == $conf->currency) {
  1130. $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  1131. } else {
  1132. $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
  1133. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  1134. $ispostactionok = -1;
  1135. $error++; // Not yet supported
  1136. }
  1137. $paiement->paiementid = $paymentTypeId;
  1138. $paiement->num_payment = '';
  1139. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
  1140. $paiement->ext_payment_id = $TRANSACTIONID;
  1141. $paiement->ext_payment_site = $service;
  1142. if (!$error) {
  1143. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  1144. if ($paiement_id < 0) {
  1145. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1146. $ispostactionok = -1;
  1147. $error++;
  1148. } else {
  1149. $postactionmessages[] = 'Payment created';
  1150. $ispostactionok = 1;
  1151. }
  1152. }
  1153. if (!$error && !empty($conf->banque->enabled)) {
  1154. $bankaccountid = 0;
  1155. if ($paymentmethod == 'paybox') {
  1156. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  1157. } elseif ($paymentmethod == 'paypal') {
  1158. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  1159. } elseif ($paymentmethod == 'stripe') {
  1160. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  1161. }
  1162. if ($bankaccountid > 0) {
  1163. $label = '(CustomerInvoicePayment)';
  1164. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  1165. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  1166. }
  1167. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  1168. if ($result < 0) {
  1169. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1170. $ispostactionok = -1;
  1171. $error++;
  1172. } else {
  1173. $postactionmessages[] = 'Bank transaction of payment created';
  1174. $ispostactionok = 1;
  1175. }
  1176. } else {
  1177. $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
  1178. $ispostactionok = -1;
  1179. $error++;
  1180. }
  1181. }
  1182. if (!$error) {
  1183. // Putting the booth to "suggested" state
  1184. $booth = new ConferenceOrBooth($db);
  1185. $resultbooth = $booth->fetch((int) $tmptag['BOO']);
  1186. if ($resultbooth < 0) {
  1187. $error++;
  1188. setEventMessages(null, $booth->errors, "errors");
  1189. } else {
  1190. $booth->status = CONFERENCEORBOOTH::STATUS_SUGGESTED;
  1191. $resultboothupdate = $booth->update($user);
  1192. if ($resultboothupdate<0) {
  1193. // Finding the thirdparty by getting the invoice
  1194. $invoice = new Facture($db);
  1195. $resultinvoice = $invoice->fetch($ref);
  1196. if ($resultinvoice<0) {
  1197. $postactionmessages[] = 'Could not find the associated invoice.';
  1198. $ispostactionok = -1;
  1199. $error++;
  1200. } else {
  1201. $thirdparty = new Societe($db);
  1202. $resultthirdparty = $thirdparty->fetch($invoice->socid);
  1203. if ($resultthirdparty<0) {
  1204. $error++;
  1205. setEventMessages(null, $thirdparty->errors, "errors");
  1206. } else {
  1207. // Sending mail
  1208. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1209. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1210. $formmail = new FormMail($db);
  1211. // Set output language
  1212. $outputlangs = new Translate('', $conf);
  1213. $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
  1214. // Load traductions files required by page
  1215. $outputlangs->loadLangs(array("main", "members"));
  1216. // Get email content from template
  1217. $arraydefaultmessage = null;
  1218. $labeltouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT;
  1219. if (!empty($labeltouse)) {
  1220. $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $labeltouse, 1, '');
  1221. }
  1222. if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  1223. $subject = $arraydefaultmessage->topic;
  1224. $msg = $arraydefaultmessage->content;
  1225. }
  1226. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
  1227. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  1228. $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
  1229. $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
  1230. $sendto = $thirdparty->email;
  1231. $from = $conf->global->MAILING_EMAIL_FROM;
  1232. $urlback = $_SERVER["REQUEST_URI"];
  1233. $ishtml = dol_textishtml($texttosend); // May contain urls
  1234. $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml);
  1235. $result = $mailfile->sendfile();
  1236. if ($result) {
  1237. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1238. } else {
  1239. dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
  1240. }
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. if (!$error) {
  1247. $db->commit();
  1248. } else {
  1249. $db->rollback();
  1250. }
  1251. }
  1252. } else {
  1253. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type" ('.$paymentType.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
  1254. $ispostactionok = -1;
  1255. }
  1256. } else {
  1257. $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
  1258. $ispostactionok = -1;
  1259. }
  1260. } else {
  1261. // Nothing done
  1262. }
  1263. }
  1264. if ($ispaymentok) {
  1265. // Get on url call
  1266. $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
  1267. $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
  1268. // Set by newpayment.php
  1269. $paymentType = $_SESSION['PaymentType'];
  1270. $currencyCodeType = $_SESSION['currencyCodeType'];
  1271. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  1272. if (is_object($object) && method_exists($object, 'call_trigger')) {
  1273. // Call trigger
  1274. $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
  1275. if ($result < 0) {
  1276. $error++;
  1277. }
  1278. // End call triggers
  1279. } elseif (get_class($object) == 'stdClass') {
  1280. //In some case $object is not instanciate (for paiement on custom object) We need to deal with payment
  1281. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  1282. $paiement = new Paiement($db);
  1283. $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
  1284. if ($result < 0) $error++;
  1285. }
  1286. print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
  1287. if ($TRANSACTIONID) {
  1288. print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n";
  1289. }
  1290. $key = 'ONLINE_PAYMENT_MESSAGE_OK';
  1291. if (!empty($conf->global->$key)) {
  1292. print '<br>';
  1293. print $conf->global->$key;
  1294. }
  1295. $sendemail = '';
  1296. if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) {
  1297. $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL;
  1298. }
  1299. $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
  1300. dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
  1301. // Send an email to admins
  1302. if ($sendemail) {
  1303. $companylangs = new Translate('', $conf);
  1304. $companylangs->setDefaultLang($mysoc->default_lang);
  1305. $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
  1306. $sendto = $sendemail;
  1307. $from = $conf->global->MAILING_EMAIL_FROM;
  1308. // Define $urlwithroot
  1309. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1310. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1311. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1312. // Define link to login card
  1313. $appli = constant('DOL_APPLICATION_TITLE');
  1314. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  1315. $appli = $conf->global->MAIN_APPLICATION_TITLE;
  1316. if (preg_match('/\d\.\d/', $appli)) {
  1317. if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
  1318. $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
  1319. }
  1320. } else {
  1321. $appli .= " ".DOL_VERSION;
  1322. }
  1323. } else {
  1324. $appli .= " ".DOL_VERSION;
  1325. }
  1326. $urlback = $_SERVER["REQUEST_URI"];
  1327. $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
  1328. $content = "";
  1329. if (array_key_exists('MEM', $tmptag)) {
  1330. $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
  1331. $content .= '<strong>'.$companylangs->trans("PaymentSubscription")."</strong><br><br>\n";
  1332. $content .= $companylangs->trans("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
  1333. $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
  1334. } elseif (array_key_exists('INV', $tmptag)) {
  1335. $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
  1336. $content .= '<strong>'.$companylangs->trans("Payment")."</strong><br><br>\n";
  1337. $content .= $companylangs->trans("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
  1338. //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
  1339. $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
  1340. } else {
  1341. $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
  1342. }
  1343. $content .= $companylangs->transnoentities("PostActionAfterPayment").' : ';
  1344. if ($ispostactionok > 0) {
  1345. //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
  1346. $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
  1347. } elseif ($ispostactionok == 0) {
  1348. $content .= $companylangs->transnoentitiesnoconv("None");
  1349. } else {
  1350. $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
  1351. $content .= '<span style="color: red">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
  1352. }
  1353. $content .= '<br>'."\n";
  1354. foreach ($postactionmessages as $postactionmessage) {
  1355. $content .= ' * '.$postactionmessage.'<br>'."\n";
  1356. }
  1357. if ($ispostactionok < 0) {
  1358. $content .= $langs->transnoentities("ARollbackWasPerformedOnPostActions");
  1359. }
  1360. $content .= '<br>'."\n";
  1361. $content .= "<br>\n";
  1362. $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
  1363. $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
  1364. $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
  1365. $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
  1366. $content .= "<br>\n";
  1367. $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
  1368. if (!empty($ErrorCode)) {
  1369. $content .= "ErrorCode = ".$ErrorCode."<br>\n";
  1370. }
  1371. if (!empty($ErrorShortMsg)) {
  1372. $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
  1373. }
  1374. if (!empty($ErrorLongMsg)) {
  1375. $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
  1376. }
  1377. if (!empty($ErrorSeverityCode)) {
  1378. $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
  1379. }
  1380. $ishtml = dol_textishtml($content); // May contain urls
  1381. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1382. $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
  1383. $result = $mailfile->sendfile();
  1384. if ($result) {
  1385. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1386. //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
  1387. } else {
  1388. dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
  1389. //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
  1390. }
  1391. }
  1392. } else {
  1393. // Get on url call
  1394. $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
  1395. $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
  1396. // Set by newpayment.php
  1397. $paymentType = $_SESSION['PaymentType'];
  1398. $currencyCodeType = $_SESSION['currencyCodeType'];
  1399. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  1400. if (is_object($object) && method_exists($object, 'call_trigger')) {
  1401. // Call trigger
  1402. $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
  1403. if ($result < 0) {
  1404. $error++;
  1405. }
  1406. // End call triggers
  1407. }
  1408. print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
  1409. print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
  1410. print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
  1411. print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
  1412. print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
  1413. if ($mysoc->email) {
  1414. print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
  1415. }
  1416. $sendemail = '';
  1417. if (!empty($conf->global->PAYMENTONLINE_SENDEMAIL)) {
  1418. $sendemail = $conf->global->PAYMENTONLINE_SENDEMAIL;
  1419. }
  1420. // TODO Remove local option to keep only the generic one ?
  1421. if ($paymentmethod == 'paypal' && !empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) {
  1422. $sendemail = $conf->global->PAYPAL_PAYONLINE_SENDEMAIL;
  1423. } elseif ($paymentmethod == 'paybox' && !empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) {
  1424. $sendemail = $conf->global->PAYBOX_PAYONLINE_SENDEMAIL;
  1425. } elseif ($paymentmethod == 'stripe' && !empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) {
  1426. $sendemail = $conf->global->STRIPE_PAYONLINE_SENDEMAIL;
  1427. }
  1428. // Send warning of error to administrator
  1429. if ($sendemail) {
  1430. $companylangs = new Translate('', $conf);
  1431. $companylangs->setDefaultLang($mysoc->default_lang);
  1432. $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
  1433. $sendto = $sendemail;
  1434. $from = $conf->global->MAILING_EMAIL_FROM;
  1435. // Define $urlwithroot
  1436. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1437. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1438. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1439. // Define link to login card
  1440. $appli = constant('DOL_APPLICATION_TITLE');
  1441. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  1442. $appli = $conf->global->MAIN_APPLICATION_TITLE;
  1443. if (preg_match('/\d\.\d/', $appli)) {
  1444. if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
  1445. $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
  1446. }
  1447. } else {
  1448. $appli .= " ".DOL_VERSION;
  1449. }
  1450. } else {
  1451. $appli .= " ".DOL_VERSION;
  1452. }
  1453. $urlback = $_SERVER["REQUEST_URI"];
  1454. $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
  1455. $content = "";
  1456. $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
  1457. $content .= "<br><br>\n";
  1458. $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
  1459. $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
  1460. $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
  1461. $content .= "<br>\n";
  1462. $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
  1463. $ishtml = dol_textishtml($content); // May contain urls
  1464. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1465. $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
  1466. $result = $mailfile->sendfile();
  1467. if ($result) {
  1468. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1469. } else {
  1470. dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
  1471. }
  1472. }
  1473. }
  1474. print "\n</div>\n";
  1475. print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag($paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
  1476. htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix);
  1477. // Clean session variables to avoid duplicate actions if post is resent
  1478. unset($_SESSION["FinalPaymentAmt"]);
  1479. unset($_SESSION["TRANSACTIONID"]);
  1480. llxFooter('', 'public');
  1481. $db->close();