5

I am having issues successfully making an AJAX call to Magento 2 REST API endpoints, using session-based authentication.

When I run the following javascript, I always receive a 401 (Not Authorized) error.

I am logged into the admin area as a user with all ACL privileges.

Here is the code that I am using to test the API:

require(['jquery'],function($){
    $.ajax({
        url: '/rest/V1/customers/1',
        type: 'get'
    });
});

From what I can tell, by reading the Magento 2 docs, session-based authentication for the admin area, should work.

http://devdocs.magento.com/guides/v2.1/get-started/authentication/gs-authentication-session.html

Can someone please tell me if it's possible to consume the API this way, and how to get it working correctly.

Thanks.

1

Yes. you can use Magento 2 API this way but you need to create a php page (say php page name is apicall.php) and make ajax call to that custom page instead Magento directly. On the the custom.php page you need to call Magento API.

apicall.Php

<?php
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
define("CONSUMERKEY", "XXXXXXXXXXXXXXX");
define("CONSUMERSECRET", "XXXXXXXXXXXXXXX");
define("ACCESSTOKEN", "XXXXXXXXXXXXXXX");
define("ACCESSTOKENSECRET", "XXXXXXXXXXXXXXX");         


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;
}


$actionName = $_REQUEST['action']; 

switch($actionName){
     case 'getcustomer':
      echo getCustomById();
      break;
}      

function getCustomById()
{

$customerId =  $_REQUEST['custid'];
$result =  null;
$method = 'GET';
$url = 'YOUR-MAGENTO-ROOT/index.php/rest/V1/customers/'.$customerId;

//
$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);

     return json_encode(array(             
            'result' => $result
        ));
}

calling Ajax to get custom data:

<script type="text/javascript">
        $(document).ready(function(){       
            $.getJSON('YOUR-MAGENTO-ROOT/apicall.php?action=getcustomer&custid=1', function(jd) {
                 var result =jQuery.parseJSON(jd.result);
                 console.log(result);
                 jQuery.each(result, function(index, value) {
                     console.log(index+":"+value);
                 });

               });
        });
    </script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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