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