1: <?php
2:
3: namespace SellerLabs\Snagshout;
4:
5: use Closure;
6: use DateTime;
7: use GuzzleHttp\Client;
8: use GuzzleHttp\Handler\CurlHandler;
9: use GuzzleHttp\HandlerStack;
10: use GuzzleHttp\Psr7\Uri;
11: use Psr\Http\Message\RequestInterface;
12: use Psr\Http\Message\ResponseInterface;
13:
14: 15: 16: 17: 18: 19: 20:
21: class SyndicationClient
22: {
23: 24: 25:
26: protected $publicId;
27:
28: 29: 30:
31: protected $secretKey;
32:
33: 34: 35:
36: protected $endpoint;
37:
38: 39: 40: 41: 42: 43:
44: public function __construct($publicId, $secretKey)
45: {
46: $this->publicId = $publicId;
47: $this->secretKey = $secretKey;
48:
49: $this->endpoint = new Uri('https://www.snagshout.com');
50:
51: $stack = new HandlerStack();
52:
53: $stack->setHandler(new CurlHandler());
54:
55: $stack->push($this->makeAuthHandler());
56:
57: $this->client = new Client([
58: 'handler' => $stack,
59: ]);
60: }
61:
62: 63: 64:
65: public function setPublicId(string $publicId)
66: {
67: $this->publicId = $publicId;
68: }
69:
70: 71: 72:
73: public function setSecretKey(string $secretKey)
74: {
75: $this->secretKey = $secretKey;
76: }
77:
78: 79: 80:
81: public function setEndpoint(Uri $endpoint)
82: {
83: $this->endpoint = $endpoint;
84: }
85:
86: 87: 88: 89: 90: 91: 92:
93: protected function hash($content)
94: {
95: $timestamp = (new DateTime())->format('Y-m-d H');
96:
97: return hash_hmac(
98: 'sha512',
99: $content . $timestamp,
100: $this->secretKey
101: );
102: }
103:
104: 105: 106: 107: 108: 109:
110: protected function makeAuthHandler()
111: {
112: return function (callable $handler) {
113: return function (
114: RequestInterface $request,
115: array $options
116: ) use ($handler) {
117: $contentHash = $this->hash($request->getBody());
118:
119: $partialUri = $request->getUri();
120: $uri = $this->endpoint
121: ->withPath(
122: $this->endpoint->getPath()
123: . $partialUri->getPath()
124: )
125: ->withQuery($partialUri->getQuery())
126: ->withFragment($partialUri->getFragment());
127:
128: $request = $request
129: ->withUri($uri)
130: ->withHeader(
131: 'Authorization',
132: vsprintf('Hash %s', [$this->publicId])
133: )
134: ->withHeader('Content-Hash', $contentHash);
135:
136: return $handler($request, $options);
137: };
138: };
139: }
140:
141: 142: 143: 144: 145: 146: 147:
148: public function getCampaigns(array $options = [])
149: {
150: return $this->client->get('/api/v1/campaigns', array_merge(
151: [
152: 'query' => [
153: 'embeds' => 'promotions',
154: ]
155: ],
156: $options
157: ));
158: }
159: }