Skip to content
Advertisement

How to pass storeUrl to default Magento oauth script?

I’m trying to create my first Magento 2 extension and integration and I’ve been following the guide in their docs here. All good so far, I’ve completed the auth handshake, stored all the required keys for api requests and can make requests back to my extension fine.

Looking at the OauthClient.php script provided at the foot of the tutorial, the url is hardcoded like so: return new Uri('http://magento.host/oauth/token/request'); and the tutorial advises you to “Change the instances of http://magento.host in this example to a valid base URL.”

<?php

use OAuthCommonConsumerCredentials;
use OAuthCommonHttpClientClientInterface;
use OAuthCommonHttpExceptionTokenResponseException;
use OAuthCommonHttpUriUri;
use OAuthCommonHttpUriUriInterface;
use OAuthCommonStorageTokenStorageInterface;
use OAuthOAuth1ServiceAbstractService;
use OAuthOAuth1SignatureSignatureInterface;
use OAuthOAuth1TokenStdOAuth1Token;
use OAuthOAuth1TokenTokenInterface;

class OauthClient extends AbstractService
{
    /** @var string|null */
    protected $_oauthVerifier = null;

    public function __construct(
        Credentials $credentials,
        ClientInterface $httpClient = null,
        TokenStorageInterface $storage = null,
        SignatureInterface $signature = null,
        UriInterface $baseApiUri = null
    ) {
        if (!isset($httpClient)) {
            $httpClient = new OAuthCommonHttpClientStreamClient();
        }
        if (!isset($storage)) {
            $storage = new OAuthCommonStorageSession();
        }
        if (!isset($signature)) {
            $signature = new OAuthOAuth1SignatureSignature($credentials);
        }
        parent::__construct($credentials, $httpClient, $storage, $signature, $baseApiUri);
    }

    /**
     * @return UriInterface
     */
    public function getRequestTokenEndpoint()
    {
        return new Uri('http://magento.host/oauth/token/request');
    }

    /**
     * Returns the authorization API endpoint.
     *
     * @throws OAuthCommonExceptionException
     */
    public function getAuthorizationEndpoint()
    {
        throw new OAuthCommonExceptionException(
            'Magento REST API is 2-legged. Current operation is not available.'
        );
    }

    /**
     * Returns the access token API endpoint.
     *
     * @return UriInterface
     */
    public function getAccessTokenEndpoint()
    {
        return new Uri('http://magento.host/oauth/token/access');
    }

    /**
     * Parses the access token response and returns a TokenInterface.
     *
     * @param string $responseBody
     * @return TokenInterface
     */
    protected function parseAccessTokenResponse($responseBody)
    {
        return $this->_parseToken($responseBody);
    }

    /**
     * Parses the request token response and returns a TokenInterface.
     *
     * @param string $responseBody
     * @return TokenInterface
     * @throws TokenResponseException
     */
    protected function parseRequestTokenResponse($responseBody)
    {
        $data = $this->_parseResponseBody($responseBody);
        if (isset($data['oauth_verifier'])) {
            $this->_oauthVerifier = $data['oauth_verifier'];
        }
        return $this->_parseToken($responseBody);
    }

    /**
     * Parse response body and create oAuth token object based on parameters provided.
     *
     * @param string $responseBody
     * @return StdOAuth1Token
     * @throws TokenResponseException
     */
    protected function _parseToken($responseBody)
    {
        $data = $this->_parseResponseBody($responseBody);
        $token = new StdOAuth1Token();
        $token->setRequestToken($data['oauth_token']);
        $token->setRequestTokenSecret($data['oauth_token_secret']);
        $token->setAccessToken($data['oauth_token']);
        $token->setAccessTokenSecret($data['oauth_token_secret']);
        $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
        unset($data['oauth_token'], $data['oauth_token_secret']);
        $token->setExtraParams($data);
        return $token;
    }

    /**
     * Parse response body and return data in array.
     *
     * @param string $responseBody
     * @return array
     * @throws OAuthCommonHttpExceptionTokenResponseException
     */
    protected function _parseResponseBody($responseBody)
    {
        if (!is_string($responseBody)) {
            throw new TokenResponseException("Response body is expected to be a string.");
        }
        parse_str($responseBody, $data);
        if (null === $data || !is_array($data)) {
            throw new TokenResponseException('Unable to parse response.');
        } elseif (isset($data['error'])) {
            throw new TokenResponseException("Error occurred: '{$data['error']}'");
        }
        return $data;
    }

    /**
     * @override to fix since parent implementation from lib not sending the oauth_verifier when requesting access token
     * Builds the authorization header for an authenticated API request
     *
     * @param string $method
     * @param UriInterface $uri the uri the request is headed
     * @param OAuthOAuth1TokenTokenInterface $token
     * @param $bodyParams array
     * @return string
     */
    protected function buildAuthorizationHeaderForAPIRequest(
        $method,
        UriInterface $uri,
        TokenInterface $token,
        $bodyParams = null
    ) {
        $this->signature->setTokenSecret($token->getAccessTokenSecret());
        $parameters = $this->getBasicAuthorizationHeaderInfo();
        if (isset($parameters['oauth_callback'])) {
            unset($parameters['oauth_callback']);
        }

        $parameters = array_merge($parameters, ['oauth_token' => $token->getAccessToken()]);
        $parameters = array_merge($parameters, $bodyParams);
        $parameters['oauth_signature'] = $this->signature->getSignature($uri, $parameters, $method);

        $authorizationHeader = 'OAuth ';
        $delimiter = '';

        foreach ($parameters as $key => $value) {
            $authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';
            $delimiter = ', ';
        }

        return $authorizationHeader;
    }
}

My Question is how do I pass the url from the store that the integration has been set up on back as a variable in here?(I have it stored in my db)

Thanks for taking the time to take a look.

Advertisement

Answer

For anyone who might come across this in future after getting the saved data from the table in my db, I added the Url into the call to make the new class on the checklogin.php script in the documentation:

$oAuthClient = new OauthClient($credentials,$magentoBaseUrl);

And then in OauthClient.php, I added the url to the construct and updated the getRequestTokenEndpoint method and the getAcessTokenEndpoint:

    public function __construct(
        Credentials $credentials,
        $magentoBaseUrl = null,
        ClientInterface $httpClient = null,
        TokenStorageInterface $storage = null,
        SignatureInterface $signature = null,
        UriInterface $baseApiUri = null

    ) {
        if (!isset($httpClient)) {
            $httpClient = new OAuthCommonHttpClientCurlClient();
        }
        if (!isset($storage)) {
            $storage = new OAuthCommonStorageSession();
        }
        if (!isset($signature)) {
            $signature = new OAuthOAuth1SignatureSignature($credentials);
        }
        if (!isset($magentoBaseUrl)) {
            die();
        }
        $this->magentoBaseUrl = $magentoBaseUrl;
        parent::__construct($credentials, $httpClient, $storage, $signature, $baseApiUri);
    }

...

    /**
     * @return UriInterface
     */
    public function getRequestTokenEndpoint()
    {
        return new Uri($this->magentoBaseUrl.'/oauth/token/request');
    }
...

    /**
     * Returns the access token API endpoint.
     *
     * @return UriInterface
     */
    public function getAccessTokenEndpoint()
    {
        return new Uri($this->magentoBaseUrl.'/oauth/token/access');
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement