summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorDaniel Weipert <code@drogueronin.de>2020-12-13 20:34:09 +0100
committerDaniel Weipert <code@drogueronin.de>2020-12-13 20:34:09 +0100
commitd79154b3612ec5c79c2fd81adf3ee40b53f83c69 (patch)
treece0e761c765eb92e8796d17f8488e36556e55145 /src
Initial commitv1.0.0
Diffstat (limited to 'src')
-rw-r--r--src/OAuthMiddleware.php66
1 files changed, 66 insertions, 0 deletions
diff --git a/src/OAuthMiddleware.php b/src/OAuthMiddleware.php
new file mode 100644
index 0000000..aeb28c7
--- /dev/null
+++ b/src/OAuthMiddleware.php
@@ -0,0 +1,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);
+ }
+}