从Wordpress网站进行AJAX调用时如何保护API密钥? [英] How to secure API key when making AJAX call from Wordpress website?
问题描述
我想对已经列出我们公司产品的本地在线商店进行API调用,然后返回其详细信息,标签,照片等的JSON.不包括敏感信息,除了保护我的API密钥.
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.
如何保护我的API密钥并向另一个网站发出GET/POST请求?
How do I secure my API key and make GET/POST requests to another website?
推荐答案
要在您网站的访问者中隐藏API密钥,请在您自己的网站上使用PHP脚本充当中继.它接收Ajax请求(没有API密钥);添加您的密钥并发出自己的API请求;然后将响应返回到浏览器.
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.
例如Javascript
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脚本(一个非常粗糙的框架):
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));
?>
注意:在我的脚本中,通常将"HTML"传递回浏览器.因此,脚本的"Json"位可能需要更改,例如可能不需要标头"(脚本的第一行).
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.
这篇关于从Wordpress网站进行AJAX调用时如何保护API密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!