| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Framework\PaymentGateways\Routes; |
| 4 |
|
| 5 |
use Give\Framework\Shims\Shim; |
| 6 |
|
| 7 |
/** |
| 8 |
* Route signature for creating secure gateway route methods |
| 9 |
* |
| 10 |
* @since 2.19.0 |
| 11 |
*/ |
| 12 |
class RouteSignature |
| 13 |
{ |
| 14 |
/** |
| 15 |
* @var string |
| 16 |
*/ |
| 17 |
private $signature; |
| 18 |
/** |
| 19 |
* @var string |
| 20 |
*/ |
| 21 |
public $expiration; |
| 22 |
|
| 23 |
/** |
| 24 |
* @since 2.19.5 replace wp_create_nonce with wp_hash and timestamp expiration |
| 25 |
* @since 2.19.4 replace RouteSignature args with unique donationId |
| 26 |
* @since 2.19.0 |
| 27 |
* |
| 28 |
* @param int $gatewayId |
| 29 |
* @param string $gatewayMethod |
| 30 |
* @param int $donationId |
| 31 |
* @param string $expiration |
| 32 |
*/ |
| 33 |
public function __construct($gatewayId, $gatewayMethod, $donationId, $expiration = null) |
| 34 |
{ |
| 35 |
$this->expiration = $expiration ?: $this->createExpirationTimestamp(); |
| 36 |
$this->signature = $this->generateSignatureString($gatewayId, $gatewayMethod, $donationId, $this->expiration); |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
/** |
| 41 |
* @since 2.19.5 |
| 42 |
* |
| 43 |
* @param string $gatewayId |
| 44 |
* @param string $gatewayMethod |
| 45 |
* @param int $donationId |
| 46 |
* @param string $expiration |
| 47 |
* @return string |
| 48 |
*/ |
| 49 |
private function generateSignatureString($gatewayId, $gatewayMethod, $donationId, $expiration) |
| 50 |
{ |
| 51 |
return "$gatewayId@$gatewayMethod:$donationId|$expiration"; |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* @since 2.19.0 |
| 56 |
* |
| 57 |
* @return string |
| 58 |
*/ |
| 59 |
public function toString() |
| 60 |
{ |
| 61 |
return $this->signature; |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* @since 2.19.5 |
| 66 |
* |
| 67 |
* @return string |
| 68 |
*/ |
| 69 |
public function toHash() |
| 70 |
{ |
| 71 |
return wp_hash($this->signature); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Create expiration timestamp |
| 76 |
* |
| 77 |
* @since 2.19.5 |
| 78 |
* |
| 79 |
* @return string |
| 80 |
*/ |
| 81 |
public function createExpirationTimestamp() |
| 82 |
{ |
| 83 |
return (string)current_datetime()->modify('+1 day')->getTimestamp(); |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
/** |
| 88 |
* @since 2.19.5 |
| 89 |
* |
| 90 |
* @param string $suppliedSignature |
| 91 |
* @return bool |
| 92 |
*/ |
| 93 |
public function isValid($suppliedSignature) |
| 94 |
{ |
| 95 |
$isSignatureValid = hash_equals( |
| 96 |
$suppliedSignature, |
| 97 |
$this->toHash() |
| 98 |
); |
| 99 |
|
| 100 |
$isNotExpired = ((int)$this->expiration) >= current_datetime()->getTimestamp(); |
| 101 |
|
| 102 |
return $isSignatureValid && $isNotExpired; |
| 103 |
} |
| 104 |
} |
| 105 |
|