paymentok.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973
  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-2023 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. // Load Dolibarr environment
  50. require '../../main.inc.php';
  51. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  52. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  53. if (isModEnabled('paypal')) {
  54. require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
  55. require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php';
  56. }
  57. // Hook to be used by external payment modules (ie Payzen, ...)
  58. $hookmanager = new HookManager($db);
  59. $hookmanager->initHooks(array('newpayment'));
  60. $langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal"));
  61. // Clean parameters
  62. if (isModEnabled('paypal')) {
  63. $PAYPAL_API_USER = "";
  64. if (getDolGlobalString('PAYPAL_API_USER')) {
  65. $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER;
  66. }
  67. $PAYPAL_API_PASSWORD = "";
  68. if (getDolGlobalString('PAYPAL_API_PASSWORD')) {
  69. $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD;
  70. }
  71. $PAYPAL_API_SIGNATURE = "";
  72. if (getDolGlobalString('PAYPAL_API_SIGNATURE')) {
  73. $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE;
  74. }
  75. $PAYPAL_API_SANDBOX = "";
  76. if (getDolGlobalString('PAYPAL_API_SANDBOX')) {
  77. $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX;
  78. }
  79. $PAYPAL_API_OK = "";
  80. if ($urlok) {
  81. $PAYPAL_API_OK = $urlok;
  82. }
  83. $PAYPAL_API_KO = "";
  84. if ($urlko) {
  85. $PAYPAL_API_KO = $urlko;
  86. }
  87. $PAYPALTOKEN = GETPOST('TOKEN');
  88. if (empty($PAYPALTOKEN)) {
  89. $PAYPALTOKEN = GETPOST('token');
  90. }
  91. $PAYPALPAYERID = GETPOST('PAYERID');
  92. if (empty($PAYPALPAYERID)) {
  93. $PAYPALPAYERID = GETPOST('PayerID');
  94. }
  95. }
  96. $FULLTAG = GETPOST('FULLTAG');
  97. if (empty($FULLTAG)) {
  98. $FULLTAG = GETPOST('fulltag');
  99. }
  100. $source = GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha');
  101. $ref = GETPOST('ref');
  102. $suffix = GETPOST("suffix", 'aZ09');
  103. $membertypeid = GETPOST("membertypeid", 'int');
  104. // Detect $paymentmethod
  105. $paymentmethod = '';
  106. $reg = array();
  107. if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) {
  108. $paymentmethod = $reg[1];
  109. }
  110. if (empty($paymentmethod)) {
  111. dol_syslog("***** paymentok.php was called with a non valid parameter FULLTAG=".$FULLTAG, LOG_DEBUG, 0, '_payment');
  112. dol_print_error(null, 'The callback url does not contain a parameter fulltag that should help us to find the payment method used');
  113. exit;
  114. }
  115. dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLTAG=".$FULLTAG." REQUEST_URI=".$_SERVER["REQUEST_URI"], LOG_DEBUG, 0, '_payment');
  116. $validpaymentmethod = array();
  117. if (isModEnabled('paypal')) {
  118. $validpaymentmethod['paypal'] = 'paypal';
  119. }
  120. if (isModEnabled('paybox')) {
  121. $validpaymentmethod['paybox'] = 'paybox';
  122. }
  123. if (isModEnabled('stripe')) {
  124. $validpaymentmethod['stripe'] = 'stripe';
  125. }
  126. // Security check
  127. if (empty($validpaymentmethod)) {
  128. httponly_accessforbidden('No valid payment mode');
  129. }
  130. $ispaymentok = false;
  131. // If payment is ok
  132. $PAYMENTSTATUS = $TRANSACTIONID = $TAXAMT = $NOTE = '';
  133. // If payment is ko
  134. $ErrorCode = $ErrorShortMsg = $ErrorLongMsg = $ErrorSeverityCode = '';
  135. $object = new stdClass(); // For triggers
  136. $error = 0;
  137. /*
  138. * Actions
  139. */
  140. /*
  141. * View
  142. */
  143. $now = dol_now();
  144. dol_syslog("Callback url when a payment was done. query_string=".(empty($_SERVER["QUERY_STRING"]) ? '' : dol_escape_htmltag($_SERVER["QUERY_STRING"]))." script_uri=".(empty($_SERVER["SCRIPT_URI"]) ? '' : dol_escape_htmltag($_SERVER["SCRIPT_URI"])), LOG_DEBUG, 0, '_payment');
  145. dol_syslog("_SERVER[SERVER_NAME] = ".(empty($_SERVER["SERVER_NAME"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_NAME"])), LOG_DEBUG, 0, '_payment');
  146. dol_syslog("_SERVER[SERVER_ADDR] = ".(empty($_SERVER["SERVER_ADDR"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_ADDR"])), LOG_DEBUG, 0, '_payment');
  147. $tracepost = "";
  148. foreach ($_POST as $k => $v) {
  149. if (is_scalar($k) && is_scalar($v)) {
  150. $tracepost .= "$k - $v\n";
  151. }
  152. }
  153. dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment');
  154. $tracesession = "";
  155. foreach ($_SESSION as $k => $v) {
  156. if (is_scalar($k) && is_scalar($v)) {
  157. $tracesession .= "$k - $v\n";
  158. }
  159. }
  160. dol_syslog("SESSION=".$tracesession, LOG_DEBUG, 0, '_payment');
  161. $head = '';
  162. if (getDolGlobalString('ONLINE_PAYMENT_CSS_URL')) {
  163. $head = '<link rel="stylesheet" type="text/css" href="' . getDolGlobalString('ONLINE_PAYMENT_CSS_URL').'?lang='.$langs->defaultlang.'">'."\n";
  164. }
  165. $conf->dol_hide_topmenu = 1;
  166. $conf->dol_hide_leftmenu = 1;
  167. $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
  168. llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);
  169. // Show message
  170. print '<span id="dolpaymentspan"></span>'."\n";
  171. print '<div id="dolpaymentdiv" class="center">'."\n";
  172. // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo)
  173. // Define logo and logosmall
  174. $logosmall = $mysoc->logo_small;
  175. $logo = $mysoc->logo;
  176. $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix;
  177. if (!empty($conf->global->$paramlogo)) {
  178. $logosmall = $conf->global->$paramlogo;
  179. } elseif (getDolGlobalString('ONLINE_PAYMENT_LOGO')) {
  180. $logosmall = $conf->global->ONLINE_PAYMENT_LOGO;
  181. }
  182. //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
  183. // Define urllogo
  184. $urllogo = '';
  185. $urllogofull = '';
  186. if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
  187. $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
  188. $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
  189. } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
  190. $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
  191. $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
  192. }
  193. // Output html code for logo
  194. if ($urllogo) {
  195. print '<div class="backgreypublicpayment">';
  196. print '<div class="logopublicpayment">';
  197. print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
  198. print '>';
  199. print '</div>';
  200. if (!getDolGlobalString('MAIN_HIDE_POWERED_BY')) {
  201. 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>';
  202. }
  203. print '</div>';
  204. }
  205. if (getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT')) {
  206. print '<div class="backimagepublicpayment">';
  207. print '<img id="idMAIN_IMAGE_PUBLIC_PAYMENT" src="' . getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT').'">';
  208. print '</div>';
  209. }
  210. print '<br><br><br>';
  211. if (isModEnabled('paypal')) {
  212. if ($paymentmethod === 'paypal') { // We call this page only if payment is ok on payment system
  213. if ($PAYPALTOKEN) {
  214. // Get on url call
  215. $onlinetoken = $PAYPALTOKEN;
  216. $fulltag = $FULLTAG;
  217. $payerID = $PAYPALPAYERID;
  218. // Set by newpayment.php
  219. $currencyCodeType = $_SESSION['currencyCodeType'];
  220. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  221. $paymentType = $_SESSION['PaymentType']; // Value can be 'Mark', 'Sole', 'Sale' for example
  222. // From env
  223. $ipaddress = $_SESSION['ipaddress'];
  224. dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
  225. // Validate record
  226. if (!empty($paymentType)) {
  227. dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment');
  228. $resArray = getDetails($onlinetoken);
  229. //var_dump($resarray);
  230. $ack = strtoupper($resArray["ACK"]);
  231. if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
  232. // Nothing to do
  233. dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
  234. } else {
  235. dol_syslog("Call to GetExpressCheckoutDetails return error: ".json_encode($resArray), LOG_WARNING, '_payment');
  236. }
  237. dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
  238. $resArray2 = confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag);
  239. //var_dump($resarray);
  240. $ack = strtoupper($resArray2["ACK"]);
  241. if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
  242. dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
  243. $object->source = $source;
  244. $object->ref = $ref;
  245. $object->payerID = $payerID;
  246. $object->fulltag = $fulltag;
  247. $object->resArray = $resArray2;
  248. // resArray was built from a string like that
  249. // 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
  250. $PAYMENTSTATUS = urldecode($resArray2["PAYMENTSTATUS"]); // Should contains 'Completed'
  251. $TRANSACTIONID = urldecode($resArray2["TRANSACTIONID"]);
  252. $TAXAMT = urldecode($resArray2["TAXAMT"]);
  253. $NOTE = urldecode($resArray2["NOTE"]);
  254. $ispaymentok = true;
  255. } else {
  256. dol_syslog("Call to DoExpressCheckoutPayment return error: ".json_encode($resArray2), LOG_WARNING, 0, '_payment');
  257. //Display a user friendly Error on the page using any of the following error information returned by PayPal
  258. $ErrorCode = urldecode($resArray2["L_ERRORCODE0"]);
  259. $ErrorShortMsg = urldecode($resArray2["L_SHORTMESSAGE0"]);
  260. $ErrorLongMsg = urldecode($resArray2["L_LONGMESSAGE0"]);
  261. $ErrorSeverityCode = urldecode($resArray2["L_SEVERITYCODE0"]);
  262. }
  263. } else {
  264. $ErrorCode = "SESSIONEXPIRED";
  265. $ErrorLongMsg = "Session expired. Can't retreive PaymentType. Payment has not been validated.";
  266. $ErrorShortMsg = "Session expired";
  267. dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
  268. dol_print_error('', 'Session expired');
  269. }
  270. } else {
  271. $ErrorCode = "PAYPALTOKENNOTDEFINED";
  272. $ErrorLongMsg = "The parameter PAYPALTOKEN was not defined. Payment has not been validated.";
  273. $ErrorShortMsg = "Parameter PAYPALTOKEN not defined";
  274. dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
  275. dol_print_error('', 'PAYPALTOKEN not defined');
  276. }
  277. }
  278. }
  279. if (isModEnabled('paybox')) {
  280. if ($paymentmethod === 'paybox') {
  281. // TODO Add a check to validate that payment is ok.
  282. $ispaymentok = true; // We call this page only if payment is ok on payment system
  283. }
  284. }
  285. if (isModEnabled('stripe')) {
  286. if ($paymentmethod === 'stripe') {
  287. // TODO Add a check to validate that payment is ok. We can request Stripe with payment_intent and payment_intent_client_secret
  288. $ispaymentok = true; // We call this page only if payment is ok on payment system
  289. }
  290. }
  291. // Check status of the object to verify if it is paid by external payment modules
  292. $action = '';
  293. $parameters = [
  294. 'paymentmethod' => $paymentmethod,
  295. ];
  296. $reshook = $hookmanager->executeHooks('isPaymentOK', $parameters, $object, $action);
  297. if ($reshook >= 0) {
  298. if (isset($hookmanager->resArray['ispaymentok'])) {
  299. dol_syslog('ispaymentok overwrite by hook return with value='.$hookmanager->resArray['ispaymentok'], LOG_DEBUG, 0, '_payment');
  300. $ispaymentok = $hookmanager->resArray['ispaymentok'];
  301. }
  302. }
  303. // If data not provided into callback url, search them into the session env
  304. if (empty($ipaddress)) {
  305. $ipaddress = $_SESSION['ipaddress'];
  306. }
  307. if (empty($TRANSACTIONID)) {
  308. $TRANSACTIONID = $_SESSION['TRANSACTIONID']; // pi_... or ch_...
  309. if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
  310. // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
  311. $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
  312. }
  313. }
  314. if (empty($FinalPaymentAmt)) {
  315. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  316. }
  317. if (empty($currencyCodeType)) {
  318. $currencyCodeType = $_SESSION['currencyCodeType'];
  319. }
  320. // Seems used onyl by Paypal
  321. if (empty($paymentType)) {
  322. $paymentType = $_SESSION["paymentType"];
  323. }
  324. $fulltag = $FULLTAG;
  325. $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
  326. dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG_DEBUG, 0, '_payment');
  327. // Set $appli for emails title
  328. $appli = $mysoc->name;
  329. // Make complementary actions
  330. $ispostactionok = 0;
  331. $postactionmessages = array();
  332. if ($ispaymentok) {
  333. // Set permission for the anonymous user
  334. if (empty($user->rights->societe)) {
  335. $user->rights->societe = new stdClass();
  336. }
  337. if (empty($user->rights->facture)) {
  338. $user->rights->facture = new stdClass();
  339. $user->rights->facture->invoice_advance = new stdClass();
  340. }
  341. if (empty($user->rights->adherent)) {
  342. $user->rights->adherent = new stdClass();
  343. $user->rights->adherent->cotisation = new stdClass();
  344. }
  345. $user->rights->societe->creer = 1;
  346. $user->rights->facture->creer = 1;
  347. $user->rights->facture->invoice_advance->validate = 1;
  348. $user->rights->adherent->cotisation->creer = 1;
  349. if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) {
  350. // Validate member
  351. // Create subscription
  352. // Create complementary actions (this include creation of thirdparty)
  353. // Send confirmation email
  354. // Record subscription
  355. include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  356. include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
  357. include_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
  358. $adht = new AdherentType($db);
  359. $object = new Adherent($db);
  360. $result1 = $object->fetch((int) $tmptag['MEM']);
  361. $result2 = $adht->fetch($object->typeid);
  362. $defaultdelay = !empty($adht->duration_value) ? $adht->duration_value : 1;
  363. $defaultdelayunit = !empty($adht->duration_unit) ? $adht->duration_unit : 'y';
  364. dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment');
  365. if ($result1 > 0 && $result2 > 0) {
  366. $paymentTypeId = 0;
  367. if ($paymentmethod == 'paybox') {
  368. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  369. }
  370. if ($paymentmethod == 'paypal') {
  371. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  372. }
  373. if ($paymentmethod == 'stripe') {
  374. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  375. }
  376. if (empty($paymentTypeId)) {
  377. dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
  378. if (empty($paymentType)) {
  379. $paymentType = 'CB';
  380. }
  381. // May return nothing when paymentType means nothing
  382. // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
  383. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  384. // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
  385. if (empty($paymentTypeId) || $paymentTypeId < 0) {
  386. $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
  387. }
  388. }
  389. dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId." currencyCodeType=".$currencyCodeType, LOG_DEBUG, 0, '_payment');
  390. // 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)
  391. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  392. // Security protection:
  393. if (empty($adht->caneditamount)) { // If we didn't allow members to choose their membership amount (if the amount is allowed in edit mode, no need to check)
  394. if ($object->status == $object::STATUS_DRAFT) { // If the member is not yet validated, we check that the amount is the same as expected.
  395. $typeid = $object->typeid;
  396. // Set amount for the subscription:
  397. // - First check the amount of the member type.
  398. $amountbytype = $adht->amountByType(1); // Load the array of amount per type
  399. $amountexpected = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
  400. // - If not found, take the default amount
  401. if (empty($amountexpected) && getDolGlobalString('MEMBER_NEWFORM_AMOUNT')) {
  402. $amountexpected = $conf->global->MEMBER_NEWFORM_AMOUNT;
  403. }
  404. if ($amountexpected && $amountexpected != $FinalPaymentAmt) {
  405. $error++;
  406. $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') differs from value expected for membership ('.$amountexpected.'). May be a hack to try to pay a different amount ?';
  407. $postactionmessages[] = $errmsg;
  408. $ispostactionok = -1;
  409. dol_syslog("Failed to validate member (bad amount check): ".$errmsg, LOG_ERR, 0, '_payment');
  410. }
  411. }
  412. }
  413. // Security protection:
  414. if (getDolGlobalString('MEMBER_MIN_AMOUNT')) {
  415. if ($FinalPaymentAmt < $conf->global->MEMBER_MIN_AMOUNT) {
  416. $error++;
  417. $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') is lower than the minimum allowed (' . getDolGlobalString('MEMBER_MIN_AMOUNT').'). May be a hack to try to pay a different amount ?';
  418. $postactionmessages[] = $errmsg;
  419. $ispostactionok = -1;
  420. dol_syslog("Failed to validate member (amount lower than minimum): ".$errmsg, LOG_ERR, 0, '_payment');
  421. }
  422. }
  423. // Security protection:
  424. if ($currencyCodeType && $currencyCodeType != $conf->currency) { // Check that currency is the good one
  425. $error++;
  426. $errmsg = 'Value of currencyCodeType ('.$currencyCodeType.') differs from value expected for membership ('.$conf->currency.'). May be a hack to try to pay a different amount ?';
  427. $postactionmessages[] = $errmsg;
  428. $ispostactionok = -1;
  429. dol_syslog("Failed to validate member (bad currency check): ".$errmsg, LOG_ERR, 0, '_payment');
  430. }
  431. if (! $error) {
  432. // We validate the member (no effect if it is already validated)
  433. $result = ($object->status == $object::STATUS_EXCLUDED) ? -1 : $object->validate($user); // if membre is excluded (status == -2) the new validation is not possible
  434. if ($result < 0 || empty($object->datevalid)) {
  435. $error++;
  436. $errmsg = $object->error;
  437. $postactionmessages[] = $errmsg;
  438. $postactionmessages = array_merge($postactionmessages, $object->errors);
  439. $ispostactionok = -1;
  440. dol_syslog("Failed to validate member: ".$errmsg, LOG_ERR, 0, '_payment');
  441. }
  442. }
  443. // Subscription informations
  444. $datesubscription = $object->datevalid; // By default, the subscription start date is the payment date
  445. if ($object->datefin > 0) {
  446. $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
  447. } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER')) {
  448. $datesubscription = dol_time_plus_duree($now, (int) substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), 0, -1), substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), -1));
  449. }
  450. if (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "m") {
  451. $datesubscription = dol_get_first_day(dol_print_date($datesubscription, "%Y"), dol_print_date($datesubscription, "%m"));
  452. } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "Y") {
  453. $datesubscription = dol_get_first_day(dol_print_date($datesubscription, "%Y"));
  454. }
  455. $datesubend = null;
  456. if ($datesubscription && $defaultdelay && $defaultdelayunit) {
  457. $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
  458. // the new end date of subscription must be in futur
  459. while ($datesubend < $now) {
  460. $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
  461. $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
  462. }
  463. $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
  464. }
  465. // Set output language
  466. $outputlangs = new Translate('', $conf);
  467. $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
  468. $paymentdate = $now;
  469. $amount = $FinalPaymentAmt;
  470. $formatteddate = dol_print_date($paymentdate, 'dayhour', 'auto', $outputlangs);
  471. $label = $langs->trans("OnlineSubscriptionPaymentLine", $formatteddate, $paymentmethod, $ipaddress, $TRANSACTIONID);
  472. // Payment informations
  473. $accountid = 0;
  474. if ($paymentmethod == 'paybox') {
  475. $accountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  476. }
  477. if ($paymentmethod == 'paypal') {
  478. $accountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  479. }
  480. if ($paymentmethod == 'stripe') {
  481. $accountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  482. }
  483. if ($accountid < 0) {
  484. $error++;
  485. $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
  486. $postactionmessages[] = $errmsg;
  487. $ispostactionok = -1;
  488. dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
  489. }
  490. $operation = dol_getIdFromCode($db, $paymentTypeId, 'c_paiement', 'id', 'code', 1); // Payment mode code returned from payment mode id
  491. $num_chq = '';
  492. $emetteur_nom = '';
  493. $emetteur_banque = '';
  494. // Define default choice for complementary actions
  495. $option = '';
  496. if (getDolGlobalString('ADHERENT_BANK_USE') == 'bankviainvoice' && isModEnabled("banque") && isModEnabled("societe") && isModEnabled('facture')) {
  497. $option = 'bankviainvoice';
  498. } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'bankdirect' && isModEnabled("banque")) {
  499. $option = 'bankdirect';
  500. } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'invoiceonly' && isModEnabled("banque") && isModEnabled("societe") && isModEnabled('facture')) {
  501. $option = 'invoiceonly';
  502. }
  503. if (empty($option)) {
  504. $option = 'none';
  505. }
  506. $sendalsoemail = 1;
  507. // Record the subscription then complementary actions
  508. $db->begin();
  509. // Create subscription
  510. if (!$error) {
  511. dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
  512. $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
  513. if ($crowid <= 0) {
  514. $error++;
  515. $errmsg = $object->error;
  516. $postactionmessages[] = $errmsg;
  517. $ispostactionok = -1;
  518. } else {
  519. $postactionmessages[] = 'Subscription created (id='.$crowid.')';
  520. $ispostactionok = 1;
  521. }
  522. }
  523. if (!$error) {
  524. dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
  525. $autocreatethirdparty = 1; // will create thirdparty if member not yet linked to a thirdparty
  526. $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
  527. if ($result < 0) {
  528. dol_syslog("Error ".$object->error." ".join(',', $object->errors), LOG_DEBUG, 0, '_payment');
  529. $error++;
  530. $postactionmessages[] = $object->error;
  531. $postactionmessages = array_merge($postactionmessages, $object->errors);
  532. $ispostactionok = -1;
  533. } else {
  534. if ($option == 'bankviainvoice') {
  535. $postactionmessages[] = 'Invoice, payment and bank record created';
  536. dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
  537. }
  538. if ($option == 'bankdirect') {
  539. $postactionmessages[] = 'Bank record created';
  540. dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
  541. }
  542. if ($option == 'invoiceonly') {
  543. $postactionmessages[] = 'Invoice recorded';
  544. dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
  545. }
  546. $ispostactionok = 1;
  547. // If an invoice was created, it is into $object->invoice
  548. }
  549. }
  550. if (!$error) {
  551. if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
  552. $thirdparty_id = $object->fk_soc;
  553. dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
  554. $service = 'StripeTest';
  555. $servicestatus = 0;
  556. if (getDolGlobalString('STRIPE_LIVE') && !GETPOST('forcesandbox', 'alpha')) {
  557. $service = 'StripeLive';
  558. $servicestatus = 1;
  559. }
  560. $stripeacc = null; // No Oauth/connect use for public pages
  561. $thirdparty = new Societe($db);
  562. $thirdparty->fetch($thirdparty_id);
  563. include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
  564. $stripe = new Stripe($db);
  565. //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
  566. $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
  567. if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
  568. dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
  569. try {
  570. global $stripearrayofkeysbyenv;
  571. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
  572. if (preg_match('/^pi_/', $TRANSACTIONID)) {
  573. // This may throw an error if not found.
  574. $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
  575. } else {
  576. // This throw an error if not found
  577. $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
  578. }
  579. if ($chpi) {
  580. $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
  581. if (empty($stripecu)) {
  582. // This include the INSERT
  583. $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
  584. // Link this customer to the payment intent
  585. if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
  586. \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
  587. }
  588. } else {
  589. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
  590. $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)";
  591. $resql = $db->query($sql);
  592. if (!$resql) { // should not happen
  593. $error++;
  594. $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
  595. dol_syslog($errmsg, LOG_ERR, 0, '_payment');
  596. $postactionmessages[] = $errmsg;
  597. $ispostactionok = -1;
  598. }
  599. }
  600. } else { // should not happen
  601. $error++;
  602. $errmsg = 'Failed to retreive paymentintent or charge from id';
  603. dol_syslog($errmsg, LOG_ERR, 0, '_payment');
  604. $postactionmessages[] = $errmsg;
  605. $ispostactionok = -1;
  606. }
  607. } catch (Exception $e) { // should not happen
  608. $error++;
  609. $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
  610. dol_syslog($errmsg, LOG_ERR, 0, '_payment');
  611. $postactionmessages[] = $errmsg;
  612. $ispostactionok = -1;
  613. }
  614. }
  615. }
  616. }
  617. if (!$error) {
  618. $db->commit();
  619. } else {
  620. $db->rollback();
  621. }
  622. // Send email to member
  623. if (!$error) {
  624. dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
  625. // Send confirmation Email
  626. if ($object->email && $sendalsoemail) {
  627. $subject = '';
  628. $msg = '';
  629. // Send subscription email
  630. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  631. $formmail = new FormMail($db);
  632. // Load traductions files required by page
  633. $outputlangs->loadLangs(array("main", "members"));
  634. // Get email content from template
  635. $arraydefaultmessage = null;
  636. $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
  637. if (!empty($labeltouse)) {
  638. $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
  639. }
  640. if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  641. $subject = $arraydefaultmessage->topic;
  642. $msg = $arraydefaultmessage->content;
  643. }
  644. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
  645. // Create external user
  646. if (getDolGlobalString('ADHERENT_CREATE_EXTERNAL_USER_LOGIN')) {
  647. $infouserlogin = '';
  648. $nuser = new User($db);
  649. $tmpuser = dol_clone($object);
  650. $result = $nuser->create_from_member($tmpuser, $object->login);
  651. $newpassword = $nuser->setPassword($user, '');
  652. if ($result < 0) {
  653. $outputlangs->load("errors");
  654. $postactionmessages[] = 'Error in create external user : '.$nuser->error;
  655. } else {
  656. $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
  657. $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
  658. }
  659. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
  660. }
  661. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  662. $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
  663. $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
  664. // Attach a file ?
  665. $file = '';
  666. $listofpaths = array();
  667. $listofnames = array();
  668. $listofmimes = array();
  669. if (is_object($object->invoice)) {
  670. $invoicediroutput = $conf->facture->dir_output;
  671. $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
  672. $file = $fileparams['fullname'];
  673. $listofpaths = array($file);
  674. $listofnames = array(basename($file));
  675. $listofmimes = array(dol_mimetype($file));
  676. }
  677. $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
  678. $result = $object->sendEmail($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
  679. if ($result < 0) {
  680. $errmsg = $object->error;
  681. $postactionmessages[] = $errmsg;
  682. $ispostactionok = -1;
  683. } else {
  684. if ($file) {
  685. $postactionmessages[] = 'Email sent to member (with invoice document attached)';
  686. } else {
  687. $postactionmessages[] = 'Email sent to member (without any attached document)';
  688. }
  689. // TODO Add actioncomm event
  690. }
  691. }
  692. }
  693. } else {
  694. $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.';
  695. $ispostactionok = -1;
  696. }
  697. } else {
  698. $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
  699. $ispostactionok = -1;
  700. }
  701. } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
  702. // Record payment
  703. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  704. $object = new Facture($db);
  705. $result = $object->fetch((int) $tmptag['INV']);
  706. if ($result) {
  707. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  708. $paymentTypeId = 0;
  709. if ($paymentmethod === 'paybox') {
  710. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  711. }
  712. if ($paymentmethod === 'paypal') {
  713. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  714. }
  715. if ($paymentmethod === 'stripe') {
  716. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  717. }
  718. if (empty($paymentTypeId)) {
  719. dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
  720. if (empty($paymentType)) {
  721. $paymentType = 'CB';
  722. }
  723. // May return nothing when paymentType means nothing
  724. // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
  725. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  726. // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
  727. if (empty($paymentTypeId) || $paymentTypeId < 0) {
  728. $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
  729. }
  730. }
  731. dol_syslog("FinalPaymentAmt = ".$FinalPaymentAmt." paymentTypeId = ".$paymentTypeId, LOG_DEBUG, 0, '_payment');
  732. // 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)
  733. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  734. $db->begin();
  735. // Creation of payment line
  736. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  737. $paiement = new Paiement($db);
  738. $paiement->datepaye = $now;
  739. if ($currencyCodeType == $conf->currency) {
  740. $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  741. } else {
  742. $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
  743. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  744. $ispostactionok = -1;
  745. $error++; // Not yet supported
  746. }
  747. $paiement->paiementid = $paymentTypeId;
  748. $paiement->num_payment = '';
  749. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
  750. $paiement->ext_payment_id = $TRANSACTIONID; // TODO LDR May be we should store py_... instead of pi_... but we started with pi_... so we continue.
  751. //$paiement->ext_payment_id = $TRANSACTIONID.':'.$customer->id.'@'.$stripearrayofkeysbyenv[$servicestatus]['publishable_key']; // TODO LDR It would be better if we could store this. Do we have customer->id and publishable_key ?
  752. $paiement->ext_payment_site = $service;
  753. if (!$error) {
  754. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  755. if ($paiement_id < 0) {
  756. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  757. $ispostactionok = -1;
  758. $error++;
  759. } else {
  760. $postactionmessages[] = 'Payment created';
  761. $ispostactionok = 1;
  762. }
  763. }
  764. if (!$error && isModEnabled("banque")) {
  765. $bankaccountid = 0;
  766. if ($paymentmethod == 'paybox') {
  767. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  768. } elseif ($paymentmethod == 'paypal') {
  769. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  770. } elseif ($paymentmethod == 'stripe') {
  771. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  772. }
  773. if ($bankaccountid > 0) {
  774. $label = '(CustomerInvoicePayment)';
  775. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  776. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  777. }
  778. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  779. if ($result < 0) {
  780. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  781. $ispostactionok = -1;
  782. $error++;
  783. } else {
  784. $postactionmessages[] = 'Bank transaction of payment created';
  785. $ispostactionok = 1;
  786. }
  787. } else {
  788. $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.';
  789. $ispostactionok = -1;
  790. $error++;
  791. }
  792. }
  793. if (!$error) {
  794. $db->commit();
  795. } else {
  796. $db->rollback();
  797. }
  798. } else {
  799. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['INV'].'. May be payment was already recorded.';
  800. $ispostactionok = -1;
  801. }
  802. } else {
  803. $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
  804. $ispostactionok = -1;
  805. }
  806. } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
  807. include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
  808. $object = new Commande($db);
  809. $result = $object->fetch((int) $tmptag['ORD']);
  810. if ($result) {
  811. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  812. $paymentTypeId = 0;
  813. if ($paymentmethod == 'paybox') {
  814. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  815. }
  816. if ($paymentmethod == 'paypal') {
  817. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  818. }
  819. if ($paymentmethod == 'stripe') {
  820. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  821. }
  822. if (empty($paymentTypeId)) {
  823. dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
  824. if (empty($paymentType)) {
  825. $paymentType = 'CB';
  826. }
  827. // May return nothing when paymentType means nothing
  828. // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
  829. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  830. // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
  831. if (empty($paymentTypeId) || $paymentTypeId < 0) {
  832. $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
  833. }
  834. }
  835. // 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)
  836. if (isModEnabled('facture')) {
  837. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  838. include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  839. $invoice = new Facture($db);
  840. $result = $invoice->createFromOrder($object, $user);
  841. if ($result > 0) {
  842. $object->classifyBilled($user);
  843. $invoice->validate($user);
  844. // Creation of payment line
  845. include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  846. $paiement = new Paiement($db);
  847. $paiement->datepaye = $now;
  848. if ($currencyCodeType == $conf->currency) {
  849. $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  850. } else {
  851. $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
  852. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  853. $ispostactionok = -1;
  854. $error++;
  855. }
  856. $paiement->paiementid = $paymentTypeId;
  857. $paiement->num_payment = '';
  858. $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
  859. $paiement->ext_payment_id = $TRANSACTIONID; // pi_... for Stripe, ...
  860. $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
  861. if (!$error) {
  862. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  863. if ($paiement_id < 0) {
  864. $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
  865. $ispostactionok = -1;
  866. $error++;
  867. } else {
  868. $postactionmessages[] = 'Payment created';
  869. $ispostactionok = 1;
  870. }
  871. }
  872. if (!$error && isModEnabled("banque")) {
  873. $bankaccountid = 0;
  874. if ($paymentmethod == 'paybox') {
  875. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  876. } elseif ($paymentmethod == 'paypal') {
  877. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  878. } elseif ($paymentmethod == 'stripe') {
  879. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  880. }
  881. if ($bankaccountid > 0) {
  882. $label = '(CustomerInvoicePayment)';
  883. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  884. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  885. }
  886. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  887. if ($result < 0) {
  888. $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
  889. $ispostactionok = -1;
  890. $error++;
  891. } else {
  892. $postactionmessages[] = 'Bank transaction of payment created';
  893. $ispostactionok = 1;
  894. }
  895. } else {
  896. $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
  897. $ispostactionok = -1;
  898. $error++;
  899. }
  900. }
  901. if (!$error) {
  902. $db->commit();
  903. } else {
  904. $db->rollback();
  905. }
  906. } else {
  907. $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
  908. $ispostactionok = -1;
  909. }
  910. } else {
  911. $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type id" (' . $paymentTypeId . ') to record the payment of order ' . $tmptag['ORD'] . '. May be payment was already recorded.';
  912. $ispostactionok = -1;
  913. }
  914. } else {
  915. $postactionmessages[] = 'Invoice module is not enable';
  916. $ispostactionok = -1;
  917. }
  918. } else {
  919. $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
  920. $ispostactionok = -1;
  921. }
  922. } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
  923. include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
  924. $don = new Don($db);
  925. $result = $don->fetch((int) $tmptag['DON']);
  926. if ($result) {
  927. $paymentTypeId = 0;
  928. if ($paymentmethod == 'paybox') {
  929. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  930. }
  931. if ($paymentmethod == 'paypal') {
  932. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  933. }
  934. if ($paymentmethod == 'stripe') {
  935. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  936. }
  937. if (empty($paymentTypeId)) {
  938. dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
  939. if (empty($paymentType)) {
  940. $paymentType = 'CB';
  941. }
  942. // May return nothing when paymentType means nothing
  943. // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
  944. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  945. // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
  946. if (empty($paymentTypeId) || $paymentTypeId < 0) {
  947. $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
  948. }
  949. }
  950. // 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)
  951. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  952. $db->begin();
  953. // Creation of paiement line for donation
  954. include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
  955. $paiement = new PaymentDonation($db);
  956. $totalpaid = $FinalPaymentAmt;
  957. if ($currencyCodeType == $conf->currency) {
  958. $paiement->amounts = array($object->id => $totalpaid); // Array with all payments dispatching with donation
  959. } else {
  960. // PaymentDonation does not support multi currency
  961. $postactionmessages[] = 'Payment donation can\'t be payed with diffent currency than '.$conf->currency;
  962. $ispostactionok = -1;
  963. $error++; // Not yet supported
  964. }
  965. $paiement->fk_donation = $don->id;
  966. $paiement->datep = $now;
  967. $paiement->paymenttype = $paymentTypeId;
  968. $paiement->num_payment = '';
  969. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
  970. $paiement->ext_payment_id = $TRANSACTIONID;
  971. $paiement->ext_payment_site = $service;
  972. if (!$error) {
  973. $paiement_id = $paiement->create($user, 1);
  974. if ($paiement_id < 0) {
  975. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  976. $ispostactionok = -1;
  977. $error++;
  978. } else {
  979. $postactionmessages[] = 'Payment created';
  980. $ispostactionok = 1;
  981. if ($totalpaid >= $don->getRemainToPay()) {
  982. $don->setPaid($don->id);
  983. }
  984. }
  985. }
  986. if (!$error && isModEnabled("banque")) {
  987. $bankaccountid = 0;
  988. if ($paymentmethod == 'paybox') {
  989. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  990. } elseif ($paymentmethod == 'paypal') {
  991. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  992. } elseif ($paymentmethod == 'stripe') {
  993. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  994. }
  995. if ($bankaccountid > 0) {
  996. $label = '(DonationPayment)';
  997. $result = $paiement->addPaymentToBank($user, 'payment_donation', $label, $bankaccountid, '', '');
  998. if ($result < 0) {
  999. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1000. $ispostactionok = -1;
  1001. $error++;
  1002. } else {
  1003. $postactionmessages[] = 'Bank transaction of payment created';
  1004. $ispostactionok = 1;
  1005. }
  1006. } else {
  1007. $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.';
  1008. $ispostactionok = -1;
  1009. $error++;
  1010. }
  1011. }
  1012. if (!$error) {
  1013. $db->commit();
  1014. } else {
  1015. $db->rollback();
  1016. }
  1017. } else {
  1018. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of donation '.$tmptag['DON'].'. May be payment was already recorded.';
  1019. $ispostactionok = -1;
  1020. }
  1021. } else {
  1022. $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
  1023. $ispostactionok = -1;
  1024. }
  1025. // TODO send email with acknowledgment for the donation
  1026. // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
  1027. } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
  1028. // Record payment for registration to an event for an attendee
  1029. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
  1030. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
  1031. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1032. $object = new Facture($db);
  1033. $result = $object->fetch($ref);
  1034. if ($result) {
  1035. $paymentTypeId = 0;
  1036. if ($paymentmethod == 'paybox') {
  1037. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  1038. }
  1039. if ($paymentmethod == 'paypal') {
  1040. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  1041. }
  1042. if ($paymentmethod == 'stripe') {
  1043. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  1044. }
  1045. if (empty($paymentTypeId)) {
  1046. dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
  1047. if (empty($paymentType)) {
  1048. $paymentType = 'CB';
  1049. }
  1050. // May return nothing when paymentType means nothing
  1051. // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
  1052. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  1053. // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
  1054. if (empty($paymentTypeId) || $paymentTypeId < 0) {
  1055. $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
  1056. }
  1057. }
  1058. // 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)
  1059. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  1060. $resultvalidate = $object->validate($user);
  1061. if ($resultvalidate < 0) {
  1062. $postactionmessages[] = 'Cannot validate invoice';
  1063. $ispostactionok = -1;
  1064. $error++; // Not yet supported
  1065. } else {
  1066. $db->begin();
  1067. // Creation of payment line
  1068. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  1069. $paiement = new Paiement($db);
  1070. $paiement->datepaye = $now;
  1071. if ($currencyCodeType == $conf->currency) {
  1072. $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  1073. } else {
  1074. $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
  1075. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  1076. $ispostactionok = -1;
  1077. $error++; // Not yet supported
  1078. }
  1079. $paiement->paiementid = $paymentTypeId;
  1080. $paiement->num_payment = '';
  1081. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
  1082. $paiement->ext_payment_id = $TRANSACTIONID;
  1083. $paiement->ext_payment_site = $service;
  1084. if (!$error) {
  1085. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  1086. if ($paiement_id < 0) {
  1087. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1088. $ispostactionok = -1;
  1089. $error++;
  1090. } else {
  1091. $postactionmessages[] = 'Payment created';
  1092. $ispostactionok = 1;
  1093. }
  1094. }
  1095. if (!$error && isModEnabled("banque")) {
  1096. $bankaccountid = 0;
  1097. if ($paymentmethod == 'paybox') {
  1098. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  1099. } elseif ($paymentmethod == 'paypal') {
  1100. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  1101. } elseif ($paymentmethod == 'stripe') {
  1102. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  1103. }
  1104. if ($bankaccountid > 0) {
  1105. $label = '(CustomerInvoicePayment)';
  1106. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  1107. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  1108. }
  1109. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  1110. if ($result < 0) {
  1111. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1112. $ispostactionok = -1;
  1113. $error++;
  1114. } else {
  1115. $postactionmessages[] = 'Bank transaction of payment created';
  1116. $ispostactionok = 1;
  1117. }
  1118. } else {
  1119. $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.';
  1120. $ispostactionok = -1;
  1121. $error++;
  1122. }
  1123. }
  1124. if (!$error) {
  1125. // Validating the attendee
  1126. $attendeetovalidate = new ConferenceOrBoothAttendee($db);
  1127. $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
  1128. if ($resultattendee < 0) {
  1129. $error++;
  1130. setEventMessages(null, $attendeetovalidate->errors, "errors");
  1131. } else {
  1132. $attendeetovalidate->validate($user);
  1133. $attendeetovalidate->amount = $FinalPaymentAmt;
  1134. $attendeetovalidate->date_subscription = dol_now();
  1135. $attendeetovalidate->update($user);
  1136. }
  1137. }
  1138. if (!$error) {
  1139. $db->commit();
  1140. } else {
  1141. setEventMessages(null, $postactionmessages, 'warnings');
  1142. $db->rollback();
  1143. }
  1144. if (! $error) {
  1145. // Sending mail
  1146. $thirdparty = new Societe($db);
  1147. $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
  1148. if ($resultthirdparty < 0) {
  1149. setEventMessages($resultthirdparty->error, $resultthirdparty->errors, "errors");
  1150. } else {
  1151. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1152. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1153. $formmail = new FormMail($db);
  1154. // Set output language
  1155. $outputlangs = new Translate('', $conf);
  1156. $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
  1157. // Load traductions files required by page
  1158. $outputlangs->loadLangs(array("main", "members", "eventorganization"));
  1159. // Get email content from template
  1160. $arraydefaultmessage = null;
  1161. $idoftemplatetouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT; // Email to send for Event organization registration
  1162. if (!empty($idoftemplatetouse)) {
  1163. $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
  1164. }
  1165. if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  1166. $subject = $arraydefaultmessage->topic;
  1167. $msg = $arraydefaultmessage->content;
  1168. } else {
  1169. $subject = '['.$appli.'] '.$object->ref.' - '.$outputlangs->trans("NewRegistration");
  1170. $msg = $outputlangs->trans("OrganizationEventPaymentOfRegistrationWasReceived");
  1171. }
  1172. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
  1173. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  1174. $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
  1175. $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
  1176. $sendto = $attendeetovalidate->email;
  1177. $cc = '';
  1178. if ($thirdparty->email) {
  1179. $cc = $thirdparty->email;
  1180. }
  1181. if ($attendeetovalidate->email_company && $attendeetovalidate->email_company != $thirdparty->email) {
  1182. $cc = ($cc ? ', ' : '').$attendeetovalidate->email_company;
  1183. }
  1184. $from = getDolGlobalString('MAILING_EMAIL_FROM') ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
  1185. $urlback = $_SERVER["REQUEST_URI"];
  1186. $ishtml = dol_textishtml($texttosend); // May contain urls
  1187. // Attach a file ?
  1188. $file = '';
  1189. $listofpaths = array();
  1190. $listofnames = array();
  1191. $listofmimes = array();
  1192. if (is_object($object)) {
  1193. $invoicediroutput = $conf->facture->dir_output;
  1194. $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->ref, preg_quote($object->ref, '/').'[^\-]+');
  1195. $file = $fileparams['fullname'];
  1196. $listofpaths = array($file);
  1197. $listofnames = array(basename($file));
  1198. $listofmimes = array(dol_mimetype($file));
  1199. }
  1200. $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, $cc, '', 0, $ishtml);
  1201. $result = $mailfile->sendfile();
  1202. if ($result) {
  1203. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1204. } else {
  1205. dol_syslog("Failed to send EMail to ".$sendto.' - '.$mailfile->error, LOG_ERR, 0, '_payment');
  1206. }
  1207. }
  1208. }
  1209. }
  1210. } else {
  1211. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
  1212. $ispostactionok = -1;
  1213. }
  1214. } else {
  1215. $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
  1216. $ispostactionok = -1;
  1217. }
  1218. } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
  1219. // Record payment for booth or conference
  1220. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
  1221. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
  1222. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1223. $object = new Facture($db);
  1224. $result = $object->fetch($ref);
  1225. if ($result) {
  1226. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  1227. $paymentTypeId = 0;
  1228. if ($paymentmethod == 'paybox') {
  1229. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  1230. }
  1231. if ($paymentmethod == 'paypal') {
  1232. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  1233. }
  1234. if ($paymentmethod == 'stripe') {
  1235. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  1236. }
  1237. if (empty($paymentTypeId)) {
  1238. dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
  1239. if (empty($paymentType)) {
  1240. $paymentType = 'CB';
  1241. }
  1242. // May return nothing when paymentType means nothing
  1243. // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
  1244. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  1245. // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
  1246. if (empty($paymentTypeId) || $paymentTypeId < 0) {
  1247. $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
  1248. }
  1249. }
  1250. // 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)
  1251. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  1252. $resultvalidate = $object->validate($user);
  1253. if ($resultvalidate < 0) {
  1254. $postactionmessages[] = 'Cannot validate invoice';
  1255. $ispostactionok = -1;
  1256. $error++; // Not yet supported
  1257. } else {
  1258. $db->begin();
  1259. // Creation of payment line
  1260. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  1261. $paiement = new Paiement($db);
  1262. $paiement->datepaye = $now;
  1263. if ($currencyCodeType == $conf->currency) {
  1264. $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  1265. } else {
  1266. $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
  1267. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  1268. $ispostactionok = -1;
  1269. $error++; // Not yet supported
  1270. }
  1271. $paiement->paiementid = $paymentTypeId;
  1272. $paiement->num_payment = '';
  1273. $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
  1274. $paiement->ext_payment_id = $TRANSACTIONID;
  1275. $paiement->ext_payment_site = $service;
  1276. if (!$error) {
  1277. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  1278. if ($paiement_id < 0) {
  1279. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1280. $ispostactionok = -1;
  1281. $error++;
  1282. } else {
  1283. $postactionmessages[] = 'Payment created';
  1284. $ispostactionok = 1;
  1285. }
  1286. }
  1287. if (!$error && isModEnabled("banque")) {
  1288. $bankaccountid = 0;
  1289. if ($paymentmethod == 'paybox') {
  1290. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  1291. } elseif ($paymentmethod == 'paypal') {
  1292. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  1293. } elseif ($paymentmethod == 'stripe') {
  1294. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  1295. }
  1296. if ($bankaccountid > 0) {
  1297. $label = '(CustomerInvoicePayment)';
  1298. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  1299. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  1300. }
  1301. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  1302. if ($result < 0) {
  1303. $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
  1304. $ispostactionok = -1;
  1305. $error++;
  1306. } else {
  1307. $postactionmessages[] = 'Bank transaction of payment created';
  1308. $ispostactionok = 1;
  1309. }
  1310. } else {
  1311. $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.';
  1312. $ispostactionok = -1;
  1313. $error++;
  1314. }
  1315. }
  1316. if (!$error) {
  1317. // Putting the booth to "suggested" state
  1318. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
  1319. require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
  1320. $booth = new ConferenceOrBooth($db);
  1321. $resultbooth = $booth->fetch((int) $tmptag['BOO']);
  1322. if ($resultbooth < 0) {
  1323. $error++;
  1324. setEventMessages(null, $booth->errors, "errors");
  1325. } else {
  1326. $booth->status = ConferenceOrBooth::STATUS_SUGGESTED;
  1327. $resultboothupdate = $booth->update($user);
  1328. if ($resultboothupdate<0) {
  1329. // Finding the thirdparty by getting the invoice
  1330. $invoice = new Facture($db);
  1331. $resultinvoice = $invoice->fetch($ref);
  1332. if ($resultinvoice<0) {
  1333. $postactionmessages[] = 'Could not find the associated invoice.';
  1334. $ispostactionok = -1;
  1335. $error++;
  1336. } else {
  1337. $thirdparty = new Societe($db);
  1338. $resultthirdparty = $thirdparty->fetch($invoice->socid);
  1339. if ($resultthirdparty<0) {
  1340. $error++;
  1341. setEventMessages(null, $thirdparty->errors, "errors");
  1342. } else {
  1343. // Sending mail
  1344. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1345. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1346. $formmail = new FormMail($db);
  1347. // Set output language
  1348. $outputlangs = new Translate('', $conf);
  1349. $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
  1350. // Load traductions files required by page
  1351. $outputlangs->loadLangs(array("main", "members", "eventorganization"));
  1352. // Get email content from template
  1353. $arraydefaultmessage = null;
  1354. $idoftemplatetouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH; // Email sent after registration for a Booth
  1355. if (!empty($idoftemplatetouse)) {
  1356. $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
  1357. }
  1358. if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  1359. $subject = $arraydefaultmessage->topic;
  1360. $msg = $arraydefaultmessage->content;
  1361. } else {
  1362. $subject = '['.$appli.'] '.$booth->ref.' - '.$outputlangs->trans("NewRegistration").']';
  1363. $msg = $outputlangs->trans("OrganizationEventPaymentOfBoothWasReceived");
  1364. }
  1365. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
  1366. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  1367. $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
  1368. $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
  1369. $sendto = $thirdparty->email;
  1370. $from = $conf->global->MAILING_EMAIL_FROM;
  1371. $urlback = $_SERVER["REQUEST_URI"];
  1372. $ishtml = dol_textishtml($texttosend); // May contain urls
  1373. $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml);
  1374. $result = $mailfile->sendfile();
  1375. if ($result) {
  1376. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1377. } else {
  1378. dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
  1379. }
  1380. }
  1381. }
  1382. }
  1383. }
  1384. }
  1385. if (!$error) {
  1386. $db->commit();
  1387. } else {
  1388. $db->rollback();
  1389. }
  1390. }
  1391. } else {
  1392. $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
  1393. $ispostactionok = -1;
  1394. }
  1395. } else {
  1396. $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
  1397. $ispostactionok = -1;
  1398. }
  1399. } elseif (array_key_exists('CON', $tmptag) && $tmptag['CON'] > 0) {
  1400. include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
  1401. $object = new Contrat($db);
  1402. $result = $object->fetch((int) $tmptag['CON']);
  1403. if ($result) {
  1404. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  1405. $paymentTypeId = 0;
  1406. if ($paymentmethod == 'paybox') {
  1407. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  1408. }
  1409. if ($paymentmethod == 'paypal') {
  1410. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  1411. }
  1412. if ($paymentmethod == 'stripe') {
  1413. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  1414. }
  1415. if (empty($paymentTypeId)) {
  1416. dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
  1417. if (empty($paymentType)) {
  1418. $paymentType = 'CB';
  1419. }
  1420. // May return nothing when paymentType means nothing
  1421. // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
  1422. $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
  1423. // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
  1424. if (empty($paymentTypeId) || $paymentTypeId < 0) {
  1425. $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
  1426. }
  1427. }
  1428. $currencyCodeType = $_SESSION['currencyCodeType'];
  1429. $contract_lines = (array_key_exists('COL', $tmptag) && $tmptag['COL'] > 0) ? $tmptag['COL'] : null;
  1430. // 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)
  1431. if (isModEnabled('facture')) {
  1432. if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
  1433. include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  1434. $invoice = new Facture($db);
  1435. $result = $invoice->createFromContract($object, $user, array((int) $contract_lines));
  1436. if ($result > 0) {
  1437. // $object->classifyBilled($user);
  1438. $invoice->validate($user);
  1439. // Creation of payment line
  1440. include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  1441. $paiement = new Paiement($db);
  1442. $paiement->datepaye = $now;
  1443. if ($currencyCodeType == $conf->currency) {
  1444. $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
  1445. } else {
  1446. $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
  1447. $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
  1448. $ispostactionok = -1;
  1449. $error++;
  1450. }
  1451. $paiement->paiementid = $paymentTypeId;
  1452. $paiement->num_payment = '';
  1453. $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
  1454. $paiement->ext_payment_id = $TRANSACTIONID; // pi_... for Stripe, ...
  1455. $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
  1456. if (!$error) {
  1457. $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
  1458. if ($paiement_id < 0) {
  1459. $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
  1460. $ispostactionok = -1;
  1461. $error++;
  1462. } else {
  1463. $postactionmessages[] = 'Payment created';
  1464. $ispostactionok = 1;
  1465. }
  1466. }
  1467. if (!$error && isModEnabled("banque")) {
  1468. $bankaccountid = 0;
  1469. if ($paymentmethod == 'paybox') {
  1470. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  1471. } elseif ($paymentmethod == 'paypal') {
  1472. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  1473. } elseif ($paymentmethod == 'stripe') {
  1474. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  1475. }
  1476. if ($bankaccountid > 0) {
  1477. $label = '(CustomerInvoicePayment)';
  1478. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  1479. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  1480. }
  1481. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
  1482. if ($result < 0) {
  1483. $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
  1484. $ispostactionok = -1;
  1485. $error++;
  1486. } else {
  1487. $postactionmessages[] = 'Bank transaction of payment created';
  1488. $ispostactionok = 1;
  1489. }
  1490. } else {
  1491. $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
  1492. $ispostactionok = -1;
  1493. $error++;
  1494. }
  1495. }
  1496. if (!$error) {
  1497. $db->commit();
  1498. } else {
  1499. $db->rollback();
  1500. }
  1501. } else {
  1502. $msg = 'Failed to create invoice form contract ' . $tmptag['CON'];
  1503. if (!empty($cols)) {
  1504. $msg .= ' and col '. $cols .'.';
  1505. }
  1506. $postactionmessages[] = $msg;
  1507. $ispostactionok = -1;
  1508. }
  1509. } else {
  1510. $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type id" (' . $paymentTypeId . ') to record the payment of contract ' . $tmptag['CON'] .'. Maybe payment was already recorded.';
  1511. $ispostactionok = -1;
  1512. }
  1513. } else {
  1514. $postactionmessages[] = 'Invoice module is not enable';
  1515. $ispostactionok = -1;
  1516. }
  1517. } else {
  1518. $msg = 'Contract paid ' . $tmptag['CON'] . ' was not found';
  1519. if (!empty($cols)) {
  1520. $msg .= ' for col '.$tmptag['COL'] .'.';
  1521. }
  1522. $postactionmessages[] = $msg;
  1523. $ispostactionok = -1;
  1524. }
  1525. } else {
  1526. // Nothing done
  1527. }
  1528. }
  1529. if ($ispaymentok) {
  1530. // Get on url call
  1531. $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
  1532. $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
  1533. // Set by newpayment.php
  1534. $currencyCodeType = $_SESSION['currencyCodeType'];
  1535. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  1536. $paymentType = $_SESSION['PaymentType']; // Seems used by paypal only
  1537. if (is_object($object) && method_exists($object, 'call_trigger')) {
  1538. // Call trigger
  1539. $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
  1540. if ($result < 0) {
  1541. $error++;
  1542. }
  1543. // End call triggers
  1544. } elseif (get_class($object) == 'stdClass') {
  1545. //In some case $object is not instanciate (for paiement on custom object) We need to deal with payment
  1546. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  1547. $paiement = new Paiement($db);
  1548. $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
  1549. if ($result < 0) {
  1550. $error++;
  1551. }
  1552. }
  1553. print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
  1554. if ($TRANSACTIONID) {
  1555. print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n";
  1556. }
  1557. $key = 'ONLINE_PAYMENT_MESSAGE_OK';
  1558. if (!empty($conf->global->$key)) {
  1559. print '<br>';
  1560. print $conf->global->$key;
  1561. }
  1562. $sendemail = '';
  1563. if (getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL')) {
  1564. $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL;
  1565. }
  1566. $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
  1567. dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
  1568. // Send an email to the admins
  1569. if ($sendemail) {
  1570. $companylangs = new Translate('', $conf);
  1571. $companylangs->setDefaultLang($mysoc->default_lang);
  1572. $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
  1573. $sendto = $sendemail;
  1574. $from = getDolGlobalString('MAILING_EMAIL_FROM') ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
  1575. // Define $urlwithroot
  1576. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1577. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1578. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1579. // Define link to login card
  1580. $urlback = $_SERVER["REQUEST_URI"];
  1581. $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
  1582. $content = "";
  1583. if (array_key_exists('MEM', $tmptag)) {
  1584. $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
  1585. $content .= '<strong>'.$companylangs->trans("PaymentSubscription")."</strong><br><br>\n";
  1586. $content .= $companylangs->trans("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
  1587. $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
  1588. } elseif (array_key_exists('INV', $tmptag)) {
  1589. $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
  1590. $content .= '<strong>'.$companylangs->trans("Payment")."</strong><br><br>\n";
  1591. $content .= $companylangs->trans("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
  1592. //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
  1593. $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
  1594. } else {
  1595. $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
  1596. }
  1597. $content .= $companylangs->transnoentities("PostActionAfterPayment").' : ';
  1598. if ($ispostactionok > 0) {
  1599. //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
  1600. $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
  1601. } elseif ($ispostactionok == 0) {
  1602. $content .= $companylangs->transnoentitiesnoconv("None");
  1603. } else {
  1604. $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
  1605. $content .= '<span class="star">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
  1606. }
  1607. $content .= '<br>'."\n";
  1608. foreach ($postactionmessages as $postactionmessage) {
  1609. $content .= ' * '.$postactionmessage.'<br>'."\n";
  1610. }
  1611. if ($ispostactionok < 0) {
  1612. $content .= $langs->transnoentities("ARollbackWasPerformedOnPostActions");
  1613. }
  1614. $content .= '<br>'."\n";
  1615. $content .= "<br>\n";
  1616. $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
  1617. $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
  1618. $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
  1619. $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
  1620. $content .= "<br>\n";
  1621. $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
  1622. if (!empty($ErrorCode)) {
  1623. $content .= "ErrorCode = ".$ErrorCode."<br>\n";
  1624. }
  1625. if (!empty($ErrorShortMsg)) {
  1626. $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
  1627. }
  1628. if (!empty($ErrorLongMsg)) {
  1629. $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
  1630. }
  1631. if (!empty($ErrorSeverityCode)) {
  1632. $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
  1633. }
  1634. $ishtml = dol_textishtml($content); // May contain urls
  1635. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1636. $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
  1637. $result = $mailfile->sendfile();
  1638. if ($result) {
  1639. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1640. //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
  1641. } else {
  1642. dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
  1643. //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
  1644. }
  1645. }
  1646. } else {
  1647. // Get on url call
  1648. $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
  1649. $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
  1650. // Set by newpayment.php
  1651. $paymentType = $_SESSION['PaymentType'];
  1652. $currencyCodeType = $_SESSION['currencyCodeType'];
  1653. $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
  1654. if (is_object($object) && method_exists($object, 'call_trigger')) {
  1655. // Call trigger
  1656. $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
  1657. if ($result < 0) {
  1658. $error++;
  1659. }
  1660. // End call triggers
  1661. }
  1662. print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
  1663. print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
  1664. print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
  1665. print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
  1666. print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
  1667. if ($mysoc->email) {
  1668. print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
  1669. }
  1670. $sendemail = '';
  1671. if (getDolGlobalString('PAYMENTONLINE_SENDEMAIL')) {
  1672. $sendemail = $conf->global->PAYMENTONLINE_SENDEMAIL;
  1673. }
  1674. // TODO Remove local option to keep only the generic one ?
  1675. if ($paymentmethod == 'paypal' && getDolGlobalString('PAYPAL_PAYONLINE_SENDEMAIL')) {
  1676. $sendemail = $conf->global->PAYPAL_PAYONLINE_SENDEMAIL;
  1677. } elseif ($paymentmethod == 'paybox' && getDolGlobalString('PAYBOX_PAYONLINE_SENDEMAIL')) {
  1678. $sendemail = $conf->global->PAYBOX_PAYONLINE_SENDEMAIL;
  1679. } elseif ($paymentmethod == 'stripe' && getDolGlobalString('STRIPE_PAYONLINE_SENDEMAIL')) {
  1680. $sendemail = $conf->global->STRIPE_PAYONLINE_SENDEMAIL;
  1681. }
  1682. // Send warning of error to administrator
  1683. if ($sendemail) {
  1684. $companylangs = new Translate('', $conf);
  1685. $companylangs->setDefaultLang($mysoc->default_lang);
  1686. $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
  1687. $sendto = $sendemail;
  1688. $from = getDolGlobalString('MAILING_EMAIL_FROM') ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
  1689. // Define $urlwithroot
  1690. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1691. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1692. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1693. $urlback = $_SERVER["REQUEST_URI"];
  1694. $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
  1695. $content = "";
  1696. $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
  1697. $content .= "<br><br>\n";
  1698. $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
  1699. $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
  1700. $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
  1701. $content .= "<br>\n";
  1702. $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
  1703. $ishtml = dol_textishtml($content); // May contain urls
  1704. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1705. $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
  1706. $result = $mailfile->sendfile();
  1707. if ($result) {
  1708. dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
  1709. } else {
  1710. dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
  1711. }
  1712. }
  1713. }
  1714. print "\n</div>\n";
  1715. print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag($paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
  1716. htmlPrintOnlineFooter($mysoc, $langs, 0, $suffix);
  1717. // Clean session variables to avoid duplicate actions if post is resent
  1718. unset($_SESSION["FinalPaymentAmt"]);
  1719. unset($_SESSION["TRANSACTIONID"]);
  1720. llxFooter('', 'public');
  1721. $db->close();