使用Curl调用API



我需要使用curl调用这个命令。

http -a $CLIENT_ID:$CLIENT_SECRET --form POST https://api-sandbox.com/auth/token grant_type=client_credentials scope=access_token_only

我试过跟随,但没有通过

$URL = "https://api-sandbox.com/auth/token";

$data = array(
'grant_type' => "client_credentials",
'scope' => "access_token_only"
);
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_APPEND, "$CLIENT_ID:$CLIENT_SECRET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$data=curl_exec($ch);
curl_close($ch);

我得到以下错误

{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

我该怎么做?

Thx

----------------附加信息------------------

oAuth2.0正在用于身份验证

此代码应该适用于

<?php
$URL = "https://api-sandbox.com/auth/token";
$data = [
'grant_type' => "client_credentials",
'scope'      => "access_token_only",
];
$client_id = getenv('CLIENT_ID');
$client_secret = getenv('CLIENT_SECRET');
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ( $ch === false ) {
throw new RuntimeException( 'failed to initialize' );
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-sandbox.com/auth/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials&scope=access_token_only");
curl_setopt($ch, CURLOPT_USERPWD, $client_id . ':' . $client_secret);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
$content = curl_exec( $ch );
curl_close( $ch );
if ( $content === false ) {
throw new RuntimeException( curl_error( $ch ), curl_errno( $ch ) );
}
/* Process $content here */
// Close curl handle
curl_close( $ch );
} catch ( RuntimeException $e ) {
trigger_error(
sprintf(
'Curl failed with error #%d: %s',
$e->getCode(),
$e->getMessage()
),
E_USER_ERROR
);
}

它以以下方式工作:

$content = "grant_type=client_credentials&scope=access_token_only&client_id=".$client_id."&client_secret=".$client_secret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-sandbox.com/auth/token');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);

最新更新