| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPDesk\GatewayWPPay\Helpers; |
| 4 |
|
| 5 |
final class ItnHashValidator { |
| 6 |
|
| 7 |
public static function is_valid( string $encoded_transactions, callable $hash_generator ): bool { |
| 8 |
$xml = self::decode_payload( $encoded_transactions ); |
| 9 |
|
| 10 |
if ( ! $xml instanceof \SimpleXMLElement ) { |
| 11 |
return false; |
| 12 |
} |
| 13 |
|
| 14 |
$data = DataConverter::simplexml_to_array( $xml ); |
| 15 |
if ( empty( $data ) || empty( $data['hash'] ) ) { |
| 16 |
return false; |
| 17 |
} |
| 18 |
|
| 19 |
$received_hash = trim( (string) $data['hash'] ); |
| 20 |
unset( $data['hash'] ); |
| 21 |
|
| 22 |
$expected_hash = $hash_generator( ArrayFlattener::flatten_array( $data ) ); |
| 23 |
|
| 24 |
return is_string( $expected_hash ) && hash_equals( $expected_hash, $received_hash ); |
| 25 |
} |
| 26 |
|
| 27 |
private static function decode_payload( string $encoded_transactions ): ?\SimpleXMLElement { |
| 28 |
$decoded_payload = base64_decode( $encoded_transactions, true ); |
| 29 |
if ( $decoded_payload === false ) { |
| 30 |
return null; |
| 31 |
} |
| 32 |
|
| 33 |
$previous_state = libxml_use_internal_errors( true ); |
| 34 |
$xml = simplexml_load_string( $decoded_payload ); |
| 35 |
libxml_clear_errors(); |
| 36 |
libxml_use_internal_errors( $previous_state ); |
| 37 |
|
| 38 |
return $xml instanceof \SimpleXMLElement ? $xml : null; |
| 39 |
} |
| 40 |
} |
| 41 |
|