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