Search code examples
ruby-on-railsmagentooauthmagento-rest-api

rails - request token on magento api REST


I have a rails application which needs to communicate with magento that is on the same server with my rails app. I made all communication in SOAP but it's really slow and I want to change everything to REST.

I have a consumer key and a consumer secret that I'll send to magento to request a token.

DOCS: oauth github, magento oauth

@consumer = OAuth::Consumer.new("44a41ac2e67b", "89578e79570738d", { request_token_path: '/oauth/initiate', access_token_path: '/oauth/token' ,site: "http://shop.myproject.com" })
=> #<OAuth::Consumer:0x000000093955e0 @key="44a1edf5861edf37c", @secret="f87a0e4bfb7663fb78d", @options={:signature_method=>"HMAC-SHA1", :request_token_path=>"/oauth/initiate", :authorize_path=>"/oauth/authorize", :access_token_path=>"/oauth/token", :proxy=>nil, :scheme=>:header, :http_method=>:post, :oauth_version=>"1.0", :site=>"http://shop.myproject.com"}>

@request_token = @consumer.get_request_token
=> Got good response and request_token is good

From magento docs:
User Authorization

The second step is to request user authorization. After receiving the Request Token
from Magento, the application provides an authorization page to the user. The only 
required parameter for this step is the Request Token (oauth_token value) received from 
the previous step. The endpoint is followed by an oauth_token parameter with the value 
set to the oauth_token value.

@access_token = @request_token.get_access_token
OAuth::Unauthorized: 400 Bad Request

Basically I'm on the page where user exchange request token for access token clicking allow or entering username and password. But since I have to do everything in the background, what's the step before I request the access token. I can't find in docummentation how to do this and I don't have a php background.

I've already read: 1, 2, 3

Please ask me for any other details in comment section.


Solution

  • Fix it adding authorize path for consumer. Poor guide below

    1) Create consumer

      @consumer = OAuth::Consumer.new("44a41ac2e67b", "89578e79570738d", { 
        request_token_path: '/oauth/initiate', 
        access_token_path: '/oauth/token',
        authorize_path: '/admin/oauth_authorize',
        site: "http://shop.myproject.com" 
      })
    

    2) Get the request token

    @request_token = @consumer.get_request_token
    

    3) Get authorize url

    @authorized_url = @request_token.authorize_url
    

    4) Click it, enter credentials, click authorize

    5) Grab oauth_verifier from the URL

    6) Get access token

    @access_token = @request_token.get_access_token(oauth_verifier: OAUTH_VERIFIER)
    

    Because access token is not going to change, I serialized it with YAML.dump and save it.