-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPaynlPayment.php
343 lines (288 loc) · 11.2 KB
/
PaynlPayment.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
<?php
namespace PaynlPayment;
/**
* The plugin can be installed via composer or via the package file.
* When installed via composer, the sdk is automaticly loaded in the vendor directory.
* In the package file this is included, but need to be loaded
*/
if (!class_exists('\Paynl\Config') && file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once(__DIR__ . '/vendor/autoload.php');
}
use Doctrine\ORM\Tools\SchemaTool;
use Paynl\Paymentmethods;
use PaynlPayment\Components\Config;
use PaynlPayment\Helpers\ExtraFieldsHelper;
use PaynlPayment\Helpers\PaynlPaymentLoggerHelper;
use PaynlPayment\Models\Banks\Banks;
use PaynlPayment\Models\Transaction;
use Psr\Log\LoggerInterface;
use Shopware\Components\Model\ModelManager;
use Shopware\Components\Plugin;
use Shopware\Components\Plugin\Context\ActivateContext;
use Shopware\Components\Plugin\Context\DeactivateContext;
use Shopware\Components\Plugin\Context\InstallContext;
use Shopware\Components\Plugin\Context\UninstallContext;
use Shopware\Components\Plugin\Context\UpdateContext;
class PaynlPayment extends Plugin
{
const PAYMENT_METHODS_TEMPLATES_DIRECTORY = __DIR__ . '/Resources/views/frontend/plugins/payment/';
const PLUGIN_NAME = 'PaynlPayment';
const IDEAL_ID = 10;
/**
* @param InstallContext $context
*/
public function install(InstallContext $context)
{
$this->createTables();
$this->addUserAttributeColumn();
$this->initPaymentIdIncrementer();
$this->migrate();
parent::install($context);
}
/**
* @param UpdateContext $context
*/
public function update(UpdateContext $context)
{
$this->createTables();
$this->initPaymentIdIncrementer();
$this->migrate();
parent::update($context);
}
/**
* @param UninstallContext $context
*/
public function uninstall(UninstallContext $context)
{
$this->disablePaymentMethods($context->getPlugin());
if (!$context->keepUserData()) {
$this->removeAllTables();
}
$this->removeAttributeColumns();
parent::uninstall($context);
}
private function removeAllTables()
{
try {
$db = $this->container->get('db');
$db->executeQuery('DROP TABLE IF EXISTS `paynl_transactions`');
$db->executeQuery('DROP TABLE IF EXISTS `s_plugin_paynlpayment_transactions`');
$db->executeQuery('DROP TABLE IF EXISTS `s_plugin_paynlpayment_payment_method_banks`');
} catch (\Exception $e) {
$this->getPaynlPaymentLoggerHelper()->addError('PAY. Uninstall: ' . $e->getMessage());
}
}
/**
* @param ActivateContext $context
* @throws \Exception
*/
public function activate(ActivateContext $context)
{
$plugin = $context->getPlugin();
$this->disablePaymentMethods($plugin);
$this->installPaymentMethods($plugin);
parent::activate($context);
$context->scheduleClearCache(ActivateContext::CACHE_LIST_ALL);
}
/**
* @param DeactivateContext $context
*/
public function deactivate(DeactivateContext $context)
{
$this->disablePaymentMethods($context->getPlugin());
parent::deactivate($context);
}
public static function getSubscribedEvents()
{
return [
'Enlight_Controller_Front_StartDispatch' => 'requireAutoloader',
];
}
/**
* Require composer autoloader
*/
public function requireAutoloader()
{
if (file_exists($this->getPath() . '/vendor/autoload.php')) {
require_once($this->getPath() . '/vendor/autoload.php');
}
}
/**
* @param \Shopware\Models\Plugin\Plugin $plugin
*/
private function disablePaymentMethods(\Shopware\Models\Plugin\Plugin $plugin)
{
$em = $this->container->get('models');
$payments = $plugin->getPayments();
foreach ($payments as $payment) {
$payment->setActive(false);
}
$em->flush();
}
/**
* @param \Shopware\Models\Plugin\Plugin $plugin
* @throws \Exception
*/
private function installPaymentMethods(\Shopware\Models\Plugin\Plugin $plugin)
{
/** @var Config $config */
$config = $this->getPaynlPaymentConfig();
try {
$config->loginSDK();
$methods = Paymentmethods::getList();
} catch (\Exception $e) {
$this->getPaynlPaymentLoggerHelper()->addNotice('PAY.: Activation error: ' . $e->getMessage());
throw new \Exception('Activation error. Please enter valid: Token-Code, API-token and Service-ID');
}
/** @var Shopware\Components\Plugin\PaymentInstaller $installer */
$installer = $this->container->get('shopware.plugin_payment_installer');
/** @var ModelManager $modelManager */
$modelManager = $this->container->get('models');
$paymentMethodBanks = $modelManager->getRepository(Banks::class);
foreach ($methods as $method) {
$options = [
'name' => sprintf('paynl_%s', $method['id']),
'class' => isset($method['brand']['id']) ? $method['brand']['id'] : '',
'description' => $method['name'],
'action' => 'PaynlPayment',
'active' => true,
'additionalDescription' =>
isset($method['brand']['public_description']) ? $method['brand']['public_description'] : ''
];
$pluginTemplateName = sprintf('%d.%s', (int)$method['id'], 'tpl');
if (is_file(self:: PAYMENT_METHODS_TEMPLATES_DIRECTORY . $pluginTemplateName)) {
$options['template'] = $pluginTemplateName;
}
$installer->createOrUpdate($plugin->getName(), $options);
if ((int)$method['id'] === self::IDEAL_ID && !empty($method['banks'])) {
$paymentMethodBanks->upsert($method['id'], $method['banks']);
}
}
}
/**
* Create tables required for this plugin
*/
private function createTables()
{
$modelManager = $this->container->get('models');
$tool = new SchemaTool($modelManager);
$classes = $this->getClasses($modelManager);
$tool->updateSchema($classes, true);
}
/**
* Get the model classes for this plugin
*
* @param ModelManager $modelManager
* @return array
*/
private function getClasses(ModelManager $modelManager)
{
return [
$modelManager->getClassMetadata(Transaction\Transaction::class),
$modelManager->getClassMetadata(Banks::class)
];
}
private function initPaymentIdIncrementer()
{
$db = $this->container->get('db');
$name = 'paynl_payment_id';
$rows = $db->executeQuery('SELECT * FROM s_order_number WHERE name = :name', ['name' => $name])->fetchAll();
if (count($rows) < 1) {
$db->executeQuery('INSERT INTO `s_order_number` (`number`, `name`, `desc`) VALUES (:number, :name, :description)', [
'number' => 1000000,
'name' => $name,
'description' => 'Payment id for pay.nl payments'
]);
}
}
private function migrate()
{
$db = $this->container->get('db');
try {
$bRenamed = false;
$db->executeQuery('SELECT 1 FROM `paynl_transactions` LIMIT 1');
try {
$db->executeQuery('SELECT 1 FROM `s_plugin_paynlpayment_transactions` LIMIT 1');
} catch (\Exception $e) {
$db->executeQuery('RENAME TABLE `paynl_transactions` TO `s_plugin_paynlpayment_transactions`');
$db->executeQuery('ALTER TABLE `s_plugin_paynlpayment_transactions` ADD `s_comment` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `exceptions`');
$db->executeQuery('ALTER TABLE `s_plugin_paynlpayment_transactions` ADD `s_dispatch` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `s_comment`');
$bRenamed = true;
}
# If `paynl_transacions` didnt exist, it would've generated an exception by now and next two queries will not be executed .
if ($bRenamed === false) {
$db->executeQuery('INSERT IGNORE INTO `s_plugin_paynlpayment_transactions` (paynl_payment_id, transaction_id, signature, amount, currency, created_at, updated_at, customer_id, order_id, payment_id, status_id)
SELECT `paynl_payment_id`, `transaction_id`, `signature`, `amount`, `currency`, `created_at`, `updated_at`, `customer_id`, `order_id`, `payment_id`, `status_id` FROM `paynl_transactions`');
$db->executeQuery('DROP TABLE `paynl_transactions` ');
}
} catch (\Exception $exception) {
$logMessage = sprintf(
'PAY.: Migration: %s in %s:%s Stack trace: %s',
$exception->getMessage(),
$exception->getFile(),
$exception->getLine(),
$exception->getTraceAsString()
);
$this->getPaynlPaymentLoggerHelper()->addNotice($logMessage);
}
}
private function addUserAttributeColumn()
{
$crudService = $this->container->get('shopware_attribute.crud_service');
if (!$this->columnExists(ExtraFieldsHelper::USER_ATTRIBUTES_TABLE, ExtraFieldsHelper::EXTRA_FIELD_COLUMN)) {
$crudService->update(
ExtraFieldsHelper::USER_ATTRIBUTES_TABLE,
ExtraFieldsHelper::EXTRA_FIELD_COLUMN,
'json',
[]
);
$this->rebuildAttributeModels([ExtraFieldsHelper::USER_ATTRIBUTES_TABLE]);
}
}
/**
* Remove extra attribute columns
*/
private function removeAttributeColumns()
{
$crudService = $this->container->get('shopware_attribute.crud_service');
if ($this->columnExists(ExtraFieldsHelper::USER_ATTRIBUTES_TABLE, ExtraFieldsHelper::EXTRA_FIELD_COLUMN)) {
$crudService->delete(ExtraFieldsHelper::USER_ATTRIBUTES_TABLE, ExtraFieldsHelper::EXTRA_FIELD_COLUMN);
$this->rebuildAttributeModels([ExtraFieldsHelper::USER_ATTRIBUTES_TABLE]);
}
}
/**
* @param string $table
* @param string $columnName
* @return bool
*/
private function columnExists(string $table, string $columnName)
{
$crudService = $this->container->get('shopware_attribute.crud_service');
$column = $crudService->get($table, $columnName);
return !empty($column);
}
/**
* @param array $tables
*/
private function rebuildAttributeModels(array $tables)
{
$em = $this->container->get('models');
$metaDataCache = $em->getConfiguration()->getMetadataCacheImpl();
$metaDataCache->deleteAll();
$em->generateAttributeModels($tables);
}
/**
* @return LoggerInterface
*/
private function getPaynlPaymentLoggerHelper()
{
return new PaynlPaymentLoggerHelper($this->container->get('pluginlogger'));
}
/**
* @return Config
*/
private function getPaynlPaymentConfig()
{
return new Config($this->container->get('shopware.plugin.config_reader'));
}
}