I want to make an API call to a local online store which already lists our company's products, and then have a return JSON of its details, tags, photos, etc. No sensitive information included, other than protecting my API key.
How do I secure my API key and make GET/POST requests to another website?
AJAX calls are itself protect CSRF using “Common Origin Policy” when CORS is disabled and JSONP requests are blocked. To prevent CSRF attack one step ahead, we can implement Anti Forgery token similar to MVC framework. AJAX calls can be called from web application as well as from MVC. In MVC, @html.
The only way to protect an API key is to keep the key only on the server. The client asks your server for some data and your server uses the API key to get the data from the API source and returns it back to the client. Anything you send to the client will be visible to any hacker.
AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX. Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here.
When you're going to make an Ajax call you'll need to send the request to the admin-ajax. php file, which is a part of WordPress core. This file is responsible for handling and processing all of your Ajax requests within the WordPress context. Do NOT use the direct URL of the file path.
To hide the API key from visitors to your site use a PHP script on your own site to act as a relay. It receives the Ajax request (without API key); adds your key and makes its own API request; then returns the response to the browser.
e.g. Javascript
var dataString = "item=" + $('#item').val() + "&qty=" + $('#quantity').val();
$.ajax({type: "POST", url:"/myrelays/getstockdata.php", data: dataString, success: function(data){ your function to handle returned data } });
getstockdata.php script (a very rough skeleton):
<?php
header('Content-Type: application/json; charset=utf-8');
$api_key = 'xyz1234';
$result = array('status'=>'Error','msg'=>'Invalid parameters');
// your code to sanitize and assign (Ajax) post variables to your PHP variables
// if invalid: exit(json_encode($result));
// make API request with $api_key
$url = 'https://api.provider.com/stockdata.json?key=' . $api_key . '&item=' . $item . '&qty=' . $qty;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_FAILONERROR, TRUE); // identify as error if http status code >= 400
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); // returns as string
$api_response = curl_exec($ch);
if(curl_errno($ch) || curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200 ) :
$result['msg'] = 'Item not found or unable to get data. ' . curl_error($ch);
curl_close($ch);
exit(json_encode($result));
endif;
curl_close($ch);
$decodedData = json_decode($api_response, true);
// check for success and do any server side manipulation of $decodedData
$result['status'] = 'OK'];
$result['msg'] = '$decodedData';
exit(json_encode($result));
?>
Note: In my scripts I usually pass "HTML" back to the browser. So the "Json" bits of the script may need altering e.g. "header" (first line of script) may not be needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With