1: <?php
2: namespace Ctct\WebHooks;
3:
4: use Ctct\Exceptions\CtctException;
5:
6: /**
7: * Main Webhook Utility class.<br/>
8: * This is meant to be used by users to validate and parse Webhooks received from ConstantContact.<br/>
9: *
10: * @package WebHooks
11: * @author Constant Contact
12: */
13: class CTCTWebhookUtil
14: {
15:
16: /**
17: * The client secret associated with the api key
18: */
19: private $clientSecret = '';
20:
21:
22: /**
23: * Constructor that creates a validation Object for WebHooks.
24: *
25: * @param string $clientSecret - The client secret associated with the api key
26: * @return CTCTWebhookUtil
27: */
28: function __construct($clientSecret='')
29: {
30: $this->setClientSecret($clientSecret);
31: }
32:
33:
34: /**
35: * CTCTWebhookUtil::getClientSecret()
36: *
37: * @return string - the secret API key
38: */
39: public function getClientSecret()
40: {
41: return $this->clientSecret;
42: }
43:
44:
45: /**
46: * CTCTWebhookUtil::setClientSecret()
47: * Set the clientSecret
48: *
49: * @param string $clientSecret - The client secret associated with the api key
50: * @return void
51: */
52: public function setClientSecret($clientSecret)
53: {
54: $this->clientSecret = $clientSecret;
55: }
56:
57: /**
58: * Get Billing Change Notification.<br/>
59: *
60: * Validates and parses the bodyMessage into
61: *
62: * @param xCtctHmacSHA256 The value in the x-ctct-hmac-sha256 header.
63: * @param bodyMessage The body message from the POST received from ConstantContact in Webhook callback.
64: * @return The object corresponding to bodyMessage in case of success; an exception is thrown otherwise.
65: * @throws CtctException Thrown when :
66: * <ul>
67: * <li>message encryption does not correspond with x-ctct-hmac-sha256 header value;</li>
68: * <li>or an error is raised when parsing the bodyMessage.</li>
69: * </ul>
70: * <p/>
71: */
72: public function getBillingChangeNotification($xCtctHmacSHA256, $bodyMessage)
73: {
74: if ($this->isValidWebhook($xCtctHmacSHA256, $bodyMessage))
75: {
76: return json_decode($bodyMessage);
77: } else
78: {
79: throw new CtctException("Invalid WebHook");
80: }
81: }
82:
83: /**
84: * Check if a Webhook message is valid or not.<br/>
85: *
86: * @param xCtctHmacSHA256 The value in the x-ctct-hmac-sha256 header.
87: * @param bodyMessage The body message from the POST received from ConstantContact in Webhook callback.
88: * @return true if in case of success; false if the Webhook is invalid.
89: *
90: */
91: public function isValidWebhook($xCtctHmacSHA256, $bodyMessage)
92: {
93: if ($this->getClientSecret() == null)
94: {
95: throw new CtctException("NO_CLIENT_SECRET");
96: }
97: $encodedString = hash_hmac("sha256", $bodyMessage, $this->clientSecret);
98:
99: return ($encodedString == $xCtctHmacSHA256)?true:false;
100: }
101: }
102: