Snippets
Created by
Luke Banka
last modified
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | <html>
<title>Magento REST client</title>
</html>
<body>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
/**
* Client for the Magento API
*/
MagentoRestClient = function(entryPoint, apiLogin, apiKey, method, timeout)
{
var self = this;
self.entryPoint = entryPoint;
self.apiLogin = apiLogin;
self.apiKey = apiKey;
self.method = method;
self.timeout = timeout;
/**
* @param string method the remote procedure to call
* @param object params parameters for the RPC
* @param callback onSuccess callback for successful request. Expects one parameter (decoded response object)
* @param callback onError callback for failed request. Expects one parameter (error message)
*
* @return void
*/
self.jsonRpc = function(method, params, onSuccess, onError) {
var request = {
method : method,
params : params,
jsonrpc : "2.0",
id : 1
};
var httpClient = new XMLHttpRequest;
httpClient.onload = function(e) {
try {
var response = JSON.parse(this.responseText);
} catch (jsonError) {
return onError(jsonError);
}
if (response.error) {
if (response.error.code == 5) { // session expired
self.sessionId = null;
}
return onError(response.error.message);
}
onSuccess(response);
};
httpClient.onerror = function(e) {
onError(e.error + '; Response:' + this.responseText);
};
httpClient.ontimeout = function(e) {
onError(e.error + '; Response:' + this.responseText);
};
httpClient.open(self.method, self.entryPoint);
httpClient.setRequestHeader("Content-type", "application/json");
httpClient.send(JSON.stringify(request));
}
/**
* Retrieve session id for API
*
* @return JQuery.Deferred deferred object for asynchronous chaining
*/
self.login = function() {
var deferred = new jQuery.Deferred();
if (self.sessionId) {
deferred.resolve();
return deferred;
}
try {
self.jsonRpc('login', [self.apiLogin, self.apiKey], function(response) {
if (response && response.result) {
self.sessionId = response.result;
deferred.resolve();
} else {
deferred.reject('Login failed.');
}
}, function(error) {
deferred.reject(error);
});
} catch (rpcError) {
deferred.reject(rpcError);
}
return deferred;
};
/**
* Updates order states in Magento
*
* @param string method name of the remote method
* @param object args arguments for the remote method
*
* @return JQuery.Deferred deferred object for asynchronous chaining
*/
self.call = function(method, args) {
var deferred = new jQuery.Deferred();
if (!self.sessionId) {
deferred.reject('No session.');
return;
}
var callParams = {
sessionId : self.sessionId,
apiPath : method,
args : args
};
try {
self.jsonRpc('call', callParams, function(response) {
deferred.resolve(response.result);
}, function(error) {
deferred.reject(error);
});
} catch (rpcError) {
deferred.reject(rpcError);
}
return deferred;
};
};
</script>
<script>
var cartId = localStorage.getItem('cartId');
var magento = new MagentoRestClient('http://192.168.50.18/api/jsonrpc/', 'magentoapi', 'magentoapi', 'POST', 60);
// API Login
magento.login().then(function() {
// API Load Products
magento.call('catalog_product.list', []).then(
function(jsonResponse) {
displayProducts(jsonResponse);
}, function(error) {
console.log('Magento API error: ' + error);
}
);
// API Create Cart and save it's ID
if(!cartId) {
magento.call('cart.create', []).then(
function (jsonResponse) {
localStorage.setItem('cartId', jsonResponse);
loadCart();
}, function (error) {
console.log('Magento API error: ' + error);
}
);
} else {
loadCart();
}
});
// Load Cart Info and Items
function loadCart() {
jQuery('#cartLoader').show();
jQuery('#cartInfo').html('');
jQuery('#cartItems').html('');
// API Load Cart Info
magento.call('cart.info', [cartId]).then(
function (jsonResponse) {
displayCartInfo(jsonResponse);
}, function (error) {
console.log('Magento API error: ' + error);
}
);
// API Load Cart Items
magento.call('cart_product.list', [cartId]).then(
function (jsonResponse) {
displayCartItems(jsonResponse);
}, function (error) {
console.log('Magento API error: ' + error);
}
);
}
function addToCart(sku) {
// Add To Cart
magento.login().then(function () {
var data = [{sku: sku, quantity: 1}];
magento.call('cart_product.add', [cartId, data]).then(
function (jsonResponse) {
loadCart();
}, function (error) {
console.log('Magento API error: ' + error);
}
);
});
}
</script>
<script>
function displayProducts(aProducts) {
jQuery('#productsLoader').hide();
jQuery(aProducts).each(function(i){
var item = aProducts[i];
var html = jQuery('#template-product').html();
html = html.replace(/{{name}}/g, item.name);
html = html.replace(/{{sku}}/g, item.sku);
jQuery('#products').append(html);
});
}
function displayCartInfo(oCart) {
jQuery('#cartLoader').hide();
var html = jQuery('#template-cart-info').html();
html = html.replace(/{{items_qty}}/g, oCart.items_qty);
jQuery('#cartInfo').html(html);
}
function displayCartItems(aProducts) {
jQuery(aProducts).each(function(i){
var item = aProducts[i];
var html = jQuery('#template-cart-item').html();
html = html.replace(/{{name}}/g, item.name);
jQuery('#cartItems').append(html);
});
}
</script>
<div style="display: none;" id="templates">
<div id="template-product">
<li>{{name}} <a href="#" onclick="addToCart('{{sku}}');">Add To Cart</a></li>
</div>
<div id="template-cart-info">
Products: {{items_qty}}
</div>
<div id="template-cart-item">
<li>{{name}} <a class="removeFromCart" href="#">Remove from Cart</a></li>
</div>
</div>
<h1>Magento REST Client</h1>
<div style="width: 100%;">
<div style="width: 50%; background-color: #00ACEE; float: left;">
<h2>Products</h2>
<span id="productsLoader">Loading products...</span>
<ul id="products"></li>
</div>
<div style="width: 50%; background-color: #008844; float: right;">
<h2>Cart <a href="#" onclick="loadCart();">Reload</a></h2>
<span id="cartLoader">Loading cart...</span>
<div id="cartInfo"></div>
<ul id="cartItems"></ul>
</div>
</div>
</body>
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.