我正在尝试根据此文档在Taboola Backstage API上获取访问令牌。
Backstage API - Authentication and General API Usage.pdf
我的示例代码如下所示:
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$post = array(
"client_id" => "secret"
, "client_secret" => "secret"
, "grant_type" => "client_credentials"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile );
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile );
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token/");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$result=curl_exec ($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
var_dump($header,$body);
如果我运行代码,我会收到错误消息。无法验证提供的CSRF令牌,因为找不到您的会话。我错过了什么,我用POST发送到正确的端点。有人请给我一个提示吗?
答案 0 :(得分:0)
看起来他们的文档可能略有偏差。通过发布到/backstage/oauth/token
(没有尾随/
),我能够获得正确的API响应。使用尾部斜杠,它会尝试将您传递到另一个非API URL。
此外,有必要通过http_build_query()
传递POST数组,以便cURL不会从提供的数组中执行多部分表单发布。由于它是API,因此无需对Cookie执行任何操作。我也删除了一些其他不必要的选项。
以下是一些让您入门的代码:
$post = array(
"client_id" => "secret",
"client_secret" => "secret",
"grant_type" => "client_credentials",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
));
curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
$result=curl_exec ($ch);
$info = curl_getinfo($ch);
$response = json_decode($result, true);
if ($info['http_code'] == 200) {
// okay
$access_token = $response['access_token'];
var_dump($response);
} else {
// error
echo $response['error'] . ': ' . $response['error_description'];
}