Consuming Magento REST service using Zend_OAuth_Consumer

Consuming Magento REST service using Zend_OAuth_Consumer

Ok folks. Until today, trying to cover this area completely, I wrote two articles about Magento oAuth and REST services:

This Magento REST and oAuth functionality and ways on which it could be used are so wide that I think that even in this three articles will not cover everything that I wanna share with you, so stay tuned for next articles about this topic in near future 🙂

In official Magento documentation, one plain PHP class is written on how to authenticate with oAuth and how to Consume Magento REST web service.
Here I am going to show how you can do it from inside your Magento controller that is acting as REST client this time. Of course, for simplicity, I am not going to handle errors in examples and I am going to consume REST on same Magento installation, but I think that it will be enough to show the point.
Let’s start.

  1. Configure your local Magento installation following last article steps: How to configure Magento REST and oAuth settings
  2. Create Magento controller class in your test module.
  3. Paste source code inside your controller to look like this:
<?php
 
/**
*
* @author Darko Goleš <darko.goles@inchoo.net>
* @package Inchoo
* @subpackage RestConnect
*
* Url of controller is: http://magento.loc/restconnect/test/[action]
*/
class Inchoo_RestConnect_TestController extends Mage_Core_Controller_Front_Action {
 
public function indexAction() {
 
//Basic parameters that need to be provided for oAuth authentication
//on Magento
$params = array(
'siteUrl' => 'http://magento.loc/oauth',
'requestTokenUrl' => 'http://magento.loc/oauth/initiate',
'accessTokenUrl' => 'http://magento.loc/oauth/token',
'authorizeUrl' => 'http://magento.loc/admin/oAuth_authorize',//This URL is used only if we authenticate as Admin user type
'consumerKey' => 'h7n8qjybu78cc3n8cdd5dr7ujtl33uqh',//Consumer key registered in server administration
'consumerSecret' => '2smfjx37a6e4w23jlcrya6iyv5v32fxr',//Consumer secret registered in server administration
'callbackUrl' => 'http://magento.loc/restconnect/test/callback',//Url of callback action below
);
 
// Initiate oAuth consumer with above parameters
$consumer = new Zend_Oauth_Consumer($params);
// Get request token
$requestToken = $consumer->getRequestToken();
// Get session
$session = Mage::getSingleton('core/session');
// Save serialized request token object in session for later use
$session->setRequestToken(serialize($requestToken));
// Redirect to authorize URL
$consumer->redirect();
 
return;
}
 
public function callbackAction() {
 
//oAuth parameters
$params = array(
'siteUrl' => 'http://magento.loc/oauth',
'requestTokenUrl' => 'http://magento.loc/oauth/initiate',
'accessTokenUrl' => 'http://magento.loc/oauth/token',
'consumerKey' => 'h7n8qjybu78cc3n8cdd5dr7ujtl33uqh',
'consumerSecret' => '2smfjx37a6e4w23jlcrya6iyv5v32fxr'
);
 
// Get session
$session = Mage::getSingleton('core/session');
// Read and unserialize request token from session
$requestToken = unserialize($session->getRequestToken());
// Initiate oAuth consumer
$consumer = new Zend_Oauth_Consumer($params);
// Using oAuth parameters and request Token we got, get access token
$acessToken = $consumer->getAccessToken($_GET, $requestToken);
// Get HTTP client from access token object
$restClient = $acessToken->getHttpClient($params);
// Set REST resource URL
$restClient->setUri('http://magento.loc/api/rest/products');
// In Magento it is neccesary to set json or xml headers in order to work
$restClient->setHeaders('Accept', 'application/json');
// Get method
$restClient->setMethod(Zend_Http_Client::GET);
//Make REST request
$response = $restClient->request();
// Here we can see that response body contains json list of products
Zend_Debug::dump($response);
 
return;
}
 
}

Now open the indexAction of this controller inside your browser. If everything configured correctly, you should be able to get list of products. At my Magento installation, URL is: http://magento.loc/restconnect/test

oAuthLogin1

oAuthAuthorize

