-
Notifications
You must be signed in to change notification settings - Fork 0
/
bienoubien.php
executable file
·1227 lines (1060 loc) · 41 KB
/
bienoubien.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* BINSHOPS REST API
*
* @author BINSHOPS | Best In Shops
* @copyright BINSHOPS | Best In Shops
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* Best In Shops eCommerce Solutions Inc.
*
*/
if (!defined('_PS_VERSION_')) {
exit;
}
require_once dirname(__FILE__) . '/classes/APIRoutes.php';
require_once(dirname(__FILE__) . '/vendor/autoload.php');
class Bienoubien extends PaymentModule
{
protected $config_form = false;
//webhook
protected $form_success = array();
protected $form_warning = array();
protected $form_error = array();
private $hooks = array(
'actionProductAdd' => 'Product Added',
'actionProductUpdate' => 'Product Updated',
'actionProductDelete' => 'Product Deleted',
'actionOrderHistoryAddAfter' => 'Order status updated',
'actionValidateOrder' => 'Order created',
'actionCustomerAccountAdd' => 'Customer created',
'actionCustomerAccountUpdate' => 'Customer updated',
'actionObjectCustomerMessageAddAfter' => 'Customer message added',
'actionCronJob' => '',
'displayBackOfficeHeader' => '',
);
public function __construct()
{
$this->name = 'bienoubien';
$this->tab = 'merchandizing';
$this->version = '1.0.11';
$this->author = 'Binshops';
$this->need_instance = 0;
/**
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Bien ou Bien');
$this->description = $this->l('Ce module permet de connecter votre boutique à la place de marché Bien ou Bien');
$this->confirmUninstall = $this->l('');
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install()
{
Configuration::updateValue('BINSHOPSREST_LIVE_MODE', false);
include(dirname(__FILE__) . '/sql/install.php');
//webhook
$webhook_secure_key = Configuration::get('WEBHOOKS_SECURE_KEY');
$cron_secure_key = Configuration::get('WEBHOOKS_CRON_SECURE_KEY');
if (false === $webhook_secure_key) {
Configuration::updateValue(
'WEBHOOKS_SECURE_KEY',
Tools::strtoupper(Tools::passwdGen(32))
);
}
if (false === $cron_secure_key) {
Configuration::updateValue(
'WEBHOOKS_CRON_SECURE_KEY',
Tools::strtoupper(Tools::passwdGen(32))
);
}
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('backOfficeHeader') && $this->registerHook('moduleRoutes') &&
$this->registerHook(array_keys($this->hooks));
}
public function uninstall()
{
Configuration::deleteByName('BINSHOPSREST_LIVE_MODE');
include(dirname(__FILE__) . '/sql/uninstall.php');
//webhook
Configuration::deleteByName('WEBHOOKS_SECURE_KEY');
Configuration::deleteByName('WEBHOOKS_CRON_SECURE_KEY');
foreach ($this->hooks as $hook => $name) {
$this->unregisterHook($hook);
}
return parent::uninstall();
}
/**
* Load the configuration form
*/
public function getContent()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitBinshopsrestModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
//webhook
// Decode messages in the URL
$messages = Tools::getValue('messages', false);
if ($messages) {
$this->unserializeMessages($messages);
}
// Create & update Webhook
if (((bool) Tools::isSubmit('submitWebhooksModule')) == true) {
$id_webhook = (int) Tools::getValue('id_webhook');
if ($id_webhook === 0) {
$this->createNewWebhook();
} else {
$this->updateWebhook($id_webhook);
}
}
// Delete Webhook
if (((bool) Tools::isSubmit('deleteWebhook')) == true) {
WebhookLogModel::deleteByWebhookId((int) Tools::getValue('id_webhook'));
WebhookQueueModel::deleteByWebhookId((int) Tools::getValue('id_webhook'));
WebhookModel::deleteById((int) Tools::getValue('id_webhook'));
$this->setSuccessMessage($this->l('Webhook was deleted.'));
return $this->redirectHome();
}
// Toggle Webhook
if (((bool) Tools::isSubmit('toggleWebhook')) == true) {
WebhookModel::changeWebhookStatus((int) Tools::getValue('id_webhook'));
$this->setSuccessMessage($this->l('Webhook status was changed.'));
return $this->redirectHome();
}
// Delete Queue
if (((bool) Tools::isSubmit('deleteQueue')) == true) {
WebhookQueueModel::deleteById((int) Tools::getValue('id_queue'));
$this->setSuccessMessage($this->l('Queued webhook was deleted.'));
return $this->redirectHome();
}
// Delete Log
if (((bool) Tools::isSubmit('deleteLog')) == true) {
WebhookLogModel::deleteById((int) Tools::getValue('id_log'));
$this->setSuccessMessage($this->l('Log entry was deleted.'));
return $this->redirectHome();
}
// View Queue
if (((bool) Tools::isSubmit('viewQueue')) == true) {
$id_queue = (int) Tools::getValue('id_queue');
return $this->renderQueueView($id_queue);
}
// View Log
if (((bool) Tools::isSubmit('viewLog')) == true) {
$id_log = (int) Tools::getValue('id_log');
return $this->renderLogView($id_log);
}
// Resend Queue
if (((bool) Tools::isSubmit('resendQueue')) == true) {
return $this->resendQueue();
}
$create_webhook_url = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name.'&token=' .
Tools::getAdminTokenLite('AdminModules') . '&createWebhook';
$cronjob_url = $this->context->link->getModuleLink(
$this->name,
'cron',
array('secure_key' => Configuration::get('WEBHOOKS_CRON_SECURE_KEY'))
);
$this->context->smarty->assign('module_dir', $this->_path);
// Messages
$this->context->smarty->assign('form_success', $this->form_success);
$this->context->smarty->assign('form_warning', $this->form_warning);
$this->context->smarty->assign('form_error', $this->form_error);
// URLS
$this->context->smarty->assign('create_webhook_url', $create_webhook_url);
$this->context->smarty->assign('cronjob_url', $cronjob_url);
$output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/base.tpl');
if (((bool) Tools::isSubmit('createWebhook')) == true ||
((bool) Tools::isSubmit('updateWebhook')) == true ||
((bool) Tools::isSubmit('submitWebhooksModule')) == true
) {
$output .= $this->renderCreateWebhookForm();
} else {
$output .= $this->context->smarty->fetch($this->local_path . 'views/templates/admin/panel.tpl');
$output .= $this->renderWebhooksList();
$output .= $this->renderQueuesList();
$output .= $this->renderLogsList();
}
return $output.$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitBinshopsrestModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
. '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon-key"></i>',
'desc' => $this->l('Copy this token and send it as request parameter in your requests'),
'name' => 'BINSHOPSREST_API_TOKEN',
'label' => $this->l('API Token'),
),
),
'submit' => array(
'title' => $this->l('Generate'),
),
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues()
{
return array(
'BINSHOPSREST_LIVE_MODE' => Configuration::get('BINSHOPSREST_LIVE_MODE', true),
'BINSHOPSREST_API_TOKEN' => Configuration::get('BINSHOPSREST_API_TOKEN', 'contact@prestashop.com'),
'BINSHOPSREST_ACCOUNT_PASSWORD' => Configuration::get('BINSHOPSREST_ACCOUNT_PASSWORD', null),
);
}
/**
* Save form data.
*/
protected function postProcess()
{
$token = $this->generateToken();
Configuration::updateValue('BINSHOPSREST_API_TOKEN', $token);
// $form_values = $this->getConfigFormValues();
//
// foreach (array_keys($form_values) as $key) {
// Configuration::updateValue($key, Tools::getValue($key));
// }
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookBackOfficeHeader()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path . 'views/js/back.js');
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
if (Tools::getValue('controller') == 'AdminModules' &&
(Tools::getValue('configure') == $this->name || Tools::getValue('module_name') == $this->name)) {
$this->context->controller->addJquery();
$this->context->controller->addJS($this->_path . 'views/js/back.js');
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*/
public function hookHeader()
{
$this->context->controller->addJS($this->_path . '/views/js/front.js');
$this->context->controller->addCSS($this->_path . '/views/css/front.css');
}
public function hookModuleRoutes()
{
return APIRoutes::getRoutes();
}
public function generateToken(){
return $this->random_str(32);
}
function random_str(
int $length = 64,
string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
if ($length < 1) {
throw new \RangeException("Length must be a positive integer");
}
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[random_int(0, $max)];
}
return implode('', $pieces);
}
/**
* ====================================================================================
* ====================================================================================
* Web Hook start
* ====================================================================================
* ====================================================================================
*/
/** ------------------------------------------------------------------------ */
/** VIEWS */
/** ------------------------------------------------------------------------ */
/**
* @param int $id_queue
* @return mixed
*/
protected function renderQueueView($id_queue)
{
$queue = WebhookQueueModel::getById((int) $id_queue);
$this->smarty->assign($queue);
return $this->display($this->local_path, 'views/templates/admin/queue/view.tpl');
}
/**
* @param int $id_queue
* @return mixed
*/
protected function renderLogView($id_queue)
{
$log = WebhookLogModel::getById((int) $id_queue);
$this->smarty->assign($log);
return $this->display($this->local_path, 'views/templates/admin/log/view.tpl');
}
/** ------------------------------------------------------------------------ */
/** LISTS */
/** ------------------------------------------------------------------------ */
/**
* Renders webhooks list
* @return mixed
*/
protected function renderWebhooksList()
{
$fields_list = array(
'id_webhook' => array(
'title' => $this->l('ID'),
'search' => false,
),
'hook' => array(
'title' => $this->l('Hook'),
'search' => false,
),
'url' => array(
'title' => $this->l('URL'),
'search' => false,
),
'real_time' => array(
'title' => $this->l('Real-time'),
'search' => false,
'type' => 'bool',
),
'retries' => array(
'title' => $this->l('Retries'),
'search' => false,
),
'active' => array(
'title' => $this->l('Status'),
'search' => false,
'type' => 'bool',
'align' => 'center',
'icon' => array(
0 => 'disabled.gif',
1 => 'enabled.gif',
'default' => 'disabled.gif'
),
),
'date_add' => array(
'title' => $this->l('Created at'),
'type' => 'datetime',
'search' => false,
),
);
if (!Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE')) {
unset($fields_list['shop_name']);
}
$helper_list = new HelperList();
$helper_list->module = $this;
$helper_list->title = $this->l('Webhooks');
$helper_list->no_link = true;
$helper_list->show_toolbar = true;
$helper_list->simple_header = false;
$helper_list->identifier = 'id_webhook';
$helper_list->table = 'Webhook';
$helper_list->currentIndex = $this->context->link->getAdminLink('AdminModules', false) .
'&configure=' . $this->name;
$helper_list->token = Tools::getAdminTokenLite('AdminModules');
$helper_list->actions = array('edit', 'toggleStatus', 'delete');
$helper_list->shopLinkType = '';
// This is needed for displayEnableLink to avoid code duplication
$this->_helperlist = $helper_list;
/* Retrieve list data */
$helper_list->listTotal = WebhookModel::getWebhooksTotal();
/* Paginate the result */
$page = ($page = Tools::getValue('submitFilter' . $helper_list->table)) ? $page : 1;
$pagination = ($pagination = Tools::getValue($helper_list->table . '_pagination')) ? $pagination : 50;
$logs = WebhookModel::getWebhooks($page, $pagination);
return $helper_list->generateList($logs, $fields_list);
}
/**
* Renders webhooks list
* @return mixed
*/
protected function renderQueuesList()
{
$fields_list = array(
'id_queue' => array(
'title' => $this->l('Queue ID'),
'search' => false,
),
'id_webhook' => array(
'title' => $this->l('Webhook ID'),
'search' => false,
),
'url' => array(
'title' => $this->l('URL'),
'search' => false,
),
'executed' => array(
'title' => $this->l('Executed'),
'search' => false,
'type' => 'bool',
'align' => 'center',
'icon' => array(
0 => 'disabled.gif',
1 => 'enabled.gif',
'default' => 'disabled.gif'
),
),
'retry' => array(
'title' => $this->l('Retries'),
'search' => false,
),
'date_add' => array(
'title' => $this->l('Queued at'),
'type' => 'datetime',
'search' => false,
),
);
if (!Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE')) {
unset($fields_list['shop_name']);
}
$helper_list = new HelperList();
$helper_list->module = $this;
$helper_list->title = $this->l('Queued webhooks');
$helper_list->no_link = true;
$helper_list->show_toolbar = true;
$helper_list->simple_header = false;
$helper_list->identifier = 'id_queue';
$helper_list->table = 'Queue';
$helper_list->currentIndex = $this->context->link->getAdminLink('AdminModules', false) .
'&configure=' . $this->name;
$helper_list->token = Tools::getAdminTokenLite('AdminModules');
$helper_list->actions = array('view', 'resend', 'delete');
$helper_list->shopLinkType = '';
// This is needed for displayEnableLink to avoid code duplication
$this->_helperlist = $helper_list;
/* Retrieve list data */
$helper_list->listTotal = WebhookQueueModel::getQueuesTotal();
if ($helper_list->listTotal === 0) {
return "";
}
/* Paginate the result */
$page = ($page = Tools::getValue('submitFilter' . $helper_list->table)) ? $page : 1;
$pagination = ($pagination = Tools::getValue($helper_list->table . '_pagination')) ? $pagination : 50;
$logs = WebhookQueueModel::getQueues($page, $pagination);
return $helper_list->generateList($logs, $fields_list);
}
/**
* Renders the logs list
* @return mixed
*/
protected function renderLogsList()
{
$fields_list = array(
'id_log' => array(
'title' => $this->l('ID'),
'search' => false,
),
'id_webhook' => array(
'title' => $this->l('Webhook ID'),
'search' => false,
),
'real_time' => array(
'title' => $this->l('Real-time'),
'search' => false,
'type' => 'bool',
),
'url' => array(
'title' => $this->l('URL'),
'search' => false,
),
'status_code' => array(
'title' => $this->l('Status'),
'search' => false,
),
'date_add' => array(
'title' => $this->l('Created at'),
'type' => 'datetime',
'search' => false,
),
);
if (!Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE')) {
unset($fields_list['shop_name']);
}
$helper_list = new HelperList();
$helper_list->module = $this;
$helper_list->title = $this->l('Execution Logs');
$helper_list->no_link = true;
$helper_list->show_toolbar = true;
$helper_list->simple_header = false;
$helper_list->identifier = 'id_log';
$helper_list->table = 'Log';
$helper_list->currentIndex = $this->context->link->getAdminLink('AdminModules', false) .
'&configure=' . $this->name;
$helper_list->token = Tools::getAdminTokenLite('AdminModules');
$helper_list->actions = array('view', 'delete');
$helper_list->shopLinkType = '';
// This is needed for displayEnableLink to avoid code duplication
$this->_helperlist = $helper_list;
/* Retrieve list data */
$helper_list->listTotal = WebhookLogModel::getLogsTotal();
if ($helper_list->listTotal === 0) {
return "";
}
/* Paginate the result */
$page = ($page = Tools::getValue('submitFilter' . $helper_list->table)) ? $page : 1;
$pagination = ($pagination = Tools::getValue($helper_list->table . '_pagination')) ? $pagination : 50;
$logs = WebhookLogModel::getLogs($page, $pagination);
return $helper_list->generateList($logs, $fields_list);
}
/**
* Resend link in Queues
* @param null $token
* @param int $id
* @param null $name
* @return mixed
*/
public function displayResendLink($token = null, $id = -1, $name = null)
{
$query = http_build_query(array(
'configure' => $this->name,
'id_queue' => (int) $id,
'token' => $token,
'resendQueue' => true,
));
$this->context->smarty->assign(array(
'location_ok' => $this->context->link->getAdminLink('AdminModules', false) . '&' . $query,
'location_ko' => 'javascript:void(0)',
'action' => $this->l('Resend'),
'confirm' => $this->l('Are you sure you want to re-send this webhook?'),
));
return $this->display($this->local_path, 'views/templates/admin/actions/resend.tpl');
}
/**
* Toggle status of webhooks
* @param null $token
* @param int $id
* @param null $name
* @return mixed
*/
public function displayToggleStatusLink($token = null, $id = -1, $name = null)
{
$query = http_build_query(array(
'configure' => $this->name,
'id_webhook' => (int) $id,
'token' => $token,
'toggleWebhook' => true,
));
$this->context->smarty->assign(array(
'location_ok' => $this->context->link->getAdminLink('AdminModules', false) . '&' . $query,
'location_ko' => 'javascript:void(0)',
'action' => $this->l('Toggle status'),
'confirm' => $this->l('Are you sure you want to change this webhook status?'),
));
return $this->display($this->local_path, 'views/templates/admin/actions/toggle.tpl');
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderCreateWebhookForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitWebhooksModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValuesWebhook(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigFormWebhook()));
}
/**
* Creates a new webhook
*/
protected function createNewWebhook()
{
// Sanitize URL
$url = filter_var(Tools::getValue('WEBHOOKS_URL'), FILTER_SANITIZE_URL);
if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
$this->setErrorMessage($this->l('The URL is invalid'));
} elseif (!Validate::isHookName(Tools::getValue('WEBHOOKS_HOOK'))) {
$this->setErrorMessage($this->l('Hook name is invalid'));
} elseif (!Validate::isUnsignedInt(Tools::getValue('WEBHOOKS_RETRIES')) ||
((int) Tools::getValue('WEBHOOKS_RETRIES')) > 99) {
$this->setErrorMessage($this->l('Please choose a retry number between 0 and 99'));
} else {
WebhookModel::insertWebhook(
$url,
Tools::getValue('WEBHOOKS_HOOK'),
Tools::getValue('WEBHOOKS_REAL_TIME', 0),
(int)Tools::getValue('WEBHOOKS_RETRIES'),
1
);
$this->setSuccessMessage($this->l('Webhook inserted'));
return $this->redirectHome();
}
}
/**
* Updates a webhook
* @param $id_webhook
* @return mixed
*/
protected function updateWebhook($id_webhook)
{
// Sanitize URL
$url = filter_var(Tools::getValue('WEBHOOKS_URL'), FILTER_SANITIZE_URL);
if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
$this->setErrorMessage($this->l('The URL is invalid'));
} elseif (!Validate::isHookName(Tools::getValue('WEBHOOKS_HOOK'))) {
$this->setErrorMessage($this->l('Hook name is invalid'));
} elseif (!Validate::isUnsignedInt(Tools::getValue('WEBHOOKS_RETRIES')) ||
((int) Tools::getValue('WEBHOOKS_RETRIES')) > 99) {
$this->setErrorMessage($this->l('Please choose a retry number between 0 and 99'));
} else {
WebhookModel::updateWebhook(
$id_webhook,
$url,
Tools::getValue('WEBHOOKS_HOOK'),
Tools::getValue('WEBHOOKS_REAL_TIME', 0),
(int)Tools::getValue('WEBHOOKS_RETRIES')
);
$this->setSuccessMessage($this->l('Webhook updated'));
return $this->redirectHome();
}
}
/**
* @return mixed
*/
protected function resendQueue()
{
$id_queue = (int) Tools::getValue('id_queue');
$queue = WebhookQueueModel::getById($id_queue);
$webhook = WebhookModel::getById((int) $queue['id_webhook']);
$payload = Tools::jsonDecode($queue['payload']);
WebhookQueueModel::incrementRetry($id_queue);
try {
$this->makeRequest($webhook, $payload);
$this->setSuccessMessage($this->l('Webhook was executed!'));
} catch (Exception $e) {
$this->setErrorMessage($this->l('There was an error executing the Webhook! ' . $e->getMessage()));
}
return $this->redirectHome();
}
/** ------------------------------------------------------------------------ */
/** REQUESTS & QUEUEING */
/** ------------------------------------------------------------------------ */
/**
* Actually makes the webhook request
* @param WebhookModel $webhook
* @param mixed $payload
* @throws Exception
* @return void
*/
private function makeRequest($webhook, $payload)
{
$response = \Httpful\Request::post($webhook['url'])
->withoutStrictSsl()
->withXSecureKey(Configuration::get('WEBHOOKS_SECURE_KEY'))
->withXHook($webhook['hook'])
->withXHookId($webhook['id_webhook'])
->sendsJson()
->body(Tools::jsonEncode($payload))
->send();
WebhookLogModel::insertLog($webhook, $payload, $response->body, $response->code);
// 200; 201; 202; 203; 204
if ($response->code < 200 || $response->code > 204) {
throw new Exception("Error: expected HTTP 2XX status code response but got {$response->code}.");
}
}
/**
* Fires the webhook and logs or queue if it fails
*
* @param WebhookModel $webhook
* @param mixed $payload
* @return void
* @throws Exception
*/
private function fireWebhook($webhook, $payload)
{
try {
$this->makeRequest($webhook, $payload);
} catch (Exception $e) {
$this->queueWebhook($webhook, $payload);
// PrestaShopLogger::addLog(var_export($e, true), 1);
}
}
/**
* Dispatch the execution of the webhook depending on the type of webhook
*
* @param WebhookModel $webhook
* @param mixed $payload
* @throws Exception
*/
private function dispatchWebhook($webhook, $payload)
{
PrestaShopLogger::addLog(
'dispatchWebhook ' . $webhook['hook'] . ' with ID ' . $webhook['id_webhook'],
1
);
$payload = $this->decoratePayload($webhook['hook'], $payload);
if ($webhook['real_time']) {
$this->fireWebhook($webhook, $payload);
} else {
$this->queueWebhook($webhook, $payload);
}
}
/**
* Queues the webhook in the DB for later
*
* @param WebhookModel $webhook
* @param mixed $payload
* @return void
*/
private function queueWebhook($webhook, $payload)
{
WebhookQueueModel::insertQueue($webhook, $payload);
}
/**
* Decorate payload and transform into stdClass
*
* @param string $hook
* @param mixed $payload
* @throws Exception
* @return mixed
*/
private function decoratePayload($hook, $payload)
{
// Transform payload into stdClass
$payload = Tools::jsonDecode(Tools::jsonEncode($payload));
if (WebhookDecorator::hasDecorator($hook)) {
try {
$decoratorClass = WebhookDecorator::getDecoratorClass($hook);
$decoratorValue = WebhookDecorator::getDecoratorValue($hook, $payload);
$enhancer = new $decoratorClass($decoratorValue, $payload);
$payload = $enhancer->present();
return $payload;
} catch (Exception $e) {
PrestaShopLogger::addLog(var_export($e, true), 1);
}
}
return $payload;
}
/**
* Prestashop own function for cron frequency
*
* @return array
*/
public function getCronFrequency()
{
return array(
'hour' => '-1',
'day' => '-1',
'month' => '-1',
'day_of_week' => '-1'
);
}
/** ------------------------------------------------------------------------ */
/** ALL HOOKS BELLOW */
/** ------------------------------------------------------------------------ */
public function hookActionValidateOrder($params)
{
$webhooks = WebhookModel::getWebhooksByHook('actionValidateOrder');
foreach ($webhooks as $webhook) {
$this->dispatchWebhook($webhook, $params);
}
}
public function hookActionOrderHistoryAddAfter($params)
{
$webhooks = WebhookModel::getWebhooksByHook('actionOrderHistoryAddAfter');
foreach ($webhooks as $webhook) {
$this->dispatchWebhook($webhook, $params);
}
}
public function hookActionProductAdded($params)
{
$webhooks = WebhookModel::getWebhooksByHook('actionProductAdd');
foreach ($webhooks as $webhook) {
$this->dispatchWebhook($webhook, $params);
}
}
public function hookActionProductUpdate($params)
{
$webhooks = WebhookModel::getWebhooksByHook('actionProductUpdate');
foreach ($webhooks as $webhook) {
$this->dispatchWebhook($webhook, $params);
}
}
public function hookActionProductDelete($params)
{
$webhooks = WebhookModel::getWebhooksByHook('actionProductDelete');
foreach ($webhooks as $webhook) {
$this->dispatchWebhook($webhook, $params);
}
}
public function hookActionCustomerAccountAdd($params)
{
$webhooks = WebhookModel::getWebhooksByHook('actionCustomerAccountAdd');
foreach ($webhooks as $webhook) {
$this->dispatchWebhook($webhook, $params);
}
}
public function hookActionCustomerAccountUpdate($params)
{
$webhooks = WebhookModel::getWebhooksByHook('actionCustomerAccountUpdate');
foreach ($webhooks as $webhook) {
$this->dispatchWebhook($webhook, $params);
}
}
public function hookActionObjectCustomerMessageAddAfter($params)
{