因此,我们希望创建一个私有API,允许其他人与我们的服务交互,例如通过api保存数据库中的某些内容或获取某些信息。
API本身只期望可以通过任何编程语言将JSON数据传递给API。与其他api (如facebook )不同,我们不给用户任何文件来使用API,就像facebook确实为不同语言提供类来与他们的api交互一样。因此,我们认为api用户可以使用任何语言向我们发送json数据,并在此基础上通过查询字符串提供的use参数调用api的某些函数。
下面是API最基本级别的代码,可以让您了解它是如何工作的:
class Api
{
/**
* Default function called when API url is accessed
*
* @return mixed
* @throws Exception
*/
public function index()
{
$appId = isset($_GET['appId']) ? $_GET['appId'] : null;
$apiKey = $_GET['apiKey'] ? $_GET['apiKey'] : null;
$method = $_GET['use'] ? $_GET['use'] : null;
$data = json_decode(file_get_contents("php://input"), true);
if ($this->validateRequest($appId, $apiKey, $method)) {
return call_user_func_array(array($this, $method), array($data));
}
}
private function validateRequest($appId, $apiKey, $method)
{
# check referer
$requestUri = isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : null;
if (!$requestUri) {
$this->bye('HTTP_REFERER is required!');
}
# check if method exists
if (!$method || !method_exists('Apicall', $method)) {
$this->bye('Invalid \'use\' value!');
}
# check appId, apiKey and requestUri
if (!$appId) {
$this->bye('Invalid appId!');
}
if (!$apiKey) {
$this->bye('Invalid apiKey!');
}
$db = new DB();
$db->where('appid', $appId);
$db->where('apikey', $apiKey);
$db->where('request_uri', pathWithoutEndingSlash($requestUri));
$db->get();
if ($db->exists() && $db->result_count() > 0) {
return true;
}
$this->bye('Request Denied!');
}
private function bye($error)
{
echo json_encode(array('Error' => $error));
exit;
}
private function getIntervals()
{
$values = array('monthly', 'quarterly', 'yearly', 'single_payment');
echo json_encode($values);
}
}可以看到,我们验证了我们的db中是否存在appId、apiKey和requestURI (我们已经为api用户生成),然后调用调用中通过use查询字符串变量指定的方法:
http://localhost/myapi/api.php?appId=local&apiKey=98a4d2e5b7fa21d424a0932c7f47a6943d57d64b&use=getIntervals
这是制作私有API的正确方式,还是我仍然遗漏了什么?
发布于 2013-12-05 11:00:30
任何监听请求的人(因此,如果您在WIFI上调用api或以AJAX调用)将能够看到您的appId和apiKey。因此,他们也可以调用您的api。一个更好的方法是:
如果您想要一个快速的REST API,我可以推荐Restler。它还包括身份验证。http://luracast.com/products/restler
https://stackoverflow.com/questions/20398109
复制相似问题