The problem actually is defined in two steps:
1. How to define a REST Api which returns an array?
2. How to use that REST Api through javascript?
Description:
What I have done but not achieved results:
etc/frontend/webapi.xml
:
<?xml version="1.0"?> <routes
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/shetab/transaction/refid" method="POST">
<service class="Amaj\ShetabPayment\Api\ShetabServiceInterface" method="getTransRefId"/>
<resources>
<resource ref="anonymous" /><!-- works even if user has been logged of -->
</resources>
</route>
</routes>
etc/di.xml
:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Amaj\ShetabPayment\Api\ShetabServiceInterface"
type="Amaj\ShetabPayment\Model\ShetabService" />
</config>
Api/ShetabServiceInterface.php
:
interface ShetabServiceInterface
{
/** Returns Transaction Reference ID
*
* @param int $quoteId
* @return string|null
*/
public function getTransRefId($quoteId);
}
Model/ShetabService.php
:
namespace Amaj\ShetabPayment\Model;
interface ShetabService implements \Amaj\ShetabPayment\Api\ShetabServiceInterface
{
protected $_logger;
public function __construc(
\Psr\Log\LoggerInterface $logger
) {
$this->_logger = $logger;
}
/** Returns Transaction Reference ID
*
* @param int $quoteId
* @return string|null
*/
public function getTransRefId($quoteId)
{
$this->_logger->info('getTransRefId is called: ' . $quoteId);
$result = array(
'transRefId' => 50
);
return json_encode($result);
}
}
Javascript code:
define(
[
'jquery',
'Magento_Checkout/js/model/url-builder',
'mage/storage',
'Magento_Checkout/js/model/error-processor',
'Magento_Checkout/js/model/full-screen-loader'
],
function (
$,
urlBuilder,
storage,
errorProcessor,
fullScreenLoader
) {
'use strict';
return {
getTransRefId: function(quoteId, messageContainer) {
var result = storage.post(
urlBuilder.createUrl('/shetab/transaction/refid', {}),
JSON.stringify({
quoteId: quoteId
})
).fail(
function (response) {
errorProcessor.process(response, messageContainer);
fullScreenLoader.stopLoader();
}
);
console.log( JSON.stringify(result.responseText) );
}
};
}
);