某些API要求在請求中提供 auth-token(身份驗證令牌)。
通常,API文檔會說明如何生成 auth-token,例如通過提交 client_id、client_secret 和 grant_type。
文件命名為 api/auth.php:
$curl = curl_init();
$auth_data = array(
'client_id' => 'XBnKaywRCrj05mM-XXX-6DXuZ3FFkUgiw45',
'client_secret' => 'btHTWVNMUATHEnF-XXX-2nQabKcKVo3VXtU',
'grant_type' => 'client_credentials'
);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $auth_data);
curl_setopt($curl, CURLOPT_URL, 'https://api-site.com/oauth/token');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if (!$result) {
die("Connection Failure");
}
curl_close($curl);
echo $result;
注意:auth-token可能有時效限制(如兩周),并且限制同時有效的數量。
const apiAuth = async () => {
try {
const response = await fetch('https://my-site.com/api/auth.php');
if (response.ok) {
return response.json();
}
throw new Error(apiAuth_response: ${response});
} catch (error) {
console.error(apiAuth: ${error});
}
};
在GET請求中,通常將auth-token作為參數附加到URL:
if (isset($_POST['access_token'])) {
$app_key = 'XBnKaywRCrj05m-XXX-v6DXuZ3FFkUgiw45';
$utoken = $_POST['access_token'];
$url = 'https://api-site.com/v1/apps/' . $app_key . '/reviews?utoken=' . $utoken;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if (!$result) {
die("Connection Failure");
}
curl_close($curl);
echo $result;
}
const getAllReviews = async () => {
const auth = await apiAuth();
const data = {
access_token: auth.access_token,
token_type: auth.token_type,
};
try {
$.post({
type: 'POST',
url: 'http://my-site.com/api/get_all_reviews.php',
data: data,
}).success(res => {
const data = JSON.parse(res);
const reviews = data.reviews;
displayAllReviews(reviews, $('.review-list'));
});
} catch (error) {
console.error(getAllReviews: ${error});
}
};
displayAllReviews為自定義函數,用于處理和展示評論數據。
POST請求同樣需要auth-token,示例PHP文件 post_review.php:
if (isset($_POST['success'])) {
$p_url = 'https://product-link.com';
$email = $_POST['email'];
$post_array = array(
'appkey' => 'XBnKaywRCrj05m-XXX-v6DXuZ3FFkUgiw45',
'domain' => 'https://api-site.com',
'product_url' => $p_url,
'email' => $email,
'review_content' => $_POST['message'],
'review_title' => $_POST['title'],
'review_score' => $_POST['star_rating_value']
);
postReview($post_array);
} else {
$response = array(
'response' => 'error',
'message' => 'POST is required to use this function'
);
}
function postReview($post_array) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_array);
curl_setopt($curl, CURLOPT_URL, 'https://api-site.com/v1/reviews');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if (!$result) {
die("Connection Failure");
}
curl_close($curl);
echo $result;
}
function postSiteReview(data, form) {
$.ajax({
url: 'https://my-site.com/api/post_review.php',
type: 'post',
data: data,
success: function (result) {
let res = JSON.parse(result);
if (res.code === 200) {
form.find('.success-message').fadeIn();
} else {
let message = res.response === 'error' ? res.message : '';
if (res.status && res.status.code === 500) {
message = res.status.message;
}
$('p.error-msg').text(Uh ooh.. ${message});
}
},
error: function (err) {
console.log('$.ajax error: ' + err);
}
});
}
如果PHP文件和前端位于不同域名,可能會遇到 CORS 問題。解決方法:
header("Access-Control-Allow-Origin: https://my-site.com");
允許指定域名訪問PHP文件,避免跨域錯誤。
通過本文示例,您已掌握:
無論是構建內部系統還是與第三方API集成,這些方法都能確保安全高效的數據交互。
原文鏈接: https://weichie.com/blog/php-curl-api-calls-authentication/