1

I wonder how do I get pending orders using Magento API with OAuth token?

Thank you,

UPDATED

If I try as follows,

public function index2()
{           
    $consumerKey = 'kfkhypveth1upv6f4uwy5l9r7tdwmdp0';
    $consumerSecret = 't9ire4rup8wre5gbbqt3ic2q2snb6ogs';
    $accessToken = '9alfh5bntatd0gk3lwdjxv972erppnmk';
    $accessTokenSecret = 'rxmvwjrb9r8qq2hy0e2ijdytk2srrhmc';        
    $method = 'GET';
    $status_field     = "searchCriteria[filterGroups][0][filters][0][field]=status";
    $status_value     =  "searchCriteria[filterGroups][0][filters][0][value]=pending";//
    $status_condition = "searchCriteria[filterGroups][0][filters][0][condition_type]=eq";       
    $sc = $status_field . '&' . $status_value . '&' . $status_condition;

    $url = "http://127.0.0.1:8080/mg1/index.php/rest/V1/orders/?".$sc;

    $data = [
            'oauth_consumer_key' => $consumerKey,
            'oauth_nonce' => md5(uniqid(rand(), true)),
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_timestamp' => time(),
            'oauth_token' => $accessToken,
            'oauth_version' => '1.0',
    ];

    $data['oauth_signature'] = $this->sign($method, $url, $data, $consumerSecret, $accessTokenSecret);      
    $curl = curl_init();        
    curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => [
                    'Authorization: OAuth ' . http_build_query($data, '', ',')
            ]
    ]);

    $result = curl_exec($curl);
    curl_close($curl);
    echo '<pre>';       
    print_r(json_decode($result,false));        


 }//end of function

I get following error,

