summaryrefslogtreecommitdiff
path: root/src/OAuthMiddleware.php
blob: aeb28c7d5f1375114e261f0df4ff86575b95ffc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php

namespace CardmarketApi;

use Psr\Http\Message\RequestInterface;

class OAuthMiddleware
{
    public function __invoke(callable $handler): callable
    {
        return function (RequestInterface $request, array $options) use ($handler) {
            $cardMarketConfig = $options['cardmarket'];
            $oAuthParams = [
                'oauth_consumer_key' => $cardMarketConfig['app_token'],
                'oauth_token' => $cardMarketConfig['access_token'],
                'oauth_nonce' => uniqid(),
                'oauth_timestamp' => time(),
                'oauth_signature_method' => 'HMAC-SHA1',
                'oauth_version' => '1.0',
            ];

            $oAuthHeaderParams = $oAuthParams + [
                'realm' => $request->getUri(),
                'oauth_signature' => $this->getOAuthSignature($request->getMethod(), $request->getUri(), $options, $oAuthParams)
            ];
            $oAuthHeader = 'OAuth ' .
                implode(',', array_map(
                    fn ($key, $value) => "$key=\"$value\"",
                    array_keys($oAuthHeaderParams),
                    $oAuthHeaderParams
                ));

            $request = $request->withHeader('Authorization', $oAuthHeader);

            return $handler($request, $options);
        };
    }

    /**
     * Generates the OAuthSignature
     * @see https://api.cardmarket.com/ws/documentation/API:Auth_libcurl
     *
     * @param string $method
     * @param string $uri
     * @param array  $options
     * @param array  $oAuthParams
     *
     * @return string
     */
    private function getOAuthSignature(string $method, string $uri, array $options, array $oAuthParams): string
    {
        $cardMarketConfig = $options['cardmarket'];

        ksort($oAuthParams);
        $baseStringParams = [
            strtoupper($method),
            rawurlencode($uri),
            rawurlencode(http_build_query($oAuthParams)),
        ];
        $baseString = implode('&', $baseStringParams);
        $signatureKey = rawurlencode($cardMarketConfig['app_secret']) . '&' . rawurlencode($cardMarketConfig['access_token_secret']);
        $rawSignature = hash_hmac('sha1', $baseString, $signatureKey, true);

        return base64_encode($rawSignature);
    }
}