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