66 exit (0 );
77}
88
9+ use Pagarme \Core \Webhook \Services \WebhookValidatorService ;
910use Woocommerce \Pagarme \Helper \Utils ;
1011use Woocommerce \Pagarme \Core ;
1112use Woocommerce \Pagarme \Model \Config ;
1213use Woocommerce \Pagarme \Model \Order ;
14+ use WP_Error ;
1315
1416class Webhooks
1517{
18+ const WEBHOOK_SIGNATURE_HEADER = 'HTTP_X_WEBHOOK_ASYMMETRIC_SIGNATURE ' ;
19+
1620 private $ config ;
1721
1822 public function __construct ()
@@ -23,17 +27,45 @@ public function __construct()
2327
2428 public function handle_requests ()
2529 {
26- $ body = Utils::get_json_post_data ();
30+ $ webHookSignature = $ _SERVER [self ::WEBHOOK_SIGNATURE_HEADER ] ?? null ;
31+ if (!$ webHookSignature ) {
32+ $ this ->config ->log ()->info ('Unauthorized Webhook Received: no signature header found! ' );
33+ wp_die (
34+ 'Unauthorized Webhook Received: no signature header found! ' ,
35+ 'Unauthorized ' ,
36+ array ('response ' => 401 )
37+ );
38+ }
39+ $ payload = file_get_contents ('php://input ' );
40+ if (empty ($ payload )) {
41+ $ this ->config ->log ()->info ('Unauthorized Webhook Received: empty payload! ' );
42+ wp_die (
43+ "Unauthorized Webhook Received: empty payload! " ,
44+ 'Unauthorized ' ,
45+ array ('response ' => 401 )
46+ );
47+ }
48+
49+ if (!WebhookValidatorService::validateSignature ($ payload , $ webHookSignature )) {
50+ $ this ->config ->log ()->info ('Unauthorized Webhook Received: invalid signature! ' );
51+ wp_die (
52+ 'Unauthorized Webhook Received: invalid signature! ' ,
53+ 'Unauthorized Webhook Received ' ,
54+ array ('response ' => 401 )
55+ );
56+ }
57+
58+ $ body = json_decode ($ payload );
2759
2860 if (empty ($ body )) {
29- $ this ->config ->log ()->add ( ' woo-pagarme ' , 'Webhook Received: empty body! ' );
61+ $ this ->config ->log ()->info ( 'Webhook Received: empty body! ' );
3062 return ;
3163 }
3264 if (!$ this ->orderByWoocommerce ($ body ->data ->code , $ body ->data ->order ->metadata , $ body ->id ) ) {
3365 return ;
3466 }
3567
36- $ this ->config ->log ()->add ( ' woo-pagarme ' , 'Webhook Received: ' . json_encode ($ body , JSON_PRETTY_PRINT ));
68+ $ this ->config ->log ()->info ( 'Webhook Received: ' . json_encode ($ body , JSON_PRETTY_PRINT ));
3769
3870 $ event = $ this ->sanitize_event_name ($ body ->type );
3971
@@ -69,7 +101,7 @@ private function orderByWoocommerce($orderId, $metadata, $webhookId)
69101 {
70102 if (!wc_get_order ($ orderId )) {
71103 if (strpos ($ this ->getMetadata ($ metadata ), "Woocommerce " ) !== false ) {
72- $ this ->config ->log ()->add ( ' woo-pagarme ' , 'Webhook Received but not proccessed: ' . $ webhookId );
104+ $ this ->config ->log ()->info ( 'Webhook Received but not proccessed: ' . $ webhookId );
73105 }
74106 return false ;
75107 }
0 commit comments