stdClass Object
(
[message] => Invalid signature
[trace] => #0 C:\wamp64\www\mg1\vendor\magento\framework\Oauth\Oauth.php(121): Magento\Framework\Oauth\Oauth->_validateSignature(Array, 't9ire4rup8wre5g...', 'GET', 'http://127.0.0....', 'rxmvwjrb9r8qq2h...')
#1 C:\wamp64\www\mg1\vendor\magento\module-webapi\Model\Authorization\OauthUserContext.php(82): Magento\Framework\Oauth\Oauth->validateAccessTokenRequest(Array, 'http://127.0.0....', 'GET')
#2 C:\wamp64\www\mg1\vendor\magento\module-authorization\Model\CompositeUserContext.php(78): Magento\Webapi\Model\Authorization\OauthUserContext->getUserId()
#3 C:\wamp64\www\mg1\vendor\magento\module-authorization\Model\CompositeUserContext.php(57): Magento\Authorization\Model\CompositeUserContext->getUserContext()
#4 C:\wamp64\www\mg1\vendor\magento\module-webapi\Model\WebapiRoleLocator.php(45): Magento\Authorization\Model\CompositeUserContext->getUserId()
#5 C:\wamp64\www\mg1\vendor\magento\framework\Authorization.php(47): Magento\Webapi\Model\WebapiRoleLocator->getAclRoleId()
#6 C:\wamp64\www\mg1\vendor\magento\framework\Interception\Interceptor.php(74): Magento\Framework\Authorization->isAllowed('Magento_Sales::...', NULL)
#7 C:\wamp64\www\mg1\vendor\magento\framework\Interception\Chain\Chain.php(70): Magento\Framework\Authorization\Interceptor->___callParent('isAllowed', Array)
#8 C:\wamp64\www\mg1\vendor\magento\framework\Interception\Chain\Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'isAllowed', Object(Magento\Framework\Authorization\Interceptor), Array, 'customerAuthori...')
#9 C:\wamp64\www\mg1\vendor\magento\module-customer\Model\Plugin\CustomerAuthorization.php(58): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}('Magento_Sales::...', NULL)
 #10 C:\wamp64\www\mg1\vendor\magento\framework\Interception\Chain\Chain.php(67): Magento\Customer\Model\Plugin\CustomerAuthorization->aroundIsAllowed(Object(Magento\Framework\Authorization\Interceptor), Object(Closure), 'Magento_Sales::...', NULL)
#11 C:\wamp64\www\mg1\vendor\magento\framework\Interception\Interceptor.php(138): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'isAllowed', Object(Magento\Framework\Authorization\Interceptor), Array, 'guestAuthorizat...')
#12 C:\wamp64\www\mg1\vendor\magento\module-webapi\Model\Plugin\GuestAuthorization.php(38): Magento\Framework\Authorization\Interceptor->Magento\Framework\Interception\{closure}('Magento_Sales::...', NULL)
#13 C:\wamp64\www\mg1\vendor\magento\framework\Interception\Interceptor.php(142): Magento\Webapi\Model\Plugin\GuestAuthorization->aroundIsAllowed(Object(Magento\Framework\Authorization\Interceptor), Object(Closure), 'Magento_Sales::...')
#14 C:\wamp64\www\mg1\var\generation\Magento\Framework\Authorization\Interceptor.php(26): Magento\Framework\Authorization\Interceptor->___callPlugins('isAllowed', Array, Array)
#15 C:\wamp64\www\mg1\vendor\magento\framework\Webapi\Authorization.php(37): Magento\Framework\Authorization\Interceptor->isAllowed('Magento_Sales::...')
#16 C:\wamp64\www\mg1\vendor\magento\module-webapi\Controller\Rest\RequestValidator.php(86): Magento\Framework\Webapi\Authorization->isAllowed(Array)
#17 C:\wamp64\www\mg1\vendor\magento\module-webapi\Controller\Rest\RequestValidator.php(70): Magento\Webapi\Controller\Rest\RequestValidator->checkPermissions()
#18 C:\wamp64\www\mg1\vendor\magento\module-webapi\Controller\Rest\InputParamsResolver.php(80): Magento\Webapi\Controller\Rest\RequestValidator->validate()
#19 C:\wamp64\www\mg1\vendor\magento\module-webapi\Controller\Rest.php(299): Magento\Webapi\Controller\Rest\InputParamsResolver->resolve()
#20 C:\wamp64\www\mg1\vendor\magento\module-webapi\Controller\Rest.php(216): Magento\Webapi\Controller\Rest->processApiRequest()
#21 C:\wamp64\www\mg1\var\generation\Magento\Webapi\Controller\Rest\Interceptor.php(37): Magento\Webapi\Controller\Rest->dispatch(Object(Magento\Framework\App\Request\Http))
#22 C:\wamp64\www\mg1\vendor\magento\framework\App\Http.php(135): Magento\Webapi\Controller\Rest\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
 #23 C:\wamp64\www\mg1\vendor\magento\framework\App\Bootstrap.php(258): Magento\Framework\App\Http->launch()
 #24 C:\wamp64\www\mg1\index.php(39): Magento\Framework\App\Bootstrap-    >run(Object(Magento\Framework\App\Http))
#25 {main}

)

But if I change the url as

 $url = "http://127.0.0.1:8080/mg1/index.php/rest/V1/orders/1";

then I get first order details.

Any idea why?

3
  • Did you know how to work with OAuth-based authentication Magento 2? Mar 23, 2017 at 12:40
  • I already have implemented OAuth and have saved access token in a table. Using this I wanted to get pending orders. Mar 23, 2017 at 13:07
  • You should try with GET: http://<magento_host>/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=status& searchCriteria[filter_groups][0][filters][0][value]=pending& searchCriteria[filter_groups][0][filters][0][condition_type]=eq Mar 23, 2017 at 13:31

4 Answers 4

3

You can use these samples to do all things that you want using the API. There are 3 different methods, you can use anyone of these 3 methods.

Remember to change the URL and method to what you want to do.

API REST using OAuth based authentication

<?php
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
    $url = urlEncodeAsZend($url);

    $data = urlEncodeAsZend(http_build_query($data, '', '&'));
    $data = implode('&', [$method, $url, $data]);

    $secret = implode('&', [$consumerSecret, $tokenSecret]);

    return base64_encode(hash_hmac('sha1', $data, $secret, true));
}

function urlEncodeAsZend($value)
{
    $encoded = rawurlencode($value);
    $encoded = str_replace('%7E', '~', $encoded);
    return $encoded;
}

// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = '1fuj3asjsk4w3qb3cx44ik5ue188s30s';
$consumerSecret = 'lcey0h5uyt26slvtws5okaiqh8ojju5d';
$accessToken = 'b41sqrw1cfqh598yfoygd836c4ll3cr8';
$accessTokenSecret = 'lywj45gighqo3knl6bv6i61n2jf6iv0a';

$method = 'GET';
$url = 'http://magento.m2/index.php/rest/V1/customers/2';

//
$data = [
    'oauth_consumer_key' => $consumerKey,
    'oauth_nonce' => md5(uniqid(rand(), true)),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_timestamp' => time(),
    'oauth_token' => $accessToken,
    'oauth_version' => '1.0',
];

$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url,
    CURLOPT_HTTPHEADER => [
        'Authorization: OAuth ' . http_build_query($data, '', ',')
    ]
]);

$result = curl_exec($curl);
curl_close($curl);
var_dump($result);

API REST using OAuth based authentication

<?php
$request = new SoapClient("http://magento.m2/index.php/soap/?wsdl&services=integrationAdminTokenServiceV1", array("soap_version" => SOAP_1_2));
$token = $request->integrationAdminTokenServiceV1CreateAdminAccessToken(array("username"=>"admin", "password"=>"GN2vKgfsszz43u"));

$opts = array(
            'http'=>array(
                'header' => 'Authorization: Bearer '.json_decode($token->result)
            )
        );

$wsdlUrl = 'http://magento.m2/soap/default?wsdl&services=directoryCurrencyInformationAcquirerV1';

$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, ['version' => SOAP_1_2, 'context' => $context]);

$soapResponse = $soapClient->__getFunctions();

API SOAP using Token based authentication

<?php
$userData = array("username" => "admin", "password" => "mypassword");
$ch = curl_init("http://magento.m2/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CUsRLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);

$ch = curl_init("http://magento.m2/index.php/rest/V1/customers/1");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

var_dump($result);
0
1

[Not test yet]

You should try with GET:

http://{magento_host}/rest/V1/orders?searchCriteria[filter_g‌​roups][0][filters][0‌​][field]=status& searchCriteria[filter_groups][0][filters][0][value]=pending&searchCriteria[filter_groups][0][filters][0][condition_type]‌​=eq

3
0

This works for me (I edited my code a little to show):

// First log in
$url = 'http://[your-domain]/rest/V1/integration/admin/token';
$body = '{"username":"user", "password":"pass"}';
$header = 'Content-type: application/json';
$options = [    'method' => 'POST',
                'content' => $body,
                'header' => $header
           ];
$context = stream_context_create(['http' => $options]);
$token = json_decode(file_get_contents($url, false, $context));

// Some settings

$header = 'Authorization: Bearer ' . $token . "\r\n"
    . 'Content-type: application/json';
$options = [    'method' => 'GET',
                'content' => $body,
                'header' => $header
           ];
$context = stream_context_create(['http' => $options]);

$url = 'http://[your-domain]/index.php/rest/V1/orders/'
    . '?searchCriteria[filter_groups][0][filters][0][field]=status&searchCriteria[filter_groups][0][filters][0][value]=pending'
    //. '&searchCriteria[sortOrders][0][field]=increment_id' // To sort Desc
    . '&fields=items[increment_id,entity_id]';

//print file_get_contents($url, false, $context) . "\n"; // Check full json if you want

// Generate json output
$json_contents = file_get_contents($url, false, $context) . "\n";
$order = json_decode($json_contents);
$answer = '{';
if ($order->items) { 
    foreach($order->items as $key => $value) {
        $answer .= '"'. $value->entity_id . '":"' . $value->increment_id . '",';
    }
    $answer = substr($answer,0,strlen($answer)-1);
    $answer .= '}';
    echo $answer;
}
1
  • Thank you Gediminas for your answer. I wanted to use $consumerKey and $consumerSecret approach to login to Magento 2. I tried with username and password approach. It works fine for me too. Just wondering why its not working with this method. Mar 25, 2017 at 6:13
0

Use swagger instead of this.

Examples:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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