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>