In Magento2 when you create an integration, how do you get an Access Token? It seems OAuth is the recommended approach for a third-party service, per the documentation. Getting an Access Token is a prerequisite for making authenticated requests against the API.

Third-party applications authenticate with OAuth 1.0a.

  • Did you just post the answer in the question? Self-answered questions are welcome, but please separate it into question and answer. You also can mark your own answer as accepted after 2 days – Fabian Schmengler Apr 12 '16 at 21:35
  • Sorry it's my first ever Q/A post. Thanks for the upvote, I'll clean it up right now! – quickshiftin Apr 12 '16 at 21:36
up vote 4 down vote accepted

Just starting out with Magento2 I found this to be pretty painful to figure out. It took me about half a day! To be fair, Magento has the appropriate documentation you need here...

The problem is it's very minimal. With my working knowledge of OAuth1 taken together with a gist of how to get an access token from Magento1 REST services I was finally able to pull it off. Details below!


1. Create a dedicated vhost (for the consumer application)

On my test environment, my Magento installation is installed at magev2.local, and I created a consumer application for purposes of obtaining an access token with the domain mage-access.local

2. Write a PHP file to interact with Magento (or use mine)

Here's the script I used (adapted from the gist I mentioned above). It uses the native PHP OAuth class, so you'll need to install that extension or swap some of this code out with your OAuth client library of choice.

<?php
//------------------------------
// Display an authorization page
//------------------------------
if($_SERVER['REQUEST_METHOD'] == 'GET') {
    file_put_contents('/tmp/redirectUrl', $_GET['success_call_back']);
?>
<html>
<head></head>
<body>
<form action="/oauth.php" method="post">
    <p>Click Authorize to get your app connected son!</p>
    <input type="hidden" name="authorized" value="yes"/>
    <input type="submit" value="Authorize"/>
</body>
<?php
} elseif($_SERVER['REQUEST_METHOD']) {
    //-----------------------------------
    // Capture OAuth info sent by Magento
    //-----------------------------------
    if(isset($_POST['oauth_consumer_key'])) {
        // Configuration
        $data['mageUrl']        = $_POST['store_base_url'];
        $data['consumerKey']    = $_POST['oauth_consumer_key'];
        $data['consumerSecret'] = $_POST['oauth_consumer_secret'];
        $data['verifier']       = $_POST['oauth_verifier'];
        file_put_contents('/tmp/oauth-info', serialize($data));
    }

    //---------------------------------------------
    // We have approval, let's get the access token
    //---------------------------------------------
    elseif(isset($_POST['authorized']) && $_POST['authorized'] == 'yes') {
        $data = unserialize(file_get_contents('/tmp/oauth-info'));
        $requestTokenRequestUrl = $data['mageUrl'] . 'oauth/token/request';
        $accessTokenRequestUrl  = $data['mageUrl'] . 'oauth/token/access';

        // Instantiate the OAuth client
        $oauthClient = new OAuth($data['consumerKey'], $data['consumerSecret']);

        try {
            // Fetch a request token and redirect to the magento site for authorization
            $requestToken = $oauthClient->getRequestToken($requestTokenRequestUrl);

            // Fetch an access token
            $oauthClient->setToken($requestToken['oauth_token'], $requestToken['oauth_token_secret']);
            $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl, null, $data['verifier']);

            // Redirect to Magento
            $redirectUrl = trim(file_get_contents('/tmp/redirectUrl'));
            unlink('/tmp/redirectUrl');
            unlink('/tmp/oauth-info');

            header('Location: ' . $redirectUrl);
        } catch (OAuthException $e) {
            ob_start();
            var_dump($e);
            $details = ob_get_clean();
            echo '<pre>';
            echo '<h2>Error Message</h2>';
            echo $e->getMessage();
            echo '<hr><h3>Details</h3>';
            echo $details;
            echo '</pre>';
        }
    }
}

3. Get your Access Token!

When you create your integration in the Magento2 admin, (substitute the domains you're using of course) use oauth.php on your shiny new consumer application for both the Callback URL and the Identity link URL, here's what mine looks like for my test environment

Sample OAuth Consumer Integration Configuration

I recommend using the Save & Activate option as shown in the image because it seems like Magento has a very short lifetime for the consumer token. I found if I didn't generate the access token immediately after provisioning the consumer, I'd get error messages about the consumer key being expired.

On the next screen ensure the permissions for your consumer are as you wish then click the Allow button. This loads a form from the oauth.php script asking for your authorization and simultaneously, Magento sends a POST request to oauth.php passing a temporary token from which you can procure request and access tokens.

All you have to do now is click the Authorize button and if everything works you'll have a shiny new access token! The list view of your integrations should now look like this

List view of authorized OAuth Consumer

and when you drill into the details, you'll see the access token

Authorized OAuth consumer with Access Token

  • could you please tell on how to Create a dedicated vhost for my custom module, is it mandatory? and also can ur script be used for any custom module? what changes have to be done? how to run it? – Sushivam Aug 8 '16 at 11:37
  • I want to create a custom soap api for magento2..could yo pls provide proper steps for implementing? – Sushivam Aug 8 '16 at 11:38
  • Hi, creating a vhost for this purpose is like creating a vhost for any php-driven site. Conceivably you could even put this script on the same domain (in your magento installation) and it might work. I think you're confused about getting an access token against the Magento API and creating a custom module. The two things don't have anything to do with each other. Getting an access toke is something you need to do if you want to access the magento API via a third party application. – quickshiftin Aug 8 '16 at 15:50
  • Fatal error: Class 'OAuth' not found in /*/*/oauth.php on line 44. To solve this error is i want to install OAuth php extension?. Or any other way? – Midlaj Apr 26 at 13:42
  • @Midlaj As I mentioned in my answer, I'm using the oauth extension. You need to either add it to your php installation or use a php oauth library like this. – quickshiftin Apr 26 at 13:44

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.