-
Notifications
You must be signed in to change notification settings - Fork 17
/
Payzen.php
505 lines (420 loc) · 19.6 KB
/
Payzen.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : [email protected] */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Payzen;
use Exception;
use InvalidArgumentException;
use Payzen\Model\Map\PayzenConfigTableMap;
use Payzen\Model\PayzenConfigQuery;
use Payzen\Payzen\PayzenCurrency;
use Payzen\Payzen\PayzenField;
use Payzen\Payzen\PayzenMultiApi;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Propel;
use Symfony\Component\DependencyInjection\Loader\Configurator\ServicesConfigurator;
use Symfony\Component\Filesystem\Filesystem;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Translation\Translator;
use Thelia\Exception\TheliaProcessException;
use Thelia\Install\Database;
use Thelia\Model\Base\CountryQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Model\Lang;
use Thelia\Model\LangQuery;
use Thelia\Model\Message;
use Thelia\Model\MessageQuery;
use Thelia\Model\ModuleImageQuery;
use Thelia\Model\Order;
use Thelia\Module\AbstractPaymentModule;
/**
* Payzen payment module
*
* @author Franck Allimant <[email protected]>
*/
class Payzen extends AbstractPaymentModule
{
/** The module domain for internationalization */
public const MODULE_DOMAIN = "payzen";
/**
* The confirmation message identifier
*/
public const CONFIRMATION_MESSAGE_NAME = 'payzen_payment_confirmation';
/** @var ?Translator $translator */
protected ?Translator $translator = null;
protected function trans($id, $locale, $parameters = []): string
{
if ($this->translator === null) {
$this->translator = Translator::getInstance();
}
return $this->translator->trans($id, $parameters, self::MODULE_DOMAIN, $locale);
}
/**
* @param ConnectionInterface|null $con
* @throws PropelException
* @throws Exception
*/
public function postActivation(ConnectionInterface $con = null): void
{
// Once activated, create the module schema in the Thelia database.
$database = new Database($con);
try {
PayzenConfigQuery::create()->findOne();
} catch (Exception) {
$database->insertSql(null, array(
__DIR__ . DS . 'Config'.DS.'TheliaMain.sql' // The module schema
));
}
$languages = LangQuery::create()->find();
if (null === MessageQuery::create()->findOneByName(self::CONFIRMATION_MESSAGE_NAME)) {
$message = new Message();
$message
->setName(self::CONFIRMATION_MESSAGE_NAME)
->setHtmlLayoutFileName('')
->setHtmlTemplateFileName(self::CONFIRMATION_MESSAGE_NAME.'.html')
->setTextLayoutFileName('')
->setTextTemplateFileName(self::CONFIRMATION_MESSAGE_NAME.'.txt')
;
foreach ($languages as $language) {
/** @var Lang $language */
$locale = $language->getLocale();
$message->setLocale($locale);
$message->setTitle(
$this->trans('Order payment confirmation', $locale)
);
$message->setSubject(
$this->trans('Order {$order_ref} payment confirmation', $locale)
);
}
$message->save();
}
/* Deploy the module's image */
$module = $this->getModuleModel();
if (ModuleImageQuery::create()->filterByModule($module)->count() === 0) {
$this->deployImageFolder($module, sprintf('%s/images', __DIR__), $con);
}
}
public function update($currentVersion, $newVersion, ConnectionInterface $con = null): void
{
if (0 === version_compare($newVersion, '1.3.1')) {
PayzenConfigQuery::set('send_confirmation_message_only_if_paid', false);
PayzenConfigQuery::set('send_payment_confirmation_message', true);
// Remove the AdminIncludes directory, and the unused files.
// @see https://github.com/thelia-modules/Payzen/issues/19
$fs = new Filesystem();
$filesToRemove = [
__DIR__ . "/AdminIncludes",
__DIR__ . "/templates/backOffice/default/payzen/form-field-template.html",
__DIR__ . "/I18n/AdminIncludes"
];
try {
foreach ($filesToRemove as $file) {
if ($fs->exists($file)) {
$fs->remove($file);
}
}
} catch (Exception $ex) {
throw new TheliaProcessException(
Translator::getInstance()->trans(
"Failed to delete obsolete files. You should delete manually the following files and directories for the Payzen module to work properly: %files",
[ 'files' => implode(", ", $filesToRemove) ]
),
null,
null,
$ex
);
}
}
parent::update($currentVersion, $newVersion, $con);
}
/**
* @param ConnectionInterface|null $con
* @param bool $deleteModuleData
* @throws PropelException
*/
public function destroy(ConnectionInterface $con = null, $deleteModuleData = false): void
{
// Delete config table and messages if required
if ($deleteModuleData) {
$database = new Database($con);
$database->execute("DROP TABLE ?", PayzenConfigTableMap::TABLE_NAME);
MessageQuery::create()->findOneByName(self::CONFIRMATION_MESSAGE_NAME)?->delete();
}
}
/**
*
* Method used by payment gateway.
*
* If this method returns a \Thelia\Core\HttpFoundation\Response instance, this response is sent to the
* browser.
*
* In many cases, it's necessary to send a form to the payment gateway. On your response you can return this form already
* completed, ready to be sent
*
* @param Order $order processed order
* @return Response the HTTP response
* @throws Exception
* @throws PropelException
*/
public function pay(Order $order): Response
{
return $this->doPay($order, 'SINGLE');
}
/**
* Payment gateway invocation
*
* @param Order $order processed order
* @param string $payment_mode the payment mode, either 'SINGLE' ou 'MULTI'
* @param string $payment_mean, either SDD (SEPA) or bank cards list
* @return Response the HTTP response
* @throws Exception
* @throws PropelException
*/
protected function doPay(Order $order, string $payment_mode, string $payment_mean = ''): Response
{
$payzen_params = $this->getPayzenParameters($order, $payment_mode, $payment_mean);
// Convert files into standard var => value array
$html_params = array();
/** @var PayzenField $field */
foreach ($payzen_params as $name => $field) {
$html_params[$name] = $field->getValue();
}
// Be sure to have a valid platform URL, otherwise give up
if (false === $platformUrl = PayzenConfigQuery::read('platform_url', false)) {
throw new InvalidArgumentException(
Translator::getInstance()->trans(
"The platform URL is not defined, please check Payzen module configuration.",
[],
self::MODULE_DOMAIN
)
);
}
return $this->generateGatewayFormResponse($order, $platformUrl, $html_params);
}
/**
* @return boolean true to allow usage of this payment module, false otherwise.
*/
public function isValidPayment() :bool
{
$valid = false;
$mode = PayzenConfigQuery::read('mode', false);
// If we're in test mode, do not display Payzen on the front office, except for allowed IP addresses.
if ('TEST' === $mode) {
$raw_ips = explode("\n", PayzenConfigQuery::read('allowed_ip_list', ''));
$allowed_client_ips = array();
foreach ($raw_ips as $ip) {
$allowed_client_ips[] = trim($ip);
}
$client_ip = $this->getRequest()->getClientIp();
$valid = in_array($client_ip, $allowed_client_ips, true);
} elseif ('PRODUCTION' === $mode) {
$valid = true;
}
if ($valid) {
// Check if the total order amount is in the module's limits
$valid = $this->checkMinMaxAmount();
}
return $valid;
}
/**
* Check if the total order amount is in the module's limits
*
* @return bool true if the current order total is within the min and max limits
*/
protected function checkMinMaxAmount(): bool
{
// Check if the total order amount is in the module's limits
$order_total = $this->getCurrentOrderTotalAmount();
$min_amount = PayzenConfigQuery::read('minimum_amount', 0);
$max_amount = PayzenConfigQuery::read('maximum_amount', 0);
return $order_total > 0 && ($min_amount <= 0 || $order_total >= $min_amount) && ($max_amount <= 0 || $order_total <= $max_amount);
}
/**
* Returns the vads transaction id, that should be unique during the current day,
* and should be 6 numeric characters between 000000 and 899999
*
* @return string|null the transaction ID
* @throws Exception an exception if something goes wrong.
*/
protected function getTransactionId(): ?string
{
$con = Propel::getWriteConnection(PayzenConfigTableMap::DATABASE_NAME);
$con->beginTransaction();
try {
$trans_id = (int)PayzenConfigQuery::read('next_transaction_id', 1);
$next_trans_id = 1 + $trans_id;
if ($next_trans_id > 899999) {
$next_trans_id = 0;
}
PayzenConfigQuery::set('next_transaction_id', $next_trans_id);
$con->commit();
return sprintf("%06d", $trans_id);
} catch (Exception $ex) {
$con->rollback();
throw $ex;
}
}
/**
* Calculate the value of the vads_payment_config parameter.
*
* @param string $payment_config
* @param float $orderAmount
* @param PayzenCurrency $currency
* @return string the value for vads_payment_config parameter
*/
protected function getPaymentConfigValue(string $payment_config, float $orderAmount, PayzenCurrency $currency): string
{
if ('MULTI' === $payment_config) {
$first = $currency->convertAmountToInteger(($orderAmount*PayzenConfigQuery::read('multi_first_payment', 0))/100);
$count = PayzenConfigQuery::read('multi_number_of_payments', 4);
$interval = PayzenConfigQuery::read('multi_payments_interval', 30);
if ($first === 0) {
$first = $currency->convertAmountToInteger($orderAmount / $count);
}
return sprintf("MULTI:first=%d;count=%d;period=%d", $first, $count, $interval);
}
return $payment_config;
}
/**
* Create the form parameter list for the given order
*
* @param Order $order
* @param string $payment_config single or multiple payment - see vads_payment_config parameter description
* @param string $payment_mean SEPA or bank card - see vads_payment_cards parameter description
*
* @return array the payzen form parameters
* @throws InvalidArgumentException if an unsupported currency is used in order
* @throws Exception
* @throws PropelException
*/
protected function getPayzenParameters(Order $order, string $payment_config, string $payment_mean): array
{
$payzenApi = new PayzenMultiApi();
// Total order amount
$amount = $this->getOrderPayTotalAmount($order);
/** @var PayzenCurrency $currency */
// Currency conversion to numeric ISO 1427 code
if (null === $currency = $payzenApi->findCurrencyByAlphaCode($order->getCurrency()->getCode())) {
throw new InvalidArgumentException(Translator::getInstance()->trans(
"Unsupported order currency: '%code'",
array('%code' => $order->getCurrency()->getCode()),
self::MODULE_DOMAIN
));
}
// Check payment mean
if ($payment_mean !== 'SDD') {
$payment_mean = PayzenConfigQuery::read('allowed_cards') ?? "";
}
$customer = $order->getCustomer();
// Get customer lang code and locale
if (null !== $langObj = LangQuery::create()->findPk($customer->getLangId())) {
$customer_lang = $langObj->getCode();
$locale = $langObj->getLocale();
} else {
$customer_lang = PayzenConfigQuery::read('default_language');
$locale = LangQuery::create()->findOneByByDefault(true)?->getLocale();
}
$address = $customer->getDefaultAddress();
// Customer phone (first non-empty)
$phone = $address->getPhone();
if (empty($phone)) {
$phone = $address->getCellphone();
}
// Transaction ID
$transaction_id = $this->getTransactionId();
$order->setTransactionRef($transaction_id)->save();
$payzen_params = array(
// Static configuration variables
'vads_version' => 'V2',
'vads_contrib' => 'Thelia version ' . ConfigQuery::read('thelia_version'),
'vads_action_mode' => 'INTERACTIVE',
'vads_payment_config' => $this->getPaymentConfigValue($payment_config, $amount, $currency),
'vads_page_action' => 'PAYMENT',
'vads_return_mode' => 'POST',
'vads_shop_name' => ConfigQuery::read("store_name", ''),
'vads_url_success' => $this->getPaymentSuccessPageUrl($order->getId()),
'vads_url_refused' => $this->getPaymentFailurePageUrl(
$order->getId(),
Translator::getInstance()->trans("Your payment has been refused", [], self::MODULE_DOMAIN)
),
'vads_url_referral' => $this->getPaymentFailurePageUrl(
$order->getId(),
Translator::getInstance()->trans("Authorization request was rejected", [], self::MODULE_DOMAIN)
),
'vads_url_cancel' => $this->getPaymentFailurePageUrl(
$order->getId(),
Translator::getInstance()->trans("You canceled the payment", [], self::MODULE_DOMAIN)
),
'vads_url_error' => $this->getPaymentFailurePageUrl(
$order->getId(),
Translator::getInstance()->trans("An internal error occurred", [], self::MODULE_DOMAIN)
),
// User-defined configuration variables
'vads_site_id' => PayzenConfigQuery::read('site_id'),
'vads_key_test' => PayzenConfigQuery::read('test_certificate'),
'vads_key_prod' => PayzenConfigQuery::read('production_certificate'),
'vads_ctx_mode' => PayzenConfigQuery::read('mode'),
'vads_platform_url' => PayzenConfigQuery::read('platform_url'),
'vads_default_language' => PayzenConfigQuery::read('default_language'),
'vads_available_languages' => PayzenConfigQuery::read('available_languages'),
'vads_capture_delay' => PayzenConfigQuery::read('banking_delay'),
'vads_validation_mode' => PayzenConfigQuery::read('validation_mode'),
'vads_payment_cards' => $payment_mean,
'vads_redirect_enabled' => PayzenConfigQuery::read('redirect_enabled'),
'vads_redirect_success_timeout' => PayzenConfigQuery::read('success_timeout'),
'vads_redirect_success_message' => PayzenConfigQuery::read('success_message'),
'vads_redirect_error_timeout' => PayzenConfigQuery::read('failure_timeout'),
'vads_redirect_error_message' => PayzenConfigQuery::read('failure_message'),
// Order related configuration variables
'vads_language' => $customer_lang,
'vads_order_id' => $order->getId(), // Do not change this, as the callback uses it to find the order
'vads_currency' => $currency->num,
'vads_amount' => $currency->convertAmountToInteger($amount),
'vads_trans_id' => $transaction_id,
'vads_trans_date' => gmdate("YmdHis"),
// Activate 3D Secure ?
'vads_threeds_mpi' => $amount >= PayzenConfigQuery::read('three_ds_minimum_order_amount', 0) ? 2 : 0,
// Customer information
'vads_cust_email' => $customer->getEmail(),
'vads_cust_id' => $customer->getId(),
'vads_cust_title' => $customer->getCustomerTitle()->setLocale($locale)->getLong(),
'vads_cust_last_name' => $customer->getLastname(),
'vads_cust_first_name' => $customer->getFirstname(),
'vads_cust_address' => trim($address->getAddress1() . ' ' . $address->getAddress2() . ' ' . $address->getAddress3()),
'vads_cust_city' => $address->getCity(),
'vads_cust_zip' => $address->getZipcode(),
'vads_cust_country' => CountryQuery::create()->findPk($address->getCountryId())?->getIsoalpha2(),
'vads_cust_phone' => $phone,
);
foreach ($payzen_params as $payzen_parameter_name => $value) {
$payzenApi->set($payzen_parameter_name, $value);
}
return $payzenApi->getRequestFields();
}
public static function configureServices(ServicesConfigurator $servicesConfigurator): void
{
$servicesConfigurator->load(self::getModuleCode().'\\', __DIR__)
->exclude([THELIA_MODULE_DIR . ucfirst(self::getModuleCode()). "/I18n/*"])
->autowire()
->autoconfigure();
}
}