Hi, I am trying to get nutricional information about a product. I developt these code in PHP but I can´t find the way to return a correct Oauth Signature. I don´t know if the problem is that the sequence of codifications is incorrect. If anybody can help me I would appreciate it.
Thank you.
// --- VARIABLES ---
$url = '
https://platform.fatsecret.com/rest/food/v5?';
$timestamp = time();
$nonce = bin2hex(random_bytes(16));
// --- PARÁMETROS OAUTH PARA EL BODY ---
$oauth_params = [
'food_id' => urlencode($_POST['id_ingrediente']),
'format' => 'json',
'method' => 'food.get',
'oauth_consumer_key' => CONSUMER_KEY,
'oauth_nonce' => $nonce,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $timestamp,
'oauth_version' => '1.0'
];
$param_string = http_build_query($oauth_params, '', '&', PHP_QUERY_RFC3986);
// --- CREAR BASE STRING PARA FIRMA ---
$method = 'POST';
$base_string = rawurlencode($method) . '&' . rawurlencode('https%3A%2F%
2Fplatform.fatsecret.com%2Frest%2Fserver.api') . '&' . rawurlencode($param_string);
// --- CLAVE DE FIRMA ---
$signing_key = rawurlencode(CONSUMER_SECRET) .'&';
// --- GENERAR OAUTH_SIGNATURE ---
$oauth_signature = base64_encode(hash_hmac('sha1', $base_string, $signing_key, true));
//echo $oauth_signature;
// --- AGREGAR LA FIRMA A LOS PARÁMETROS ---
$oauth_params['oauth_signature'] = $oauth_signature;
//Ordenamos por orden alfabético:
ksort($oauth_params);
// --- CONSTRUIR HEADER AUTHORIZATION (opcional) ---
$auth_header = 'Authorization: OAuth ';
$header_parts = [];
foreach ($oauth_params as $k => $v) {
$header_parts[] = $k . '="' . rawurlencode($v) . '"';
}
$auth_header .= implode(', ', $header_parts);
echo $auth_header;
// --- BODY POST CON EL RESTO DE PARÁMETROS ---
$post_body = http_build_query($oauth_params, '', '&', PHP_QUERY_RFC3986);
//echo $auth_header;
// --- CURL ---
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $post_body, // NECESARIO
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
$auth_header
),
]);