如何从Wordpress网站进行AJAX调用时保护API密钥



我想对已经列出我们公司产品的本地在线商店进行 API 调用,然后返回其详细信息、标签、照片等的 JSON。

如何保护我的 API 密钥并向另一个网站发出 GET/POST 请求?

要对您网站的访问者隐藏 API 密钥,请在您自己的网站上使用 PHP 脚本充当中继。它接收 Ajax 请求(没有 API 密钥(;添加您的密钥并发出自己的 API 请求;然后将响应返回到浏览器。

例如 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脚本(一个非常粗糙的骨架(:

<?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"位可能需要更改,例如"header"(脚本的第一行(可能不需要。

最新更新