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