1 回答

TA貢獻1934條經驗 獲得超2個贊
要在發送前使用 Authorization 標頭并獲取 POST 請求的長度,請參見下文。
$id = 'xxxx';
$secret='xxxx';
$url = "//myapi.com/endpoint";
/*
If the API endpoint is https it will be necessary to use certificate verification
techniques which require you have a valid cacert.pem file
You can download a valid copy from:-
https://curl.haxx.se/docs/caextract.html
*/
$cacert='/path/to/cacert.pem';
/*
The POST request body needs to have it's length measured for
the correct `Content-Length` header
*/
$params=array(
'client_id' => $id,
'client_secret' => $secret
);
$payload=http_build_query( $params );
/*
create the base64 encoded clientid/secret portion of the auth header
*/
$encoded = base64_encode( sprintf('%s:%s', $id, $secret ) );
/*
create the full auth header string
*/
$authheader = sprintf('Authorization: Basic %s', $encoded );
/*
create the content-length header string - use `strlen` to get the length!
*/
$contentlength = sprintf( 'Content-Length: %s', strlen( $payload ) );
/*
construct the headers array that will be sent with the request
*/
$headers=array(
'Content-Type: application/x-www-form-urlencoded',
$contentlength,
$authheader
);
/*
initialise the request and set options
*/
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, $url );
if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $ch, CURLOPT_CAINFO, $cacert );
}
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_USERAGENT, 'Google Chrome' );
curl_setopt( $ch, CURLINFO_HEADER_OUT, false );
$data = curl_exec( $ch );
$errs = curl_error( $ch );
$info = (object)curl_getinfo( $ch );
curl_close( $ch );
if( info->http_code==200 ){
/* OK */
print_r( $data );
} else {
print_r( $info );
}
- 1 回答
- 0 關注
- 280 瀏覽
添加回答
舉報