记录一个PHP中Curl模拟请求Form-Data类型接口的坑
背景是对方业务的鉴权接口与明确要求了使用Form-Data 调试的时候发现参数获取不到
排查后是需要build下 随手记录下
/**
* 鉴权接口
* @param $params
* @return array
*/
public function getTocken()
{
//增加缓存读取
$cache_data = S('XXX');
if(!empty($cache_data)){
return $cache_data;
}
//提供和配置参数
$data = array();
$data['appKey'] = "";
$data['appSecret'] = "";
$appUrl = 'xxx';
//向发送数据
$ch = curl_init();
//将数组转换为符合 form-data 格式的字符串
$formData = http_build_query($data);
curl_setopt($ch, CURLOPT_URL, $appUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result = json_decode($response, true);
if ($httpCode == 200 && isset($result['code']) && $result['code'] == '0') {
S('xxx', $result, 3600);
return $result;
}else{
return ['status_code'=>$httpCode,'status_message'=>'鉴权失败!'];
}
}
随手吐槽 : 那些在老大面前汇报工作比谁都积极 工作时候却告诉别人不要努力混就完了的人真恶心!!!