dolibarr 20.0.0
paymentok.php
Go to the documentation of this file.
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
32if (!defined('NOLOGIN')) {
33 define("NOLOGIN", 1); // This means this output page does not require to be logged.
34}
35if (!defined('NOCSRFCHECK')) {
36 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
37}
38if (!defined('NOIPCHECK')) {
39 define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
40}
41if (!defined('NOBROWSERNOTIF')) {
42 define('NOBROWSERNOTIF', '1');
43}
44
45// For MultiCompany module.
46// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
47// Because 2 entities can have the same ref.
48$entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1));
49if (is_numeric($entity)) {
50 define("DOLENTITY", $entity);
51}
52
53// Load Dolibarr environment
54require '../../main.inc.php';
55require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
56require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
57if (isModEnabled('paypal')) {
58 require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
59 require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php';
60}
61
62// Hook to be used by external payment modules (ie Payzen, ...)
63$hookmanager = new HookManager($db);
64
65$hookmanager->initHooks(array('newpayment'));
66
67$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal", "stripe"));
68
69// Clean parameters
70if (isModEnabled('paypal')) {
71 $PAYPAL_API_USER = "";
72 if (getDolGlobalString('PAYPAL_API_USER')) {
73 $PAYPAL_API_USER = getDolGlobalString('PAYPAL_API_USER');
74 }
75 $PAYPAL_API_PASSWORD = "";
76 if (getDolGlobalString('PAYPAL_API_PASSWORD')) {
77 $PAYPAL_API_PASSWORD = getDolGlobalString('PAYPAL_API_PASSWORD');
78 }
79 $PAYPAL_API_SIGNATURE = "";
80 if (getDolGlobalString('PAYPAL_API_SIGNATURE')) {
81 $PAYPAL_API_SIGNATURE = getDolGlobalString('PAYPAL_API_SIGNATURE');
82 }
83 $PAYPAL_API_SANDBOX = "";
84 if (getDolGlobalString('PAYPAL_API_SANDBOX')) {
85 $PAYPAL_API_SANDBOX = getDolGlobalString('PAYPAL_API_SANDBOX');
86 }
87 /*$PAYPAL_API_OK = "";
88 if ($urlok) {
89 $PAYPAL_API_OK = $urlok;
90 }
91 $PAYPAL_API_KO = "";
92 if ($urlko) {
93 $PAYPAL_API_KO = $urlko;
94 }*/
95
96 $PAYPALTOKEN = GETPOST('TOKEN');
97 if (empty($PAYPALTOKEN)) {
98 $PAYPALTOKEN = GETPOST('token');
99 }
100 $PAYPALPAYERID = GETPOST('PAYERID');
101 if (empty($PAYPALPAYERID)) {
102 $PAYPALPAYERID = GETPOST('PayerID');
103 }
104}
105
106$FULLTAG = GETPOST('FULLTAG');
107if (empty($FULLTAG)) {
108 $FULLTAG = GETPOST('fulltag');
109}
110$source = GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha');
111$ref = GETPOST('ref');
112
113$suffix = GETPOST("suffix", 'aZ09');
114$membertypeid = GETPOSTINT("membertypeid");
115
116
117// Detect $paymentmethod
118$paymentmethod = '';
119$reg = array();
120if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) {
121 $paymentmethod = $reg[1];
122}
123if (empty($paymentmethod)) {
124 dol_syslog("***** paymentok.php was called with a non valid parameter FULLTAG=".$FULLTAG, LOG_DEBUG, 0, '_payment');
125 dol_print_error(null, 'The callback url does not contain a parameter fulltag that should help us to find the payment method used');
126 exit;
127}
128
129dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLTAG=".$FULLTAG." REQUEST_URI=".$_SERVER["REQUEST_URI"], LOG_DEBUG, 0, '_payment');
130
131// Detect $ws
132$ws = preg_match('/WS=([^\.]+)/', $FULLTAG, $reg_ws) ? $reg_ws[1] : 0;
133if ($ws) {
134 dol_syslog("Paymentok.php page is invoked from a website with ref ".$ws.". It performs actions and then redirects back to this website. A page with ref paymentok must be created for this website.", LOG_DEBUG, 0, '_payment');
135}
136
137$validpaymentmethod = getValidOnlinePaymentMethods($paymentmethod);
138
139// Security check
140if (empty($validpaymentmethod)) {
141 httponly_accessforbidden('No valid payment mode');
142}
143
144// Common variables
145$creditor = $mysoc->name;
146$paramcreditor = 'ONLINE_PAYMENT_CREDITOR';
147$paramcreditorlong = 'ONLINE_PAYMENT_CREDITOR_'.$suffix;
148if (getDolGlobalString($paramcreditorlong)) {
149 $creditor = getDolGlobalString($paramcreditorlong); // use label long of the seller to show
150} elseif (getDolGlobalString($paramcreditor)) {
151 $creditor = getDolGlobalString($paramcreditor); // use label short of the seller to show
152}
153
154
155$ispaymentok = false;
156// If payment is ok
157$PAYMENTSTATUS = $TRANSACTIONID = $TAXAMT = $NOTE = '';
158// If payment is ko
159$ErrorCode = $ErrorShortMsg = $ErrorLongMsg = $ErrorSeverityCode = '';
160
161
162$object = new stdClass(); // For triggers
163
164$error = 0;
165
166
167/*
168 * Actions and view
169 */
170
171// Check if we have redirtodomain to do.
172if ($ws) {
173 $doactionsthenredirect = 1;
174}
175
176
177$now = dol_now();
178
179dol_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');
180dol_syslog("_SERVER[SERVER_NAME] = ".(empty($_SERVER["SERVER_NAME"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_NAME"])), LOG_DEBUG, 0, '_payment');
181dol_syslog("_SERVER[SERVER_ADDR] = ".(empty($_SERVER["SERVER_ADDR"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_ADDR"])), LOG_DEBUG, 0, '_payment');
182
183$tracepost = "";
184foreach ($_POST as $k => $v) {
185 if (is_scalar($k) && is_scalar($v)) {
186 $tracepost .= "$k - $v\n";
187 }
188}
189dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment');
190$tracesession = "";
191foreach ($_SESSION as $k => $v) {
192 if (is_scalar($k) && is_scalar($v)) {
193 $tracesession .= "$k - $v\n";
194 }
195}
196dol_syslog("SESSION=".$tracesession, LOG_DEBUG, 0, '_payment');
197
198$head = '';
199if (getDolGlobalString('ONLINE_PAYMENT_CSS_URL')) {
200 $head = '<link rel="stylesheet" type="text/css" href="' . getDolGlobalString('ONLINE_PAYMENT_CSS_URL').'?lang='.$langs->defaultlang.'">'."\n";
201}
202
203$conf->dol_hide_topmenu = 1;
204$conf->dol_hide_leftmenu = 1;
205
206
207// Show header
208if (empty($doactionsthenredirect)) {
209 $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
210 llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);
211
212
213 // Show page content id="dolpaymentdiv"
214 print '<span id="dolpaymentspan"></span>'."\n";
215 print '<div id="dolpaymentdiv" class="center">'."\n";
216
217
218 // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo)
219 // Define logo and logosmall
220 $logosmall = $mysoc->logo_small;
221 $logo = $mysoc->logo;
222 $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix;
223 if (!empty($conf->global->$paramlogo)) {
224 $logosmall = getDolGlobalString($paramlogo);
225 } elseif (getDolGlobalString('ONLINE_PAYMENT_LOGO')) {
226 $logosmall = getDolGlobalString('ONLINE_PAYMENT_LOGO');
227 }
228 //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
229 // Define urllogo
230 $urllogo = '';
231 $urllogofull = '';
232 if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
233 $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
234 $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
235 } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
236 $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
237 $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
238 }
239
240 // Output html code for logo
241 if ($urllogo) {
242 print '<div class="backgreypublicpayment">';
243 print '<div class="logopublicpayment">';
244 print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
245 print '>';
246 print '</div>';
247 if (!getDolGlobalString('MAIN_HIDE_POWERED_BY')) {
248 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>';
249 }
250 print '</div>';
251 } elseif ($creditor) {
252 print '<div class="backgreypublicpayment">';
253 print '<div class="logopublicpayment">';
254 print $creditor;
255 print '</div>';
256 print '</div>';
257 }
258 if (getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT')) {
259 print '<div class="backimagepublicpayment">';
260 print '<img id="idMAIN_IMAGE_PUBLIC_PAYMENT" src="' . getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT').'">';
261 print '</div>';
262 }
263
264
265 print '<br><br><br>';
266}
267
268
269// Validate the payment (for payment mode that need another step after the callback return for this).
270if (isModEnabled('paypal')) {
271 if ($paymentmethod === 'paypal') { // We call this page only if payment is ok on payment system
272 if ($PAYPALTOKEN) {
273 // Get on url call
274 $onlinetoken = $PAYPALTOKEN;
275 $fulltag = $FULLTAG;
276 $payerID = $PAYPALPAYERID;
277 // Set by newpayment.php
278 $currencyCodeType = $_SESSION['currencyCodeType'];
279 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
280 $paymentType = $_SESSION['PaymentType']; // Value can be 'Mark', 'Sole', 'Sale' for example
281 // From env
282 $ipaddress = $_SESSION['ipaddress'];
283
284 dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
285
286 // Validate record
287 if (!empty($paymentType)) {
288 dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment');
289 $resArray = getDetails($onlinetoken);
290 //var_dump($resarray);
291
292 $ack = strtoupper($resArray["ACK"]);
293 if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
294 // Nothing to do
295 dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
296 } else {
297 dol_syslog("Call to GetExpressCheckoutDetails return error: ".json_encode($resArray), LOG_WARNING, '_payment');
298 }
299
300 dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
301 $resArray2 = confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag);
302 //var_dump($resarray);
303
304 $ack = strtoupper($resArray2["ACK"]);
305 if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
306 dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
307
308 $object->source = $source;
309 $object->ref = $ref;
310 $object->payerID = $payerID;
311 $object->fulltag = $fulltag;
312 $object->resArray = $resArray2;
313
314 // resArray was built from a string like that
315 // 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
316 $PAYMENTSTATUS = urldecode($resArray2["PAYMENTSTATUS"]); // Should contains 'Completed'
317 $TRANSACTIONID = urldecode($resArray2["TRANSACTIONID"]);
318 $TAXAMT = urldecode($resArray2["TAXAMT"]);
319 $NOTE = urldecode($resArray2["NOTE"]);
320
321 $ispaymentok = true;
322 } else {
323 dol_syslog("Call to DoExpressCheckoutPayment return error: ".json_encode($resArray2), LOG_WARNING, 0, '_payment');
324
325 //Display a user friendly Error on the page using any of the following error information returned by PayPal
326 $ErrorCode = urldecode($resArray2["L_ERRORCODE0"]);
327 $ErrorShortMsg = urldecode($resArray2["L_SHORTMESSAGE0"]);
328 $ErrorLongMsg = urldecode($resArray2["L_LONGMESSAGE0"]);
329 $ErrorSeverityCode = urldecode($resArray2["L_SEVERITYCODE0"]);
330 }
331 } else {
332 $ErrorCode = "SESSIONEXPIRED";
333 $ErrorLongMsg = "Session expired. Can't retrieve PaymentType. Payment has not been validated.";
334 $ErrorShortMsg = "Session expired";
335
336 dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
337 dol_print_error(null, 'Session expired');
338 }
339 } else {
340 $ErrorCode = "PAYPALTOKENNOTDEFINED";
341 $ErrorLongMsg = "The parameter PAYPALTOKEN was not defined. Payment has not been validated.";
342 $ErrorShortMsg = "Parameter PAYPALTOKEN not defined";
343
344 dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
345 dol_print_error(null, 'PAYPALTOKEN not defined');
346 }
347 }
348}
349
350if (isModEnabled('paybox')) {
351 if ($paymentmethod === 'paybox') {
352 // TODO Add a check to validate that payment is ok.
353 $ispaymentok = true; // We call this page only if payment is ok on payment system
354 }
355}
356
357if (isModEnabled('stripe')) {
358 if ($paymentmethod === 'stripe') {
359 // TODO Add a check to validate that payment is ok. We can request Stripe with payment_intent and payment_intent_client_secret
360 $ispaymentok = true; // We call this page only if payment is ok on payment system
361 }
362}
363
364// Check status of the object to verify if it is paid by external payment modules
365$action = '';
366$parameters = [
367 'paymentmethod' => $paymentmethod,
368];
369$reshook = $hookmanager->executeHooks('isPaymentOK', $parameters, $object, $action);
370if ($reshook >= 0) {
371 if (isset($hookmanager->resArray['ispaymentok'])) {
372 dol_syslog('ispaymentok overwrite by hook return with value='.$hookmanager->resArray['ispaymentok'], LOG_DEBUG, 0, '_payment');
373 $ispaymentok = $hookmanager->resArray['ispaymentok'];
374 }
375}
376
377
378// If data not provided into callback url, search them into the session env
379if (empty($ipaddress)) {
380 $ipaddress = $_SESSION['ipaddress'];
381}
382if (empty($TRANSACTIONID)) {
383 $TRANSACTIONID = empty($_SESSION['TRANSACTIONID']) ? '' :$_SESSION['TRANSACTIONID']; // pi_... or ch_...
384 if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
385 // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
386 $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
387 }
388}
389if (empty($FinalPaymentAmt)) {
390 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
391}
392if (empty($currencyCodeType)) {
393 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
394}
395// Seems used only by Paypal
396if (empty($paymentType)) {
397 $paymentType = empty($_SESSION["paymentType"]) ? '' : $_SESSION["paymentType"];
398}
399
400$fulltag = $FULLTAG;
401$tmptag = dolExplodeIntoArray($fulltag, '.', '=');
402
403
404dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG_DEBUG, 0, '_payment');
405
406
407// Set $appli for emails title
408$appli = $mysoc->name;
409
410
411// Make complementary actions (post payment actions if payment is ok)
412$ispostactionok = 0;
413$postactionmessages = array();
414if ($ispaymentok) {
415 // Set permission for the anonymous user
416 if (empty($user->rights->societe)) {
417 $user->rights->societe = new stdClass();
418 }
419 if (empty($user->rights->facture)) {
420 $user->rights->facture = new stdClass();
421 $user->rights->facture->invoice_advance = new stdClass();
422 }
423 if (empty($user->rights->adherent)) {
424 $user->rights->adherent = new stdClass();
425 $user->rights->adherent->cotisation = new stdClass();
426 }
427 $user->rights->societe->creer = 1;
428 $user->rights->facture->creer = 1;
429 $user->rights->facture->invoice_advance->validate = 1;
430 $user->rights->adherent->cotisation->creer = 1;
431
432 if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) {
433 // Validate member
434 // Create subscription
435 // Create complementary actions (this include creation of thirdparty)
436 // Send confirmation email
437
438 // Record subscription
439 include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
440 include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
441 include_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
442 $adht = new AdherentType($db);
443 $object = new Adherent($db);
444
445 $result1 = $object->fetch((int) $tmptag['MEM']);
446 $result2 = $adht->fetch($object->typeid);
447
448 $defaultdelay = !empty($adht->duration_value) ? $adht->duration_value : 1;
449 $defaultdelayunit = !empty($adht->duration_unit) ? $adht->duration_unit : 'y';
450
451 dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment');
452
453 if ($result1 > 0 && $result2 > 0) {
454 $paymentTypeId = 0;
455 if ($paymentmethod == 'paybox') {
456 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
457 }
458 if ($paymentmethod == 'paypal') {
459 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
460 }
461 if ($paymentmethod == 'stripe') {
462 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
463 }
464 if (empty($paymentTypeId)) {
465 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
466
467 if (empty($paymentType)) {
468 $paymentType = 'CB';
469 }
470 // May return nothing when paymentType means nothing
471 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
472 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
473
474 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
475 if (empty($paymentTypeId) || $paymentTypeId < 0) {
476 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
477 }
478 }
479
480 dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId." currencyCodeType=".$currencyCodeType, LOG_DEBUG, 0, '_payment');
481
482 // 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)
483 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
484 // Security protection:
485 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)
486 if ($object->status == $object::STATUS_DRAFT) { // If the member is not yet validated, we check that the amount is the same as expected.
487 $typeid = $object->typeid;
488 $amountbytype = $adht->amountByType(1); // Load the array of amount per type
489
490 // Set amount for the subscription:
491 // - First check the amount of the member type.
492 $amountexpected = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
493 // - If not found, take the default amount
494 if (empty($amountexpected) && getDolGlobalString('MEMBER_NEWFORM_AMOUNT')) {
495 $amountexpected = getDolGlobalString('MEMBER_NEWFORM_AMOUNT');
496 }
497 // - If not set, we accept to have amount defined as parameter (for backward compatibility).
498 //if (empty($amount)) {
499 // $amount = (GETPOST('amount') ? price2num(GETPOST('amount', 'alpha'), 'MT', 2) : '');
500 //}
501 // - If a min is set, we take it into account
502 $amountexpected = max(0, (float) $amountexpected, (float) getDolGlobalInt("MEMBER_MIN_AMOUNT"));
503
504 if ($amountexpected && $amountexpected != $FinalPaymentAmt) {
505 $error++;
506 $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') propagated by payment page differs from the expected value for membership ('.$amountexpected.'). May be a hack to try to pay a different amount ?';
507 $postactionmessages[] = $errmsg;
508 $ispostactionok = -1;
509 dol_syslog("Failed to validate member (bad amount check): ".$errmsg, LOG_ERR, 0, '_payment');
510 }
511 }
512 }
513
514 // Security protection:
515 if (getDolGlobalInt('MEMBER_MIN_AMOUNT')) {
516 if ($FinalPaymentAmt < getDolGlobalInt('MEMBER_MIN_AMOUNT')) {
517 $error++;
518 $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 ?';
519 $postactionmessages[] = $errmsg;
520 $ispostactionok = -1;
521 dol_syslog("Failed to validate member (amount propagated from payment page is lower than allowed minimum): ".$errmsg, LOG_ERR, 0, '_payment');
522 }
523 }
524
525 // Security protection:
526 if ($currencyCodeType && $currencyCodeType != $conf->currency) { // Check that currency is the good one
527 $error++;
528 $errmsg = 'Value of currencyCodeType ('.$currencyCodeType.') differs from value expected for membership ('.$conf->currency.'). May be a hack to try to pay a different amount ?';
529 $postactionmessages[] = $errmsg;
530 $ispostactionok = -1;
531 dol_syslog("Failed to validate member (bad currency check): ".$errmsg, LOG_ERR, 0, '_payment');
532 }
533
534 if (! $error) {
535 // We validate the member (no effect if it is already validated)
536 $result = ($object->status == $object::STATUS_EXCLUDED) ? -1 : $object->validate($user); // if membre is excluded (status == -2) the new validation is not possible
537 if ($result < 0 || empty($object->datevalid)) {
538 $error++;
539 $errmsg = $object->error;
540 $postactionmessages[] = $errmsg;
541 $postactionmessages = array_merge($postactionmessages, $object->errors);
542 $ispostactionok = -1;
543 dol_syslog("Failed to validate member: ".$errmsg, LOG_ERR, 0, '_payment');
544 }
545 }
546
547 // Guess the subscription start date
548 $datesubscription = $object->datevalid; // By default, the subscription start date is the payment date
549 if ($object->datefin > 0) {
550 $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
551 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER')) {
552 $datesubscription = dol_time_plus_duree($now, (int) substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), 0, -1), substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), -1));
553 }
554 // Now do a correction of the suggested date
555 if (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "m") {
556 $datesubscription = dol_get_first_day(dol_print_date($datesubscription, "%Y"), dol_print_date($datesubscription, "%m"));
557 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "Y") {
558 $datesubscription = dol_get_first_day(dol_print_date($datesubscription, "%Y"));
559 }
560
561 $datesubend = null;
562 if ($datesubscription && $defaultdelay && $defaultdelayunit) {
563 $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
564 // the new end date of subscription must be in futur
565 while ($datesubend < $now) {
566 $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
567 $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
568 }
569 $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
570 }
571
572 // Set output language
573 $outputlangs = new Translate('', $conf);
574 $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
575 $paymentdate = $now;
576 $amount = $FinalPaymentAmt;
577 $formatteddate = dol_print_date($paymentdate, 'dayhour', 'auto', $outputlangs);
578 $label = $langs->trans("OnlineSubscriptionPaymentLine", $formatteddate, $paymentmethod, $ipaddress, $TRANSACTIONID);
579
580 // Payment information
581 $accountid = 0;
582 if ($paymentmethod == 'paybox') {
583 $accountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
584 }
585 if ($paymentmethod == 'paypal') {
586 $accountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
587 }
588 if ($paymentmethod == 'stripe') {
589 $accountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
590 }
591
592 //Get bank account for a specific paymentmedthod
593 $parameters = [
594 'paymentmethod' => $paymentmethod,
595 ];
596 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
597 if ($reshook >= 0) {
598 if (isset($hookmanager->resArray['bankaccountid'])) {
599 dol_syslog('accountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
600 $accountid = $hookmanager->resArray['bankaccountid'];
601 }
602 }
603 if ($accountid < 0) {
604 $error++;
605 $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
606 $postactionmessages[] = $errmsg;
607 $ispostactionok = -1;
608 dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
609 }
610
611 $operation = dol_getIdFromCode($db, $paymentTypeId, 'c_paiement', 'id', 'code', 1); // Payment mode code returned from payment mode id
612 $num_chq = '';
613 $emetteur_nom = '';
614 $emetteur_banque = '';
615 // Define default choice for complementary actions
616 $option = '';
617 if (getDolGlobalString('ADHERENT_BANK_USE') == 'bankviainvoice' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
618 $option = 'bankviainvoice';
619 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'bankdirect' && isModEnabled("bank")) {
620 $option = 'bankdirect';
621 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'invoiceonly' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
622 $option = 'invoiceonly';
623 }
624 if (empty($option)) {
625 $option = 'none';
626 }
627 $sendalsoemail = 1;
628
629 // Record the subscription then complementary actions
630 $db->begin();
631
632 // Create subscription
633 if (!$error) {
634 dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
635
636 $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
637 if ($crowid <= 0) {
638 $error++;
639 $errmsg = $object->error;
640 $postactionmessages[] = $errmsg;
641 $ispostactionok = -1;
642 } else {
643 $postactionmessages[] = 'Subscription created (id='.$crowid.')';
644 $ispostactionok = 1;
645 }
646 }
647
648 if (!$error) {
649 dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
650
651 $autocreatethirdparty = 1; // will create thirdparty if member not yet linked to a thirdparty
652
653 $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
654 if ($result < 0) {
655 dol_syslog("Error ".$object->error." ".implode(',', $object->errors), LOG_DEBUG, 0, '_payment');
656
657 $error++;
658 $postactionmessages[] = $object->error;
659 $postactionmessages = array_merge($postactionmessages, $object->errors);
660 $ispostactionok = -1;
661 } else {
662 if ($option == 'bankviainvoice') {
663 $postactionmessages[] = 'Invoice, payment and bank record created';
664 dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
665 }
666 if ($option == 'bankdirect') {
667 $postactionmessages[] = 'Bank record created';
668 dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
669 }
670 if ($option == 'invoiceonly') {
671 $postactionmessages[] = 'Invoice recorded';
672 dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
673 }
674 $ispostactionok = 1;
675
676 // If an invoice was created, it is into $object->invoice
677 }
678 }
679
680 if (!$error) {
681 // If payment using Strip, save the Stripe payment info into societe_account
682 if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
683 $thirdparty_id = ($object->socid ? $object->socid : $object->fk_soc);
684
685 dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
686
687 $service = 'StripeTest';
688 $servicestatus = 0;
689 if (getDolGlobalString('STRIPE_LIVE') && !GETPOST('forcesandbox', 'alpha')) {
690 $service = 'StripeLive';
691 $servicestatus = 1;
692 }
693 $stripeacc = null; // No Oauth/connect use for public pages
694
695 $thirdparty = new Societe($db);
696 $thirdparty->fetch($thirdparty_id);
697
698 include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
699 $stripe = new Stripe($db);
700 //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
701
702 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
703
704 if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
705 dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
706
707 try {
708 global $stripearrayofkeysbyenv;
709 \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
710
711 if (preg_match('/^pi_/', $TRANSACTIONID)) {
712 // This may throw an error if not found.
713 $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
714 } else {
715 // This throw an error if not found
716 $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
717 }
718
719 if ($chpi) {
720 $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
721
722 if (empty($stripecu)) {
723 // This include the INSERT
724 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
725
726 // Link this customer to the payment intent
727 if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
728 \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
729 }
730 } else {
731 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
732 $sql .= " VALUES (".$thirdparty_id.", '', '".$db->escape($stripecu)."', 'stripe', '".$db->escape($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])."', ".((int) $servicestatus).", ".((int) $conf->entity).", '".$db->idate(dol_now())."', 0)";
733 $resql = $db->query($sql);
734 if (!$resql) { // should not happen
735 $error++;
736 $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
737 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
738 $postactionmessages[] = $errmsg;
739 $ispostactionok = -1;
740 }
741 }
742 } else { // should not happen
743 $error++;
744 $errmsg = 'Failed to retrieve paymentintent or charge from id';
745 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
746 $postactionmessages[] = $errmsg;
747 $ispostactionok = -1;
748 }
749 } catch (Exception $e) { // should not happen
750 $error++;
751 $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
752 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
753 $postactionmessages[] = $errmsg;
754 $ispostactionok = -1;
755 }
756 }
757 }
758 }
759
760 if (!$error) {
761 $db->commit();
762 } else {
763 $db->rollback();
764 }
765
766 // Set string to use to send email info
767 $infouserlogin = '';
768
769 // Create external user
770 if (getDolGlobalString('ADHERENT_CREATE_EXTERNAL_USER_LOGIN')) {
771 $nuser = new User($db);
772 $tmpuser = dol_clone($object, 0); // $object is type Adherent
773
774 // Check if a user login already exists for this member or not
775 $found = 0;
776 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."user WHERE fk_member = ".((int) $object->id);
777 $resqlcount = $db->query($sql);
778 if ($resqlcount) {
779 $objcount = $db->fetch_object($resqlcount);
780 if ($objcount) {
781 $found = $objcount->nb;
782 }
783 }
784
785 if (!$found) {
786 $result = $nuser->create_from_member($tmpuser, $object->login);
787 $newpassword = $nuser->setPassword($user, '');
788
789 if ($result < 0) {
790 $outputlangs->load("errors");
791 $postactionmessages[] = 'Error in create external user : '.$nuser->error;
792 } else {
793 $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
794 $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
795 }
796 } else {
797 $outputlangs->load("errors");
798 $postactionmessages[] = 'No user created because a user linked to member already exists';
799 }
800 }
801
802 // Send email to member
803 if (!$error) {
804 dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
805
806 // Send confirmation Email
807 if ($object->email && $sendalsoemail) {
808 $subject = '';
809 $msg = '';
810
811 // Send subscription email
812 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
813 $formmail = new FormMail($db);
814 // Load traductions files required by page
815 $outputlangs->loadLangs(array("main", "members"));
816 // Get email content from template
817 $arraydefaultmessage = null;
818 $labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION');
819
820 if (!empty($labeltouse)) {
821 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
822 }
823
824 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
825 $subject = $arraydefaultmessage->topic;
826 $msg = $arraydefaultmessage->content;
827 }
828
829 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
830
831 if ($infouserlogin) {
832 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
833 }
834
835 complete_substitutions_array($substitutionarray, $outputlangs, $object);
836 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
837 $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
838
839 // Attach a file ?
840 $file = '';
841 $listofpaths = array();
842 $listofnames = array();
843 $listofmimes = array();
844 if (is_object($object->invoice)) {
845 $invoicediroutput = $conf->facture->dir_output;
846 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
847 $file = $fileparams['fullname'];
848
849 $listofpaths = array($file);
850 $listofnames = array(basename($file));
851 $listofmimes = array(dol_mimetype($file));
852 }
853
854 $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
855
856 $result = $object->sendEmail($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
857
858 if ($result < 0) {
859 $errmsg = $object->error;
860 $postactionmessages[] = $errmsg;
861 $ispostactionok = -1;
862 } else {
863 if ($file) {
864 $postactionmessages[] = 'Email sent to member (with invoice document attached)';
865 } else {
866 $postactionmessages[] = 'Email sent to member (without any attached document)';
867 }
868
869 // TODO Add actioncomm event
870 }
871 }
872 }
873 } else {
874 $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.';
875 $ispostactionok = -1;
876 }
877 } else {
878 $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
879 $ispostactionok = -1;
880 }
881 } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
882 // Record payment
883 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
884 $object = new Facture($db);
885 $result = $object->fetch((int) $tmptag['INV']);
886 if ($result) {
887 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
888
889 $paymentTypeId = 0;
890 if ($paymentmethod === 'paybox') {
891 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
892 }
893 if ($paymentmethod === 'paypal') {
894 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
895 }
896 if ($paymentmethod === 'stripe') {
897 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
898 }
899 if (empty($paymentTypeId)) {
900 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
901
902 if (empty($paymentType)) {
903 $paymentType = 'CB';
904 }
905 // May return nothing when paymentType means nothing
906 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
907 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
908
909 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
910 if (empty($paymentTypeId) || $paymentTypeId < 0) {
911 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
912 }
913 }
914
915 dol_syslog("FinalPaymentAmt = ".$FinalPaymentAmt." paymentTypeId = ".$paymentTypeId, LOG_DEBUG, 0, '_payment');
916
917 // 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)
918 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
919 $db->begin();
920
921 // Creation of payment line
922 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
923 $paiement = new Paiement($db);
924 $paiement->datepaye = $now;
925 if ($currencyCodeType == $conf->currency) {
926 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
927 } else {
928 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
929
930 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
931 $ispostactionok = -1;
932 $error++; // Not yet supported
933 }
934 $paiement->paiementid = $paymentTypeId;
935 $paiement->num_payment = '';
936 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
937 $paiement->ext_payment_id = $TRANSACTIONID; // TODO LDR May be we should store py_... instead of pi_... but we started with pi_... so we continue.
938 //$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 ?
939 $paiement->ext_payment_site = $service;
940
941 if (!$error) {
942 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
943 if ($paiement_id < 0) {
944 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
945 $ispostactionok = -1;
946 $error++;
947 } else {
948 $postactionmessages[] = 'Payment created';
949 $ispostactionok = 1;
950 }
951 }
952
953 if (!$error && isModEnabled("bank")) {
954 $bankaccountid = 0;
955 if ($paymentmethod == 'paybox') {
956 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
957 } elseif ($paymentmethod == 'paypal') {
958 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
959 } elseif ($paymentmethod == 'stripe') {
960 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
961 }
962
963 //Get bank account for a specific paymentmedthod
964 $parameters = [
965 'paymentmethod' => $paymentmethod,
966 ];
967 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
968 if ($reshook >= 0) {
969 if (isset($hookmanager->resArray['bankaccountid'])) {
970 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
971 $bankaccountid = $hookmanager->resArray['bankaccountid'];
972 }
973 }
974 if ($bankaccountid > 0) {
975 $label = '(CustomerInvoicePayment)';
976 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
977 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
978 }
979 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
980 if ($result < 0) {
981 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
982 $ispostactionok = -1;
983 $error++;
984 } else {
985 $postactionmessages[] = 'Bank transaction of payment created';
986 $ispostactionok = 1;
987 }
988 } else {
989 $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.';
990 $ispostactionok = -1;
991 $error++;
992 }
993 }
994
995 if (!$error) {
996 $db->commit();
997 } else {
998 $db->rollback();
999 }
1000 } else {
1001 $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.';
1002 $ispostactionok = -1;
1003 }
1004 } else {
1005 $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
1006 $ispostactionok = -1;
1007 }
1008 } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
1009 include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
1010 $object = new Commande($db);
1011 $result = $object->fetch((int) $tmptag['ORD']);
1012 if ($result) {
1013 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1014
1015 $paymentTypeId = 0;
1016 if ($paymentmethod == 'paybox') {
1017 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1018 }
1019 if ($paymentmethod == 'paypal') {
1020 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1021 }
1022 if ($paymentmethod == 'stripe') {
1023 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1024 }
1025 if (empty($paymentTypeId)) {
1026 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1027
1028 if (empty($paymentType)) {
1029 $paymentType = 'CB';
1030 }
1031 // May return nothing when paymentType means nothing
1032 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1033 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1034
1035 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1036 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1037 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1038 }
1039 }
1040
1041 // 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)
1042 if (isModEnabled('invoice')) {
1043 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1044 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1045 $invoice = new Facture($db);
1046 $result = $invoice->createFromOrder($object, $user);
1047 if ($result > 0) {
1048 $object->classifyBilled($user);
1049 $invoice->validate($user);
1050 // Creation of payment line
1051 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1052 $paiement = new Paiement($db);
1053 $paiement->datepaye = $now;
1054 if ($currencyCodeType == $conf->currency) {
1055 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1056 } else {
1057 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1058
1059 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1060 $ispostactionok = -1;
1061 $error++;
1062 }
1063 $paiement->paiementid = $paymentTypeId;
1064 $paiement->num_payment = '';
1065 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1066 $paiement->ext_payment_id = $TRANSACTIONID; // pi_... for Stripe, ...
1067 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1068
1069 if (!$error) {
1070 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1071 if ($paiement_id < 0) {
1072 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1073 $ispostactionok = -1;
1074 $error++;
1075 } else {
1076 $postactionmessages[] = 'Payment created';
1077 $ispostactionok = 1;
1078 }
1079 }
1080
1081 if (!$error && isModEnabled("bank")) {
1082 $bankaccountid = 0;
1083 if ($paymentmethod == 'paybox') {
1084 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1085 } elseif ($paymentmethod == 'paypal') {
1086 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1087 } elseif ($paymentmethod == 'stripe') {
1088 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1089 }
1090
1091 //Get bank account for a specific paymentmedthod
1092 $parameters = [
1093 'paymentmethod' => $paymentmethod,
1094 ];
1095 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1096 if ($reshook >= 0) {
1097 if (isset($hookmanager->resArray['bankaccountid'])) {
1098 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1099 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1100 }
1101 }
1102 if ($bankaccountid > 0) {
1103 $label = '(CustomerInvoicePayment)';
1104 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1105 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1106 }
1107 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1108 if ($result < 0) {
1109 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1110 $ispostactionok = -1;
1111 $error++;
1112 } else {
1113 $postactionmessages[] = 'Bank transaction of payment created';
1114 $ispostactionok = 1;
1115 }
1116 } else {
1117 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1118 $ispostactionok = -1;
1119 $error++;
1120 }
1121 }
1122
1123 if (!$error) {
1124 $db->commit();
1125 } else {
1126 $db->rollback();
1127 }
1128 } else {
1129 $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
1130 $ispostactionok = -1;
1131 }
1132 } else {
1133 $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.';
1134 $ispostactionok = -1;
1135 }
1136 } else {
1137 $postactionmessages[] = 'Invoice module is not enable';
1138 $ispostactionok = -1;
1139 }
1140 } else {
1141 $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
1142 $ispostactionok = -1;
1143 }
1144 } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
1145 include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
1146 $don = new Don($db);
1147 $result = $don->fetch((int) $tmptag['DON']);
1148 if ($result) {
1149 $paymentTypeId = 0;
1150 if ($paymentmethod == 'paybox') {
1151 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1152 }
1153 if ($paymentmethod == 'paypal') {
1154 $paymentTypeId = getDolGlobalInt('global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1155 }
1156 if ($paymentmethod == 'stripe') {
1157 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1158 }
1159 if (empty($paymentTypeId)) {
1160 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1161
1162 if (empty($paymentType)) {
1163 $paymentType = 'CB';
1164 }
1165 // May return nothing when paymentType means nothing
1166 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1167 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1168
1169 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1170 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1171 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1172 }
1173 }
1174
1175 // 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)
1176 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1177 $db->begin();
1178
1179 // Creation of paiement line for donation
1180 include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
1181 $paiement = new PaymentDonation($db);
1182
1183 $totalpaid = $FinalPaymentAmt;
1184
1185 if ($currencyCodeType == $conf->currency) {
1186 $paiement->amounts = array($object->id => $totalpaid); // Array with all payments dispatching with donation
1187 } else {
1188 // PaymentDonation does not support multi currency
1189 $postactionmessages[] = 'Payment donation can\'t be paid with different currency than '.$conf->currency;
1190 $ispostactionok = -1;
1191 $error++; // Not yet supported
1192 }
1193
1194 $paiement->fk_donation = $don->id;
1195 $paiement->datep = $now;
1196 $paiement->paymenttype = $paymentTypeId;
1197 $paiement->num_payment = '';
1198 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1199 $paiement->ext_payment_id = $TRANSACTIONID;
1200 $paiement->ext_payment_site = $service;
1201
1202 if (!$error) {
1203 $paiement_id = $paiement->create($user, 1);
1204 if ($paiement_id < 0) {
1205 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1206 $ispostactionok = -1;
1207 $error++;
1208 } else {
1209 $postactionmessages[] = 'Payment created';
1210 $ispostactionok = 1;
1211
1212 if ($totalpaid >= $don->getRemainToPay()) {
1213 $don->setPaid($don->id);
1214 }
1215 }
1216 }
1217
1218 if (!$error && isModEnabled("bank")) {
1219 $bankaccountid = 0;
1220 if ($paymentmethod == 'paybox') {
1221 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1222 } elseif ($paymentmethod == 'paypal') {
1223 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1224 } elseif ($paymentmethod == 'stripe') {
1225 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1226 }
1227
1228 //Get bank account for a specific paymentmedthod
1229 $parameters = [
1230 'paymentmethod' => $paymentmethod,
1231 ];
1232 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1233 if ($reshook >= 0) {
1234 if (isset($hookmanager->resArray['bankaccountid'])) {
1235 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1236 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1237 }
1238 }
1239 if ($bankaccountid > 0) {
1240 $label = '(DonationPayment)';
1241 $result = $paiement->addPaymentToBank($user, 'payment_donation', $label, $bankaccountid, '', '');
1242 if ($result < 0) {
1243 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1244 $ispostactionok = -1;
1245 $error++;
1246 } else {
1247 $postactionmessages[] = 'Bank transaction of payment created';
1248 $ispostactionok = 1;
1249 }
1250 } else {
1251 $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.';
1252 $ispostactionok = -1;
1253 $error++;
1254 }
1255 }
1256
1257 if (!$error) {
1258 $db->commit();
1259 } else {
1260 $db->rollback();
1261 }
1262 } else {
1263 $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.';
1264 $ispostactionok = -1;
1265 }
1266 } else {
1267 $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
1268 $ispostactionok = -1;
1269 }
1270
1271 // TODO send email with acknowledgment for the donation
1272 // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
1273 } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
1274 // Record payment for registration to an event for an attendee
1275 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1276 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1277 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1278 $object = new Facture($db);
1279 $result = $object->fetch($ref);
1280 if ($result) {
1281 $paymentTypeId = 0;
1282 if ($paymentmethod == 'paybox') {
1283 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1284 }
1285 if ($paymentmethod == 'paypal') {
1286 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1287 }
1288 if ($paymentmethod == 'stripe') {
1289 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1290 }
1291 if (empty($paymentTypeId)) {
1292 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1293
1294 if (empty($paymentType)) {
1295 $paymentType = 'CB';
1296 }
1297 // May return nothing when paymentType means nothing
1298 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1299 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1300
1301 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1302 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1303 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1304 }
1305 }
1306
1307 // 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)
1308 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1309 $resultvalidate = $object->validate($user);
1310 if ($resultvalidate < 0) {
1311 $postactionmessages[] = 'Cannot validate invoice';
1312 $ispostactionok = -1;
1313 $error++; // Not yet supported
1314 } else {
1315 $db->begin();
1316
1317 // Creation of payment line
1318 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1319 $paiement = new Paiement($db);
1320 $paiement->datepaye = $now;
1321 if ($currencyCodeType == $conf->currency) {
1322 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1323 } else {
1324 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1325
1326 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1327 $ispostactionok = -1;
1328 $error++; // Not yet supported
1329 }
1330 $paiement->paiementid = $paymentTypeId;
1331 $paiement->num_payment = '';
1332 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
1333 $paiement->ext_payment_id = $TRANSACTIONID;
1334 $paiement->ext_payment_site = $service;
1335
1336 if (!$error) {
1337 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1338 if ($paiement_id < 0) {
1339 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1340 $ispostactionok = -1;
1341 $error++;
1342 } else {
1343 $postactionmessages[] = 'Payment created';
1344 $ispostactionok = 1;
1345 }
1346 }
1347
1348 if (!$error && isModEnabled("bank")) {
1349 $bankaccountid = 0;
1350 if ($paymentmethod == 'paybox') {
1351 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1352 } elseif ($paymentmethod == 'paypal') {
1353 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1354 } elseif ($paymentmethod == 'stripe') {
1355 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1356 }
1357
1358 //Get bank account for a specific paymentmedthod
1359 $parameters = [
1360 'paymentmethod' => $paymentmethod,
1361 ];
1362 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1363 if ($reshook >= 0) {
1364 if (isset($hookmanager->resArray['bankaccountid'])) {
1365 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1366 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1367 }
1368 }
1369 if ($bankaccountid > 0) {
1370 $label = '(CustomerInvoicePayment)';
1371 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1372 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1373 }
1374 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1375 if ($result < 0) {
1376 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1377 $ispostactionok = -1;
1378 $error++;
1379 } else {
1380 $postactionmessages[] = 'Bank transaction of payment created';
1381 $ispostactionok = 1;
1382 }
1383 } else {
1384 $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.';
1385 $ispostactionok = -1;
1386 $error++;
1387 }
1388 }
1389
1390 $attendeetovalidate = new ConferenceOrBoothAttendee($db);
1391
1392 if (!$error) {
1393 // Validating the attendee
1394 $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
1395 if ($resultattendee < 0) {
1396 $error++;
1397 setEventMessages(null, $attendeetovalidate->errors, "errors");
1398 } else {
1399 $attendeetovalidate->validate($user);
1400
1401 $attendeetovalidate->amount = $FinalPaymentAmt;
1402 $attendeetovalidate->date_subscription = dol_now();
1403 $attendeetovalidate->update($user);
1404 }
1405 }
1406
1407 if (!$error) {
1408 $db->commit();
1409 } else {
1410 setEventMessages(null, $postactionmessages, 'warnings');
1411
1412 $db->rollback();
1413 }
1414
1415 if (! $error) {
1416 // Sending mail
1417 $thirdparty = new Societe($db);
1418 $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
1419 if ($resultthirdparty < 0) {
1420 setEventMessages($resultthirdparty->error, $resultthirdparty->errors, "errors");
1421 } else {
1422 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1423 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1424 $formmail = new FormMail($db);
1425 // Set output language
1426 $outputlangs = new Translate('', $conf);
1427 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1428 // Load traductions files required by page
1429 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1430 // Get email content from template
1431 $arraydefaultmessage = null;
1432
1433 $idoftemplatetouse = getDolGlobalString('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT'); // Email to send for Event organization registration
1434
1435 if (!empty($idoftemplatetouse)) {
1436 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1437 }
1438
1439 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1440 $subject = $arraydefaultmessage->topic;
1441 $msg = $arraydefaultmessage->content;
1442 } else {
1443 $subject = '['.$appli.'] '.$object->ref.' - '.$outputlangs->trans("NewRegistration");
1444 $msg = $outputlangs->trans("OrganizationEventPaymentOfRegistrationWasReceived");
1445 }
1446
1447 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1448 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1449
1450 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1451 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1452
1453 $sendto = $attendeetovalidate->email;
1454 $cc = '';
1455 if ($thirdparty->email) {
1456 $cc = $thirdparty->email;
1457 }
1458 if ($attendeetovalidate->email_company && $attendeetovalidate->email_company != $thirdparty->email) {
1459 $cc = ($cc ? ', ' : '').$attendeetovalidate->email_company;
1460 }
1461
1462 $from = getDolGlobalString('MAILING_EMAIL_FROM') ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1463
1464 $urlback = $_SERVER["REQUEST_URI"];
1465
1466 $ishtml = dol_textishtml($texttosend); // May contain urls
1467
1468 // Attach a file ?
1469 $file = '';
1470 $listofpaths = array();
1471 $listofnames = array();
1472 $listofmimes = array();
1473 if (is_object($object)) {
1474 $invoicediroutput = $conf->facture->dir_output;
1475 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->ref, preg_quote($object->ref, '/').'[^\-]+');
1476 $file = $fileparams['fullname'];
1477
1478 $listofpaths = array($file);
1479 $listofnames = array(basename($file));
1480 $listofmimes = array(dol_mimetype($file));
1481 }
1482
1483 $trackid = 'inv'.$object->id;
1484
1485 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, $cc, '', 0, $ishtml, '', '', $trackid, '', 'standard');
1486
1487 $result = $mailfile->sendfile();
1488 if ($result) {
1489 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1490 } else {
1491 dol_syslog("Failed to send EMail to ".$sendto.' - '.$mailfile->error, LOG_ERR, 0, '_payment');
1492 }
1493 }
1494 }
1495 }
1496 } else {
1497 $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.';
1498 $ispostactionok = -1;
1499 }
1500 } else {
1501 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1502 $ispostactionok = -1;
1503 }
1504 } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
1505 // Record payment for booth or conference
1506 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1507 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1508 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1509 $object = new Facture($db);
1510 $result = $object->fetch($ref);
1511 if ($result) {
1512 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1513
1514 $paymentTypeId = 0;
1515 if ($paymentmethod == 'paybox') {
1516 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1517 }
1518 if ($paymentmethod == 'paypal') {
1519 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1520 }
1521 if ($paymentmethod == 'stripe') {
1522 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1523 }
1524 if (empty($paymentTypeId)) {
1525 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1526
1527 if (empty($paymentType)) {
1528 $paymentType = 'CB';
1529 }
1530 // May return nothing when paymentType means nothing
1531 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1532 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1533
1534 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1535 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1536 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1537 }
1538 }
1539
1540 // 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)
1541 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1542 $resultvalidate = $object->validate($user);
1543 if ($resultvalidate < 0) {
1544 $postactionmessages[] = 'Cannot validate invoice';
1545 $ispostactionok = -1;
1546 $error++; // Not yet supported
1547 } else {
1548 $db->begin();
1549
1550 // Creation of payment line
1551 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1552 $paiement = new Paiement($db);
1553 $paiement->datepaye = $now;
1554 if ($currencyCodeType == $conf->currency) {
1555 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1556 } else {
1557 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1558
1559 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1560 $ispostactionok = -1;
1561 $error++; // Not yet supported
1562 }
1563 $paiement->paiementid = $paymentTypeId;
1564 $paiement->num_payment = '';
1565 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1566 $paiement->ext_payment_id = $TRANSACTIONID;
1567 $paiement->ext_payment_site = $service;
1568
1569 if (!$error) {
1570 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1571 if ($paiement_id < 0) {
1572 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1573 $ispostactionok = -1;
1574 $error++;
1575 } else {
1576 $postactionmessages[] = 'Payment created';
1577 $ispostactionok = 1;
1578 }
1579 }
1580
1581 if (!$error && isModEnabled("bank")) {
1582 $bankaccountid = 0;
1583 if ($paymentmethod == 'paybox') {
1584 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1585 } elseif ($paymentmethod == 'paypal') {
1586 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1587 } elseif ($paymentmethod == 'stripe') {
1588 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1589 }
1590
1591 //Get bank account for a specific paymentmedthod
1592 $parameters = [
1593 'paymentmethod' => $paymentmethod,
1594 ];
1595 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1596 if ($reshook >= 0) {
1597 if (isset($hookmanager->resArray['bankaccountid'])) {
1598 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1599 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1600 }
1601 }
1602 if ($bankaccountid > 0) {
1603 $label = '(CustomerInvoicePayment)';
1604 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1605 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1606 }
1607 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1608 if ($result < 0) {
1609 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1610 $ispostactionok = -1;
1611 $error++;
1612 } else {
1613 $postactionmessages[] = 'Bank transaction of payment created';
1614 $ispostactionok = 1;
1615 }
1616 } else {
1617 $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.';
1618 $ispostactionok = -1;
1619 $error++;
1620 }
1621 }
1622
1623 if (!$error) {
1624 // Putting the booth to "suggested" state
1625 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1626 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1627 $booth = new ConferenceOrBooth($db);
1628 $resultbooth = $booth->fetch((int) $tmptag['BOO']);
1629 if ($resultbooth < 0) {
1630 $error++;
1631 setEventMessages(null, $booth->errors, "errors");
1632 } else {
1633 $booth->status = ConferenceOrBooth::STATUS_SUGGESTED;
1634 $resultboothupdate = $booth->update($user);
1635 if ($resultboothupdate<0) {
1636 // Finding the thirdparty by getting the invoice
1637 $invoice = new Facture($db);
1638 $resultinvoice = $invoice->fetch($ref);
1639 if ($resultinvoice<0) {
1640 $postactionmessages[] = 'Could not find the associated invoice.';
1641 $ispostactionok = -1;
1642 $error++;
1643 } else {
1644 $thirdparty = new Societe($db);
1645 $resultthirdparty = $thirdparty->fetch($invoice->socid);
1646 if ($resultthirdparty<0) {
1647 $error++;
1648 setEventMessages(null, $thirdparty->errors, "errors");
1649 } else {
1650 // Sending mail
1651 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1652 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1653 $formmail = new FormMail($db);
1654 // Set output language
1655 $outputlangs = new Translate('', $conf);
1656 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1657 // Load traductions files required by page
1658 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1659 // Get email content from template
1660 $arraydefaultmessage = null;
1661
1662 $idoftemplatetouse = getDolGlobalString('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH'); // Email sent after registration for a Booth
1663
1664 if (!empty($idoftemplatetouse)) {
1665 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1666 }
1667
1668 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1669 $subject = $arraydefaultmessage->topic;
1670 $msg = $arraydefaultmessage->content;
1671 } else {
1672 $subject = '['.$appli.'] '.$booth->ref.' - '.$outputlangs->trans("NewRegistration").']';
1673 $msg = $outputlangs->trans("OrganizationEventPaymentOfBoothWasReceived");
1674 }
1675
1676 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1677 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1678
1679 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1680 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1681
1682 $sendto = $thirdparty->email;
1683 $from = getDolGlobalString('MAILING_EMAIL_FROM');
1684 $urlback = $_SERVER["REQUEST_URI"];
1685
1686 $ishtml = dol_textishtml($texttosend); // May contain urls
1687 $trackid = 'inv'.$invoice->id;
1688
1689 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml, '', '', $trackid, '', 'standard');
1690
1691 $result = $mailfile->sendfile();
1692 if ($result) {
1693 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1694 } else {
1695 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1696 }
1697 }
1698 }
1699 }
1700 }
1701 }
1702
1703 if (!$error) {
1704 $db->commit();
1705 } else {
1706 $db->rollback();
1707 }
1708 }
1709 } else {
1710 $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.';
1711 $ispostactionok = -1;
1712 }
1713 } else {
1714 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1715 $ispostactionok = -1;
1716 }
1717 } elseif (array_key_exists('CON', $tmptag) && $tmptag['CON'] > 0) {
1718 include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
1719 $object = new Contrat($db);
1720 $result = $object->fetch((int) $tmptag['CON']);
1721 if ($result) {
1722 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1723
1724 $paymentTypeId = 0;
1725 if ($paymentmethod == 'paybox') {
1726 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1727 }
1728 if ($paymentmethod == 'paypal') {
1729 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1730 }
1731 if ($paymentmethod == 'stripe') {
1732 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1733 }
1734 if (empty($paymentTypeId)) {
1735 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1736
1737 if (empty($paymentType)) {
1738 $paymentType = 'CB';
1739 }
1740 // May return nothing when paymentType means nothing
1741 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1742 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1743
1744 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1745 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1746 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1747 }
1748 }
1749
1750 $currencyCodeType = $_SESSION['currencyCodeType'];
1751 $contract_lines = (array_key_exists('COL', $tmptag) && $tmptag['COL'] > 0) ? $tmptag['COL'] : null;
1752
1753 // 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)
1754 if (isModEnabled('invoice')) {
1755 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1756 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1757 $invoice = new Facture($db);
1758 $result = $invoice->createFromContract($object, $user, array((int) $contract_lines));
1759 if ($result > 0) {
1760 // $object->classifyBilled($user);
1761 $invoice->validate($user);
1762 // Creation of payment line
1763 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1764 $paiement = new Paiement($db);
1765 $paiement->datepaye = $now;
1766 if ($currencyCodeType == $conf->currency) {
1767 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1768 } else {
1769 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1770
1771 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1772 $ispostactionok = -1;
1773 $error++;
1774 }
1775 $paiement->paiementid = $paymentTypeId;
1776 $paiement->num_payment = '';
1777 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1778 $paiement->ext_payment_id = $TRANSACTIONID; // pi_... for Stripe, ...
1779 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1780
1781 if (!$error) {
1782 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1783 if ($paiement_id < 0) {
1784 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1785 $ispostactionok = -1;
1786 $error++;
1787 } else {
1788 $postactionmessages[] = 'Payment created';
1789 $ispostactionok = 1;
1790 }
1791 }
1792
1793 if (!$error && isModEnabled("bank")) {
1794 $bankaccountid = 0;
1795 if ($paymentmethod == 'paybox') {
1796 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1797 } elseif ($paymentmethod == 'paypal') {
1798 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1799 } elseif ($paymentmethod == 'stripe') {
1800 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1801 }
1802
1803 //Get bank account for a specific paymentmedthod
1804 $parameters = [
1805 'paymentmethod' => $paymentmethod,
1806 ];
1807 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1808 if ($reshook >= 0) {
1809 if (isset($hookmanager->resArray['bankaccountid'])) {
1810 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1811 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1812 }
1813 }
1814 if ($bankaccountid > 0) {
1815 $label = '(CustomerInvoicePayment)';
1816 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1817 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1818 }
1819 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1820 if ($result < 0) {
1821 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1822 $ispostactionok = -1;
1823 $error++;
1824 } else {
1825 $postactionmessages[] = 'Bank transaction of payment created';
1826 $ispostactionok = 1;
1827 }
1828 } else {
1829 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1830 $ispostactionok = -1;
1831 $error++;
1832 }
1833 }
1834
1835 if (!$error) {
1836 $db->commit();
1837 } else {
1838 $db->rollback();
1839 }
1840 } else {
1841 $msg = 'Failed to create invoice form contract ' . $tmptag['CON'];
1842 if (!empty($cols)) {
1843 $msg .= ' and col '. $cols .'.';
1844 }
1845 $postactionmessages[] = $msg;
1846 $ispostactionok = -1;
1847 }
1848 } else {
1849 $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.';
1850 $ispostactionok = -1;
1851 }
1852 } else {
1853 $postactionmessages[] = 'Invoice module is not enable';
1854 $ispostactionok = -1;
1855 }
1856 } else {
1857 $msg = 'Contract paid ' . $tmptag['CON'] . ' was not found';
1858 if (!empty($cols)) {
1859 $msg .= ' for col '.$tmptag['COL'] .'.';
1860 }
1861 $postactionmessages[] = $msg;
1862 $ispostactionok = -1;
1863 }
1864 } else {
1865 // Nothing done
1866 }
1867}
1868
1869if ($ispaymentok) {
1870 // Get on url call
1871 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
1872 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
1873 // Set by newpayment.php
1874 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
1875 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '': $_SESSION["FinalPaymentAmt"];
1876 $paymentType = empty($_SESSION['PaymentType']) ? '' : $_SESSION['PaymentType']; // Seems used by paypal only
1877
1878 if (is_object($object) && method_exists($object, 'call_trigger')) {
1879 // Call trigger
1880 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
1881 if ($result < 0) {
1882 $error++;
1883 }
1884 // End call triggers
1885 } elseif (get_class($object) == 'stdClass') {
1886 //In some case $object is not instantiate (for paiement on custom object) We need to deal with payment
1887 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1888 $paiement = new Paiement($db);
1889 $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
1890 if ($result < 0) {
1891 $error++;
1892 }
1893 }
1894}
1895
1896
1897// Show result message
1898if (empty($doactionsthenredirect)) {
1899 if ($ispaymentok) {
1900 print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
1901 if ($TRANSACTIONID) {
1902 print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n";
1903 }
1904
1905 // Show a custom message
1906 $key = 'ONLINE_PAYMENT_MESSAGE_OK';
1907 if (getDolGlobalString($key)) {
1908 print '<br>';
1909 print getDolGlobalString($key);
1910 }
1911 } else {
1912 print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
1913 print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
1914 print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
1915 print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
1916 print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
1917
1918 if ($mysoc->email) {
1919 print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
1920 }
1921 }
1922}
1923
1924
1925// Send email
1926if ($ispaymentok) {
1927 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
1928
1929 $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
1930
1931 dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
1932
1933 // Send an email to the admins
1934 if ($sendemail) {
1935 $companylangs = new Translate('', $conf);
1936 $companylangs->setDefaultLang($mysoc->default_lang);
1937 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
1938
1939 $sendto = $sendemail;
1940 $from = getDolGlobalString('MAILING_EMAIL_FROM') ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1941 // Define $urlwithroot
1942 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1943 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1944 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1945
1946 // Define link to login card
1947
1948 $urlback = $_SERVER["REQUEST_URI"];
1949 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
1950 $content = "";
1951 if (array_key_exists('MEM', $tmptag)) {
1952 $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
1953 $content .= '<strong>'.$companylangs->trans("PaymentSubscription")."</strong><br><br>\n";
1954 $content .= $companylangs->trans("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
1955 $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
1956 } elseif (array_key_exists('INV', $tmptag)) {
1957 $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
1958 $content .= '<strong>'.$companylangs->trans("Payment")."</strong><br><br>\n";
1959 $content .= $companylangs->trans("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
1960 //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
1961 $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
1962 } else {
1963 $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
1964 }
1965 $content .= $companylangs->transnoentities("PostActionAfterPayment").' : ';
1966 if ($ispostactionok > 0) {
1967 //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
1968 $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
1969 } elseif ($ispostactionok == 0) {
1970 $content .= $companylangs->transnoentitiesnoconv("None");
1971 } else {
1972 $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
1973 $content .= '<span class="star">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
1974 }
1975 $content .= '<br>'."\n";
1976 foreach ($postactionmessages as $postactionmessage) {
1977 $content .= ' * '.$postactionmessage.'<br>'."\n";
1978 }
1979 if ($ispostactionok < 0) {
1980 $content .= $langs->transnoentities("ARollbackWasPerformedOnPostActions");
1981 }
1982 $content .= '<br>'."\n";
1983
1984 $content .= "<br>\n";
1985 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
1986 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
1987 $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
1988 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
1989 $content .= "<br>\n";
1990 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
1991
1992 if (!empty($ErrorCode)) {
1993 $content .= "ErrorCode = ".$ErrorCode."<br>\n";
1994 }
1995 if (!empty($ErrorShortMsg)) {
1996 $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
1997 }
1998 if (!empty($ErrorLongMsg)) {
1999 $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
2000 }
2001 if (!empty($ErrorSeverityCode)) {
2002 $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
2003 }
2004
2005
2006 $ishtml = dol_textishtml($content); // May contain urls
2007 $trackid = '';
2008
2009 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2010 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml, '', '', $trackid, '', 'standard');
2011
2012 $result = $mailfile->sendfile();
2013 if ($result) {
2014 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2015 //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
2016 } else {
2017 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2018 //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
2019 }
2020 }
2021} else {
2022 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
2023
2024 // Get on url call
2025 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
2026 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
2027 // Set by newpayment.php
2028 $paymentType = $_SESSION['PaymentType'];
2029 $currencyCodeType = $_SESSION['currencyCodeType'];
2030 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
2031
2032 if (is_object($object) && method_exists($object, 'call_trigger')) {
2033 // Call trigger
2034 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
2035 if ($result < 0) {
2036 $error++;
2037 }
2038 // End call triggers
2039 }
2040
2041 // Send warning of error to administrator
2042 if ($sendemail) {
2043 $companylangs = new Translate('', $conf);
2044 $companylangs->setDefaultLang($mysoc->default_lang);
2045 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
2046
2047 $sendto = $sendemail;
2048 $from = getDolGlobalString('MAILING_EMAIL_FROM') ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
2049 // Define $urlwithroot
2050 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2051 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2052 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2053
2054 $urlback = $_SERVER["REQUEST_URI"];
2055 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
2056 $content = "";
2057 $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
2058
2059 $content .= "<br><br>\n";
2060 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
2061 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
2062 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
2063 $content .= "<br>\n";
2064 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
2065
2066
2067 $ishtml = dol_textishtml($content); // May contain urls
2068 $trackid = '';
2069
2070 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2071 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml, '', '', $trackid, '', 'standard');
2072
2073 $result = $mailfile->sendfile();
2074 if ($result) {
2075 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2076 } else {
2077 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2078 }
2079 }
2080}
2081
2082
2083// Clean session variables to avoid duplicate actions if post is resent
2084unset($_SESSION["FinalPaymentAmt"]);
2085unset($_SESSION["TRANSACTIONID"]);
2086
2087
2088// Close page content id="dolpaymentdiv"
2089if (empty($doactionsthenredirect)) {
2090 print "\n</div>\n";
2091
2092 print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag($paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
2093}
2094
2095
2096// Show footer
2097if (empty($doactionsthenredirect)) {
2098 htmlPrintOnlineFooter($mysoc, $langs, 0, $suffix);
2099
2100 llxFooter('', 'public');
2101}
2102
2103
2104$db->close();
2105
2106
2107// If option to do a redirect somewhere else.
2108if (!empty($doactionsthenredirect)) {
2109 if ($ispaymentok) {
2110 // Redirect to a success page
2111 // Paymentok page must be created for the specific website
2112 $ext_urlok = DOL_URL_ROOT.'/public/website/index.php?website='.urlencode($ws).'&pageref=paymentok&fulltag='.$FULLTAG;
2113 print "<script>window.top.location.href = '".dol_escape_js($ext_urlok) ."';</script>";
2114 } else {
2115 // Redirect to an error page
2116 // Paymentko page must be created for the specific website
2117 $ext_urlko = DOL_URL_ROOT.'/public/website/index.php?website='.urlencode($ws).'&pageref=paymentko&fulltag='.$FULLTAG;
2118 print "<script>window.top.location.href = '".dol_escape_js($ext_urlko)."';</script>";
2119 }
2120}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader()
Empty header.
Definition wrapper.php:55
llxFooter()
Empty footer.
Definition wrapper.php:69
Class to manage members of a foundation.
Class to manage members type.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage customers orders.
Class for ConferenceOrBoothAttendee.
Class for ConferenceOrBooth.
Class to manage contracts.
Class to manage donations.
Definition don.class.php:41
Class to manage invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
Class to manage hooks.
Class to manage payments of customer invoices.
Class to manage payments of donations.
Class to manage third parties objects (customers, suppliers, prospects...)
Stripe class @TODO No reason to extends CommonObject.
Class to manage translations.
Class to manage Dolibarr users.
htmlPrintOnlineFooter($fromcompany, $langs, $addformmessage=0, $suffix='', $object=null)
Show footer of company in HTML pages.
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:594
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:124
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0)
Return file(s) into a directory (by default most recent)
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag)
Validate payment.
getDetails($token)
Prepares the parameters for the GetExpressCheckoutDetails API Call.
httponly_accessforbidden($message='1', $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.