How to secure API key when making AJAX call from W

2019-02-26 03:29发布

问题:

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?

回答1:

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.