Let’s explain above steps a little bit:

  • First we had to define basic neccesary oAuth parameters for Zend_OAuth_Client.
  • After initiating the client, first we get RequestToken. After request token is retreived, we save it into the session for usage in callback action later.
  • Then we call $client->redirect action and we are redirected to the server user login screen.
  • After successful login, we are redirected to Authorize URL in order user to Authorize application.
  • After authorization, server redirects to our callbackUrl we defined in $params. Here we are getting the RequestToken from session and requesting the AccessToken.
  • After AccessToken is retreived from server, oAuth dance is finished and we are preparing the Http client for making the REST request.
  • We make REST request to server resource URL and retreiving the response

Better way

Uf, let me share something more with you dear visitors:
In the meantime I investigated how to power up Magento oAuth, I developed one Model that can be used ro perform above operations even simpler and cleaner from inside your controller, and I wanna share it with you here.

<?php
/**
*
* @author Darko Goleš <darko.goles@inchoo.net>
* @package Inchoo
* @subpackage RestConnect
*/
class Inchoo_RestConnect_Model_Oauth_Client extends Mage_Core_Model_Abstract
{
private $_callbackUrl;
private $_siteUrl;
private $_consumerKey;
private $_consumerSecret;
private $_requestTokenUrl;
private $_accessTokenUrl;
private $_consumer;
private $_authorizeUrl;
private $_userAuthorizationUrl;
 
private $_authorized_token;
 
const OAUTH_STATE_NO_TOKEN = 0;
const OAUTH_STATE_REQUEST_TOKEN = 1;
const OAUTH_STATE_ACCESS_TOKEN = 2;
const OAUTH_STATE_ERROR = 3;
 
public function init($config)
{
$this->setOAuthConfig($config);
return $this;
}
 
public function setAuthorizedToken($token)
{
$this->_authorized_token = $token;
}
 
public function getAuthorizedToken()
{
if ($this->_authorized_token) {
return $this->_authorized_token;
}
return false;
}
 
public function reset()
{
return $this->resetSessionParams();
}
 
public function authenticate()
{
$state = $this->getOAuthState();
$consumer = $this->_getOAuthConsumer();
 
try {
switch ($state) {
case self::OAUTH_STATE_NO_TOKEN:
$requestToken = $this->getRequestToken();
$this->setOAuthState(self::OAUTH_STATE_REQUEST_TOKEN);
$consumer->redirect();
return self::OAUTH_STATE_REQUEST_TOKEN;
break;
 
case self::OAUTH_STATE_REQUEST_TOKEN:
$accessToken = $this->getAccessToken($this->getRequestToken());
$this->setAuthorizedToken($accessToken);
$this->setOAuthState(self::OAUTH_STATE_ACCESS_TOKEN);
return self::OAUTH_STATE_ACCESS_TOKEN;
break;
case self::OAUTH_STATE_ACCESS_TOKEN:
return self::OAUTH_STATE_ACCESS_TOKEN;
default:
$this->resetSessionParams();
return self::OAUTH_STATE_NO_TOKEN;
return;
break;
}
 
} catch (Zend_Oauth_Exception $e) {
$this->resetSessionParams();
Mage::logException($e);
} catch (Exception $e) {
Mage::logException($e);
}
return self::OAUTH_STATE_NO_TOKEN;
}
 
private function resetSessionParams()
{
$this->getSession()->unsetData('o_auth_state');
$this->getSession()->unsetData('request_token');
$this->getSession()->unsetData('o_auth_config');
$this->getSession()->unsetData('access_token');
 
return $this;
}
 
public function getRequestToken()
{
$token = $this->_getRequestTokenFromSession();
if ($token && $token instanceof Zend_Oauth_Token_Request) {
return $token;
}
 
$token = $this->_getRequestTokenFromServer();
if ($token && $token instanceof Zend_Oauth_Token_Request) {
$this->_saveRequestTokenInSession($token);
return $token;
}
 
return false;
}
 
public function getAccessToken($requestToken)
{
$token = $this->_getAccessTokenFromSession();
if ($token && $token instanceof Zend_Oauth_Token_Access) {
return $token;
}
 
$token = $this->_getAcessTokenFromServer($requestToken);
if ($token && $token instanceof Zend_Oauth_Token_Access) {
$this->_saveAccessTokenInSesion($token);
return $token;
}
}
 
private function _getAcessTokenFromServer($requestToken)
{
if ($requestToken && $requestToken instanceof Zend_Oauth_Token_Request) {
$accToken = $this->_getOAuthConsumer()->getAccessToken(
$_GET,
$requestToken
);
}
 
if ($accToken && $accToken instanceof Zend_Oauth_Token_Access) {
return $accToken;
}
 
return false;
}
 
private function _saveAccessTokenInSesion($accessToken)
{
$this->getSession()->setAccessToken(serialize($accessToken));
}
 
private function _getAccessTokenFromSession()
{
$accessToken = unserialize($this->getSession()->getAcessToken());
if ($accessToken && $accessToken instanceof Zend_Oauth_Token_Access) {
return $accessToken;
}
return false;
}
 
private function _getRequestTokenFromServer()
{
$token = $this->_getOAuthConsumer()->getRequestToken();
return $token;
}
 
private function _saveRequestTokenInSession(Zend_Oauth_Token_Request $requestToken)
{
$this->getSession()->setRequestToken(serialize($requestToken));
}
 
private function _getRequestTokenFromSession()
{
$requestToken = unserialize($this->getSession()->getRequestToken());
if ($requestToken && $requestToken instanceof Zend_Oauth_Token_Request) {
return $requestToken;
}
return false;
}
 
public function getSession()
{
return Mage::getSingleton('core/session');
}
 
public function getOAuthToken()
{
return $this->getRequest()->getParam('oauth_token', false);
}
 
public function getRequest()
{
return Mage::app()->getRequest();
}
 
private function _getOAuthConsumer()
{
if ($consumer = $this->_consumer) {
if ($consumer instanceof Zend_Oauth_Consumer) {
return $this->_consumer;
}
}
$this->_consumer = new Zend_Oauth_Consumer($this->getOAuthConfig());
return $this->_consumer;
}
 
private function getOAuthConfig()
{
$config = array(
'callbackUrl' => $this->_callbackUrl,
'siteUrl' => $this->_siteUrl,
'consumerKey' => $this->_consumerKey,
'consumerSecret' => $this->_consumerSecret,
'requestTokenUrl' => $this->_requestTokenUrl,
'accessTokenUrl' => $this->_accessTokenUrl,
);
 
if ($this->_authorizeUrl && $this->_authorizeUrl != '') {
$config['authorizeUrl'] = $this->_authorizeUrl;
}
 
if ($this->_userAuthorizationUrl && $this->_userAuthorizationUrl != '') {
$config['userAuthorizationUrl'] = $this->_userAuthorizationUrl;
}
 
return $config;
 
}
 
private function setOAuthConfig($config)
{
$this->getSession()->setOAuthConfig(serialize($config));
foreach ($config as $key => $val) {
$_key = '_' . $key;
$this->$_key = $val;
}
}
 
public function getConfigFromSession()
{
$config = unserialize($this->getSession()->getOAuthConfig());
if ($config && is_array($config)) {
return $config;
}
return false;
}
 
private function setOAuthState($state)
{
$this->getSession()->setOAuthState($state);
}
 
public function getOAuthState()
{
$state = $this->getSession()->getOAuthState();
if ($state == null) {
return self::OAUTH_STATE_NO_TOKEN;
}
 
$paramOAuthToken = $this->getOAuthToken();
if ($paramOAuthToken == false && $state == self::OAUTH_STATE_REQUEST_TOKEN) {
$this->resetSessionParams();
return self::OAUTH_STATE_NO_TOKEN;
}
 
return $state;
 
}
 
}

