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