Hello,
Sharing how to send an API request using PHP Curl and Bearer token:
<?php
define('FRONT_API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxx');
/**
* Performs an API call using cURL
*
* @since 1.0.0
*
* @global string FRONT_API_KEY
*
* @param string $url URL.
* @param string $requestType 'GET', 'PUT', 'PATCH', etc.
* @param array $postFields Array of fields and values to be posted to URL
*
* @return array Associated array of JSON objects returned from API call.
*
*/
function api_call($url, $requestType, $postFields) {
try {
$ch = curl_init();
if ($ch === false) {
throw new Exception("Failed to initialize");
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestType);
if (isset($postFields)) {
$json = json_encode($postFields);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.77.0");
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json',
'Authorization: Bearer ' . FRONT_API_KEY
]);
$content = curl_exec($ch);
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
} else {
$httpReturnCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (($requestType == "GET" && $httpReturnCode != 200) || ($requestType == "PUT" && $httpReturnCode != 204)) {
throw new Exception("Failed https response. Content: " . $content, $httpReturnCode);
}
return json_decode($content, true);
}
} catch(Exception $e) {
// Handle exception
echo sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage());
} finally {
// Cleanup
if (is_resource($ch)) {
curl_close($ch);
}
}
}
// Usage - Update Conversation custom fields
$payload = file_get_contents('php://input');
$arrPayload = json_decode($payload, true);
$conversationId = $arrPayload['conversation']['id'];
$postFields = array(
"custom_fields" => array(
"Custom Field 1" => "Some value",
"Custom Field 2" => "Some value"
));
api_call('https://api2.frontapp.com/conversations/'. $conversationId, 'PATCH', $postFields);
?>