前言
折磨了我一个下午
今天对接一个第三方鉴权验证接口,一直没有通过,排查各种原因,最后发现竟然是data参数没有json_encode编码,导致那边接收不到,验证失败,我还一直以为是请求头没有传签名过去……
1、代码
1、post请求
//发送post请求-使用自带的curl
public static function PostDateByCurl($url, $headers, $data, $isSave = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
//header设置示例
//$headers = array();
//$headers[] = 'User-Agent: Apipost client Runtime/+https://www.apipost.cn/';
//$headers[] = 'Authorization: MTE2MjQ5NzY6MjAyMjEwMDgxNjIwMDM=';
//$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
if ($isSave) {
Log::WriteToFile("PostDateByCurl", "url:" . $url . ";\nheaders:" . json_encode($headers) . ";\ndata:" . json_encode($data) . ";\nresult:" . $result);
} else {
Log::WriteToFile("PostDateByCurl", "url:" . $url . ";\nheaders:" . json_encode($headers) . ";\ndata:" . json_encode($data));
}
curl_close($ch);
$_resultData = json_decode($result);
return json_encode($_resultData);
}
2、测试调用
//线索池鉴权测试
function test1(){
$_timestamp='20221008162003';//date('YmdHis');
//获取签名
$_sgin=WxFun::GetXscSgin($_timestamp);
$_auth_token=WxFun::GetXscAuthToken($_timestamp);
$_appId="11624976";
$_secret="xxx";
$_date_array=array(
"appId"=>$_appId,
"secret"=>$_secret,
"timestamp"=>$_timestamp,
"auth_token"=>$_auth_token,
"sign"=>$_sgin
);
$headers = array();
$headers[] = 'Authorization: MTE2MjQ5NzY6MjAyMjEwMDgxNjIwMDM=';
$headers[] = 'Content-Type: application/json';
$_url="http://xxx/v1/{$_appId}/auth";
$_result=WxFun::PostDateByCurl($_url,$headers,$_date_array,true);
return $_result;
}