This is an example of a proxy to keep the API authentication token safe. Instead of hardcoding the authentication token client side (on the HTML page), the token is kept server side. All requests from your App to the EValue API, instead go via your proxy. The proxy will add the authentication token to the header, and then send the request to the EValue API server.
This code snippet takes 2 arguments, methodData
and methodOptions
. methodData
contains the data sent so the API, methodOptions
contains the URL of the specific API to call and the method type (GET or POST). Here is an example of the URL to this proxy for the State Benefit Age API call: /?methodData={"dateOfBirth":"1980-05-11","gender":"FEMALE"}&methodOptions={"pathname":"/state-benefit/1.0.0/stateBenefitAge/age", "method": "POST"}
<?php
header('Content-Type: application/json');
$token = "0b72096d-7c56-35ea-9551-ef61e5816f4e" ;
/**
* Main method.
A. ) Quick sanitise of inputs. Check user has passed in the name of the API they want to call
B.) Convert methodOptions JSON string into an object, to make it easier for future methods to process it
*/
function main(){
if(isset($_REQUEST['methodOptions']) ){
$methodOptions = json_decode($_REQUEST['methodOptions']);
if(property_exists($methodOptions,"pathname")){
$result = sendRequest($methodOptions, $_REQUEST['methodData']);
}else{
$result = "{\"error\":\"Missing pathname\"}";
}
}else{
//error.
$result = "{\"error\":\"Missing pathname\"}";
}
return $result;
}
function sendRequest($params, $body){
$options = setUpOptions($params, $body);
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$err = curl_error($curl);
$contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
$httpResponseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if($httpResponseCode == 417) {
/*417 == Expectation Failed.
The server wants us to add the empty "Expect" request header. (I think because the request is too big).
Send the request again, but with the "Expect" header
*/
$params->expect = "";
sendRequest($params, $body);
} else {
echo $response;
}
}
function setUpOptions($params, $body) {
$method = (property_exists($params,"method")) ? strtoupper($params->method) : "POST";
$headers = setUpHeaders($params);
$options = array(
CURLOPT_URL => "https://api.evalueproduction.com".$params->pathname,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $headers
);
return $options;
}
function setUpHeaders($params) {
global $token;
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer ". $token,
"Cache-Control: no-cache",
);
if(property_exists($params,"expect")) {
array_push($headers,"Expect: ".$params->expect);
}
return $headers;
}
main();
?>