以下为千帆开放平台http类
<?php
class QF_HTTP_CLIENT
{
private $domain = 'https://xxx.qianfanyun.com'; // 站点hostname
private $token = 'xxxxxxxxx'; // 开放平台token
/**
* @param string $method 请求方式
* @param string $path 请求路径
* @param array $requestBody 请求体参数
* @return array
* @throws Exception
*/
private function _request($method, $path, $requestBody)
{
$header = array(
"Authorization: Bearer {$this->token}",
"Content-Type: application/x-www-form-urlencoded",
"Cache-Control: no-cache",
"Accept: application/json",
"User-Agent: QianFanHttpClient/1.0.0"
);
$url = "{$this->domain}/openapi/{$path}";
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_HEADER, 0);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $method);
if (count($requestBody)) {
curl_setopt($curlHandle, CURLOPT_POST, 1);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, http_build_query($requestBody));
}
curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 2); // 连接超时
curl_setopt($curlHandle, CURLOPT_TIMEOUT, 2); // 响应超时
$response = curl_exec($curlHandle);
$error = curl_error($curlHandle);
$errno = curl_errno($curlHandle);
// $status = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle);
if ($error) {
throw new Exception("cURL Error #{$errno}. $error", 1);
}
$data = json_decode($response, true);
if (json_last_error() != JSON_ERROR_NONE) {
$error = json_last_error_msg();
$errno = json_last_error();
throw new Exception("Json Parsing Error #{$errno}. $error", 1);
}
return $data;
}
public function get($path)
{
return $this->_request('GET', $path, []);
}
public function put($path, $data)
{
return $this->_request('PUT', $path, $data);
}
public function post($path, $data)
{
return $this->_request('POST', $path, $data);
}
public function delete($path, $data)
{
return $this->_request('DELETE', $path, $data);
}
}
// 使用示例
$client = new QF_HTTP_CLIENT();
// 查询用户详情示例
$data = $client->get('users/2');
print_r($data);
// 修改用户信息示例
$data = $client->put('users/2', ['signature' => '试试修改签名21212']);
print_r($data);
// 解析wap_token示例
$data = $client->post('users/parse-wap-token', ['wap_token' => 'xxxxxxxx']);
print_r($data);
文档更新时间: 2024-08-21 11:39 作者:漫漫