Create your own Model file inside your extension dir, and paste above source code there (of course, don’t forget to rename the class to fit your needs).

After that, you just need to have controller like this:

<?php
 
/**
*
* @author Darko Goleš <darko.goles@inchoo.net>
* @package Inchoo
* @subpackage RestConnect
*
* Url of controller is: http://magento.loc/restconnect/test/[action]
*/
class Inchoo_RestConnect_TestController extends Mage_Core_Controller_Front_Action {
 
public function indexAction() {
 
//Basic parameters that need to be provided for oAuth authentication
//on Magento
$params = array(
'siteUrl' => 'http://magento.loc/oauth',
'requestTokenUrl' => 'http://magento.loc/oauth/initiate',
'accessTokenUrl' => 'http://magento.loc/oauth/token',
'authorizeUrl' => 'http://magento.loc/admin/oAuth_authorize', //This URL is used only if we authenticate as Admin user type
'consumerKey' => 'h7n8qjybu78cc3n8cdd5dr7ujtl33uqh', //Consumer key registered in server administration
'consumerSecret' => '2smfjx37a6e4w23jlcrya6iyv5v32fxr', //Consumer secret registered in server administration
'callbackUrl' => 'http://magento.loc/restconnect/test/callback', //Url of callback action below
);
 
$oAuthClient = Mage::getModel('inchoo_restconnect/oauth_client');
$oAuthClient->reset();
 
$oAuthClient->init($params);
$oAuthClient->authenticate();
 
return;
}
 
public function callbackAction() {
 
$oAuthClient = Mage::getModel('inchoo_restconnect/oauth_client');
$params = $oAuthClient->getConfigFromSession();
$oAuthClient->init($params);
 
$state = $oAuthClient->authenticate();
 
if ($state == Inchoo_RestConnect_Model_OAuth_Client::OAUTH_STATE_ACCESS_TOKEN) {
$acessToken = $oAuthClient->getAuthorizedToken();
}
 
$restClient = $acessToken->getHttpClient($params);
// Set REST resource URL
$restClient->setUri('http://magento.loc/api/rest/products');
// In Magento it is neccesary to set json or xml headers in order to work
$restClient->setHeaders('Accept', 'application/json');
// Get method
$restClient->setMethod(Zend_Http_Client::GET);
//Make REST request
$response = $restClient->request();
// Here we can see that response body contains json list of products
Zend_Debug::dump($response);
 
return;
}
 
}

