百度获取access_token

方法一

通过PHP:向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求,通过API Key和Secret Key获取的access_token

<?php

// 请求参数
$params = array(
    'grant_type' => 'client_credentials',
    'client_id' => 'csMh3hZ1X***QUSyZF',//API Key
    'client_secret' => '4YY9TId*****WB8bmD85Gk3syT'//Secret Key
);

// 发送 POST 请求获取 access_token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://aip.baidubce.com/oauth/2.0/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证
$result = curl_exec($ch);
curl_close($ch);

// 解析响应数据
if (empty($result)) {
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(array('success' => false, 'message' => 'Access token request failed'));
    exit;
}

$resp = json_decode($result, true);
if (empty($resp['access_token'])) {
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(array('success' => false, 'message' => 'Access token not found in response data'));
    exit;
}
$access_token = $resp['access_token'];

// 输出 access_token
echo $access_token;

?>

方法二

通过替换网址中的API Key和Secret Key也可以获取access_token

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]&

获取结果参考样式

24.eb1d0046cf9b03215200f43b0d9d745d.2592000.1682909052.282335-31877024

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。