百度智能云服务内置很多api接口(文字识别,企业信息识别,等),所有百度智能云自带的接口都会用到百度的access_token
CREATE TABLE `bd_ak` (
`id` int(10) UNSIGNED NOT NULL,
`body` text NOT NULL COMMENT '返回内容',
`create_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='百度Access_token表' ROW_FORMAT=DYNAMIC;
ALTER TABLE `bd_ak`
ADD PRIMARY KEY (`id`);
ALTER TABLE `bd_ak`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;
public function run()
{
//获取数据库内是否有没过期的Access_token
$bd_ak=db('bd_ak')->where('create_time','>=',time())->find();
if ($bd_ak){
//判断如果有Access_token则直接json_decode返回
return json_decode($bd_ak['body']);
}else{
//判断如果没有Access_token,就需要通过AK和SK获取 Access_token
$client_id='';//创建应用时返回的API key
$client_secret='';//创建应用时返回的Secret Key
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id=".$client_id."&client_secret=".$client_secret."&grant_type=client_credentials",
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept: application/json'
),
));
$response = curl_exec($curl);
$return_data=json_decode($response);
curl_close($curl);
$data['body']=$response;
$data['create_time']=time()+$return_data->expires_in;
//存储access_token方便下次查询
db('bd_ak')->insert($data);
return $return_data;
}
}