If you use this source, please leave the credit at the top of the file. Thanks.

I hope this article helped to better understand oAuth and REST web services with Magento. 🙂

In case you’re going to need any other help with your Magento development, we’re here for you!

Related Inchoo Services

You made it all the way down here so you must have enjoyed this post! You may also like:

How to configure Magento REST and oAuth settings Darko Goles
Darko Goles, | 26

How to configure Magento REST and oAuth settings

Introduction to Magento REST and oAuth Darko Goles
Darko Goles, | 11

Introduction to Magento REST and oAuth

Unit testing with Zend framework: Setting up environment for the first test using Netbeans IDE for php Darko Goles
Darko Goles, | 1

Unit testing with Zend framework: Setting up environment for the first test using Netbeans IDE for php

45 comments

  1. Hello All,

    I have implement controller and model as per tutorial.

    but in Post Man i am not able to get products data. In post man i am getting Magento admin login screen.
    http://prntscr.com/ixfwey

    or in front side i am try to call controller but some time give me error like “Request is not GET” and “Invalid Form Key. Please refresh the page.” .
    http://prntscr.com/ixfxhv

    can anyone please suggest where i am doing wrong.

    Thanks in advance..

  2. thanks for your articles, very well explained. I have a question for you. I test your code with get request and function very well, but I need do a post request for create a product. I put the follow code but I receive an error message.

    			$restClient->setHeaders('Content-type', 'application/json');
                            $restClient->setMethod(Zend_Http_Client::POST);
                            $restClient->setParameterPost(array(
    					'type_id'           => 'simple',
    					'attribute_set_id'  => 4,
    					'sku'               => 'SKUTEST' . uniqid(),
    					'weight'            => 1,
    					'status'            => 1,
    					'visibility'        => 4,
    					'name'              => 'Simple Product',
    					'description'       => 'Simple Description',
    					'short_description' => 'Simple Short Description',
    					'price'             => 69.95,
    					'tax_class_id'      => 0,
                            $response = $restClient->request();

    The error code is:

    object(Zend_Http_Response)[330]
      protected 'version' => string '1.1' (length=3)
      protected 'code' => int 500
      protected 'message' => string 'Internal Server Error' (length=21)
      protected 'headers' => 
        array (size=7)
          'Date' => string 'Thu, 26 Oct 2017 08:50:00 GMT' (length=29)
          'Server' => string 'Apache' (length=6)
          'X-frame-options' => string 'SAMEORIGIN' (length=10)
          'X-powered-by' => string 'PHP/5.6.22' (length=10)
          'Content-length' => string '29' (length=2)
          'Connection' => string 'close' (length=5)
          'Content-type' => string 'text/html; charset=UTF-8' (length=24)
      protected 'body' => string 'Service temporary unavailable' (length=29)
    

    I config my admin user of magento who is conected with their code with All resources role and all acl attribute rules.
    is the code that I use correct?
    Thank you for your support

  3. Hi,
    This helped me a lot, I get this working and thanks to you for sharing with us.

    but being a newbie I must ask do I need to authorize every time I call the API?

    when i tried to access the Pre-Authorized API (I refreshed the link)
    it says :- “is not a valid URI”
    and gives:
    PHP Fatal error: Call to a member function getHttpClient() on boolean in /controllers/IndexController.php

    when I switch client
    it says:-

    Could not retrieve a valid Token response from Token URL: oauth_problem=nonce_used

    Maybe something I missed to handle those conditions, need advice.

    Thanks

    P.S. I wonder what are those for:–

    
        const OAUTH_STATE_NO_TOKEN = 0;
        const OAUTH_STATE_REQUEST_TOKEN = 1;
        const OAUTH_STATE_ACCESS_TOKEN = 2;
        const OAUTH_STATE_ERROR = 3;
    
  4. I have implemented this but when I am calling the controller action on browser I am getting this error

    Could not retrieve a valid Token response from Token URL:
    oauth_problem=nonce_used

    Please help me on resolving this.

  5. getting error like
    ‘There has been an error processing your request
    Exception printing is disabled by default for security reasons.
    Error log record number: 965589527279’

  6. I got error like

    Error in HTTP request

    Trace:
    #0 /var/www/html/mage1.9/lib/Zend/Oauth/Http/RequestToken.php(51): Zend_Oauth_Http->startRequestCycle(Array)
    #1 /var/www/html/mage1.9/lib/Zend/Oauth/Consumer.php(115): Zend_Oauth_Http_RequestToken->execute()
    #2 /var/www/html/mage1.9/app/code/local/Practice/ControllerTest/controllers/IndexController.php(61): Zend_Oauth_Consumer->getRequestToken()
    #3 /var/www/html/mage1.9/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Practice_ControllerTest_IndexController->indexAction()
    #4 /var/www/html/mage1.9/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch(‘index’)
    #5 /var/www/html/mage1.9/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
    #6 /var/www/html/mage1.9/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
    #7 /var/www/html/mage1.9/app/Mage.php(683): Mage_Core_Model_App->run(Array)
    #8 /var/www/html/mage1.9/index.php(83): Mage::run(”, ‘store’)
    #9 {main}

  7. Hello,

    I got the following error after clicking on Authorize button.
    ——————————————————
    Error in HTTP request

    Trace:
    #0 /home/coszi/domains/coszi.com/public_html/lib/Zend/Oauth/Http/AccessToken.php(51): Zend_Oauth_Http->startRequestCycle(Array)
    #1 /home/coszi/domains/coszi.com/public_html/lib/Zend/Oauth/Consumer.php(225): Zend_Oauth_Http_AccessToken->execute()
    #2 /home/coszi/domains/coszi.com/public_html/app/code/local/MS/RestConnect/controllers/TestController.php(44): Zend_Oauth_Consumer->getAccessToken(Array, Object(Zend_Oauth_Token_Request))
    #3 /home/coszi/domains/coszi.com/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): MS_RestConnect_TestController->callbackAction()
    #4 /home/coszi/domains/coszi.com/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch(‘callback’)
    #5 /home/coszi/domains/coszi.com/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
    #6 /home/coszi/domains/coszi.com/public_html/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
    #7 /home/coszi/domains/coszi.com/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
    #8 /home/coszi/domains/coszi.com/public_html/index.php(89): Mage::run(”, ‘store’)
    #9 {main}

    ———————————————————

    Please help me to resolve it.

    Thanks,

  8. Can anyone say what is the filename to be saved, where to be saved, and explain everything about executing this. This question may seem so simple but as i am new to this i need to know from scratch. Thanks

  9. Hi. In what file name the code should be saved. and the file first line states class Inchoo_RestConnect_TestController extends Mage_Core_Controller_Front_Action
    so is that the directory should contain this file. If so then where is the code. This question may be silly but please let me know the way how it is done.

    1. Hi Party. I would to know the same answer. It seems simple for every one, but for us that never used Rest API ora Soap API before, it isn’t

  10. The article was very much informative and helpful, however,I was struggling to use callback action with above example. So I wrote following controller and its working

    class myModule_RestConnect_IndexController extends Mage_Core_Controller_Front_Action {

    public function indexAction() {

    //Parameters that need to be provided for oAuth authentication.
    $params = array(
    ‘siteUrl’ => Mage::getBaseUrl().’oauth’,
    ‘requestTokenUrl’ => Mage::getBaseUrl().’oauth/initiate’,
    ‘accessTokenUrl’ => Mage::getBaseUrl().’oauth/token’,
    ‘authorizeUrl’ => Mage::getBaseUrl().’admin/oAuth_authorize’,// This URL is used only if we authenticate as Cunsumer.
    ‘consumerKey’ => ‘xxxxxxxxxxxxxxxxxxxx’,// Consumer key registered in server administration.
    ‘consumerSecret’ => ‘xxxxxxxxxxxxxxxxxxxxxxx’,// Consumer secret registered in server administration.
    ‘callbackUrl’ => Mage::getBaseUrl().’restconnect/login/callback’,// Url of callback action below.
    );

    // Initiate oAuth consumer with above parameters
    $consumer = new Zend_Oauth_Consumer($params);

    // Get request token
    $requestToken = $consumer->getRequestToken();

    // Get session
    $session = Mage::getSingleton(‘core/session’);

    // Save serialized request token object in session for later use
    $session->setRequestToken(serialize($requestToken));

    // Redirect to authorize URL
    $consumer->redirect();

    return;

    }

    public function callbackAction() {
    $session = Mage::getSingleton(‘core/session’);
    // Read and unserialize request token from session
    $requestToken = unserialize($session->getRequestToken());

    // Initiate oAuth consumer
    $consumer = new Zend_Oauth_Consumer($params);

    // Using oAuth parameters and request Token we got, get access token
    $acessToken = $consumer->getAccessToken($_GET, $requestToken);

    // Get HTTP client from access token object
    $restClient = $acessToken->getHttpClient($params);

    // Set REST resource URL
    $restClient->setUri(Mage::getBaseUrl().’api/rest/products’);

    // In Magento it is neccesary to set json or xml headers in order to work
    $restClient->setHeaders(‘Accept’, ‘application/json’);

    // Set method
    $restClient->setMethod(Zend_Http_Client::GET);

    //Make REST request
    $response = $restClient->request();
    // Here we can see that response body contains json list of products

    Zend_Debug::dump($response);

    return;
    }
    }

  11. Hi Darko. Great tutorial. I’m a newbie in magento. I’m using version 1.9.x. Could you open up the code to the test module. I’m really worried about this. I try to create a module test but I still can’t make it. Please share me the code of the test module.

    Thanks in advance.

  12. The given code is working fine. But in response only 10 products/customers/orders list are coming.

    How can we set LIMIT and PAGE number?

    when directly browsing URL (http://127.0.0.1/magentodemo/api/rest/products?limit=20&page=2) then result are coming, but when using same URL ($restClient->setUri(‘http://10.201.61.206/magentodemo/api/rest/products?limit=20&page=2’);) in Oauth then error comes. As below:
    {“messages”:{“error”:[{“code”:401,”message”:”oauth_problem=signature_invalid”}]}}

    Please help!

  13. Hello

    i could not get xml out , Please let me know where i have to change header type ,

    Thank you
    Vishwa

  14. I am getting the following error, Please help

    There has been an error processing your request

    Error in HTTP request

    Trace:
    #0 C:\wamp\www\magento\lib\Zend\Oauth\Http\RequestToken.php(51): Zend_Oauth_Http->startRequestCycle(Array)
    #1 C:\wamp\www\magento\lib\Zend\Oauth\Consumer.php(115): Zend_Oauth_Http_RequestToken->execute()
    #2 C:\wamp\www\magento\app\code\local\Practice\ControllerTest\controllers\IndexController.php(21): Zend_Oauth_Consumer->getRequestToken()
    #3 C:\wamp\www\magento\app\code\core\Mage\Core\Controller\Varien\Action.php(418): Practice_ControllerTest_IndexController->indexAction()
    #4 C:\wamp\www\magento\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch(‘index’)
    #5 C:\wamp\www\magento\app\code\core\Mage\Core\Controller\Varien\Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
    #6 C:\wamp\www\magento\app\code\core\Mage\Core\Model\App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
    #7 C:\wamp\www\magento\app\Mage.php(684): Mage_Core_Model_App->run(Array)
    #8 C:\wamp\www\magento\index.php(87): Mage::run(”, ‘store’)
    #9 {main}

    1. Hello,

      I got the same error.

      Can anyone have the solution for this issue?

      Thanks,

    2. found any solution for

      C:\wamp\www\magentoold\includes\src\Zend_Oauth_Http_RequestToken.php(54): Zend_Oauth_Http->startRequestCycle(Array)
      #1 C:\wamp\www\magentoold\includes\src\Zend_Oauth_Consumer.php(115): Zend_Oauth_Http_RequestToken->execute()
      #2 C:\wamp\www\magentoold\app\code\local\Multidots\HelloWorld\controllers\IndexController.php(28): Zend_Oauth_Consumer->getRequestToken()
      #3 C:\wamp\www\magentoold\includes\src\__default.php(14334): Multidots_HelloWorld_IndexController->indexAction()
      #4 C:\wamp\www\magentoold\includes\src\__default.php(18813): Mage_Core_Controller_Varien_Action->dispatch(‘index’)
      #5 C:\wamp\www\magentoold\includes\src\__default.php(18343): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
      #6 C:\wamp\www\magentoold\includes\src\__default.php(21279): Mage_Core_Controller_Varien_Front->dispatch()
      #7 C:\wamp\www\magentoold\app\Mage.php(684): Mage_Core_Model_App->run(Array)
      #8 C:\wamp\www\magentoold\index.php(83): Mage::run(”, ‘store’)

  15. use ‘authorizeUrl’ => ‘http://magento.loc/admin/oauth_authorize'(lower case oauth_authorize)
    instead of ‘authorizeUrl’ => ‘http://magento.loc/admin/oAuth_authorize’

    works for me, hope this will help others also.

  16. I tried your first example and working fine for admin login,
    but when I tried customer login it redirects to customer/account/login page.

    Does it work only for Admin user not Costomer?

    1. There might be a form key issue.
      Try to put the hidden form key <input name="form_key" type="hidden" value="getFormKey() ?>” /> below form tag in your phtml file.

  17. Hi,

    I’m getting following response .. Need Help!!

    object(Zend_Http_Response)#110 (5) {
    [“version”:protected] => string(3) “1.1”
    [“code”:protected] => int(406)
    [“message”:protected] => string(14) “Not Acceptable”
    [“headers”:protected] => array(8) {
    [“Date”] => string(29) “Mon, 19 Jan 2015 13:05:21 GMT”
    [“Server”] => string(22) “Apache/2.2.22 (Ubuntu)”
    [“Alternates”] => string(44) “{“api.php” 1 {type application/x-httpd-php}}”
    [“Vary”] => string(15) “Accept-Encoding”
    [“Content-encoding”] => string(4) “gzip”
    [“Content-length”] => string(3) “354”
    [“Connection”] => string(5) “close”
    [“Content-type”] => string(29) “text/html; charset=iso-8859-1”
    }
    [“body”:protected] => string(354) “�]QMO�0��W��@b�Z!(D��`Lb;pL�TꚐ����ݸ�H�?���y�x�o?7Kxپ��f���h,�j�}b�]�*y:b��DZ�7JZԆ��Au3���#��%z�E�R�*�R���L�r*�^�Z���C� !��%M�k�U@��~w
    {�u�D�.�QWUp������~’���I0��J�P��1в��r]k�g��#D�^%����^$4�j)>$�kXnS+���GL�z�G��H�\=�5u9� ~Ɩț�a>�emK�j�uiQ�)�.wE�Rw�*��t�fw�i��i��q�`:�g�n͇�?*��(��”
    }

  18. For your information, hope this could help

    I had the same 404 issue while calling API url. I am using ubuntu version 12.10
    By adding the following code to apache file i was able to fix the issue:
    File Path: /etc/apache2/sites-available/default
    Code:

    Options Indexes FollowSymLinks
    AllowOverride All

    1. use ‘authorizeUrl’ => ‘http://magento.loc/admin/oauth_authorize'(lower case oauth_authorize)
      instead of ‘authorizeUrl’ => ‘http://magento.loc/admin/oAuth_authorize’

      written in first comment. works for me on ubuntu,

  19. Could anyone please explain how the magento rest api written with any sample example or source code for fetching the orders or stuff like that.

    Any help would be greatly appreciated.

  20. Hi Drako,
    I am not expert in Magento. can you help me, where in my magento setup should i do this:
    “Create Magento controller class in your test module.”
    I mean which file or folder of my magento setup e.g.”app/code”,”skin”…

  21. Hi,

    How can we create new REST API with new resources. For example if i am creating a new extension and then i have to create API for it using new resources like event module then how i can i create REST API for it. Please guide me.

    Thanks

  22. Hi Darko

    thanks for your articles, very well explained. I have a question for you, are Magento REST APIs meant to be consumed within a user module? Let me explain. I am trying to connect with an external desktop app, however I cannot even get the unathorized token. I tracked than this problem to Server.php in Oauth module, and it looks like the following line is not getting the headers when trying to consume the service from an external application:

    $authHeaderValue = $this->_request->getHeader(‘Authorization’);

    I checked the request object and is not supposed to have the getHeader anyway, so that makes me confused. Originally, the request object is set on the constructor of the said class like this:

    if (is_object($request)) {
    if (!$request instanceof Zend_Controller_Request_Http) {
    throw new Exception(‘Invalid request object passed’);
    }
    $this->_request = $request;

    } else {
    $this->_request = Mage::app()->getRequest();

    }

    Thus, I am wondering if I am supposed to create the module to be able to consume the service, or if there is way to do it directly from an external app. Thanks!

  23. Many thanks for author.

    Only thing that I want to add:

    ~~~ Oauth_Client line 71
    case self::OAUTH_STATE_ACCESS_TOKEN:
    $accessToken = $this->_getAccessTokenFromSession();
    if ($accessToken && $accessToken instanceof Zend_Oauth_Token_Access) {
    $this->setAuthorizedToken($accessToken);
    }
    return self::OAUTH_STATE_ACCESS_TOKEN;
    ~~~
    you shouldn’t authorize each time with this code applied while session dies.

    1. Into the class, the function to get the sessionaccess token should be:

      private function _getAccessTokenFromSession()
      {
      $accessToken = unserialize($this->getSession()->getAccessToken());
      if ($accessToken && $accessToken instanceof Zend_Oauth_Token_Access) {
      return $accessToken;
      }
      return false;
      }

      The getAccessToken should be with double ‘s’ because the set is with double ‘S’

  24. Hi Darko, After successful login I’m being redirected to the customer account panel. As in your example you are redirected to the Authorise URL.
    Do you have any idea if this is to be expected or am i missing something?

    Any help would be appreciated.
    Thanks for the tutorial.

  25. @fabrice, you should create standard Magento module with regular configuration. Please try to Google for: create own controller magento and you will find the answer 🙂

  26. Hi Darko, I’m stucked at
    2.Create Magento controller class in your test module.
    3. Paste source code inside your controller to look like this:[…]

    Could you explain me which structure I have to create exactly?
    I created this in code/local, my module name is Vac
    /Vac/RestConnect/controllers/Test.php
    /Vac/RestConnect/etc/config.xml (but I don’t know what to put here exactly)
    And my module is declared in etc/modules/Vac_RestConnect.xml
    But I only get a 404 when trying.
    Any help would be much appreciated!
    cheers from Switzerland

    1. Hi fabrice ,
      change controller name test.php to testController.php

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.