I want to make GET, POST & PUT calls to a 3rd party API and display the response on the client side via AJAX. The API calls require a token, but I need to keep that token secret / not in the client-side JS code.
I've seen a few suggestions like this one to have server-side code in the middle that would be queried by the AJAX, and would handle the actual API call. I'm OK working directly with the API from AJAX, but I'm unsure of how to work with a two-step process in order to hide the token from users. My Googling hasn't turned up any pointers on a best-practice method of achieving this.
In my case the server in the middle would be running PHP, so I assume cURL / Guzzle is the straightforward option to make the API calls with the token. The API responses will be JSON.
Can anyone please give me a rough example of how this would be achieved using jQuery.ajax(), to PHP, to the 3rd party API?
Alternatively if there are any quality resources that cover this method in detail, I'd appreciate a link. Equally, if this is a terrible method to use it'd be great to know why.
Edit
Probably worth noting that I want as much flexibility in deploying this as possible; it would be used on multiple sites with unique configurations, so ideally this would be implemented without altering server or hosting account configuration.
It is bit hard without sample code. But As per I understood you can follow this,
AJAX CALL
$.ajax({
type: "POST",
data: {YOU DATA},
url: "yourUrl/anyFile.php",
success: function(data){
// do what you need to
}
});
In PHP
Collect your posted data and handle API, Something like this
$data = $_POST['data'];
// lets say your data something like this
$data =array("line1" => "line1", "line2"=>"line1", "line3" =>"line1");
$api = new Api();
$api->PostMyData($data );
Example API Class
class Api
{
const apiUrl = "https://YourURL/ ";
const targetEndPoint = self::apiUrl. "someOtherPartOFurl/";
const key = "someKey819f053bb08b795343e0b2ebc75fb66f";
const secret ="someSecretef8725578667351c9048162810c65d17";
private $autho="";
public function PostMyData($data){
$createOrder = $this->callApi("POST", self::targetEndPoint, $data, true);
return $createOrder;
}
private function callApi($method, $url, $data=null, $authoRequire = false){
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
if($authoRequire){
$this->autho = self::key.":".self::secret;
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $this->autho);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
}