Gow*_*wri -1 php curl commercetools
在我的应用程序中,我使用 Commercetools API。
为了从他们的 API 获取数据,我需要调用一个端点。
以下是我用来获取产品的端点。
https://api.sphere.io/vc-1209/products -H "Authorization: Bearer -5DVqQFgkd_SDGthsFgtepS"
Run Code Online (Sandbox Code Playgroud)
当我在终端中运行上面的 URL 时,例如
curl https://api.sphere.io/vc-1209/products -H "Authorization: Bearer -5DVqQFgkd_SDGthsFgtepS"
Run Code Online (Sandbox Code Playgroud)
它给了我所有产品的回应。
但是当我从 PHP 的 cURL 执行相同的 URL 时,它不起作用。
$url = 'https://api.sphere.io/vc-1209/products -H "Authorization: Bearer -5DVqQFgkd_SDGthsFgtepS"';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
print_r($response);
Run Code Online (Sandbox Code Playgroud)
我回来了:
客户端发送了错误的请求。
您只需CURLOPT_HTTPHEADER在示例中进行设置即可获得响应。
<?php
$url = 'https://api.sphere.io/vc-1209/products';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer -5DVqQFgkd_SDGthsFgtepS'
));
$response = curl_exec($ch);
var_dump($response);
?>
Run Code Online (Sandbox Code Playgroud)
当您在本地主机中运行代码时,它bool(false)可能会因为https请求而给您提供信息。
当我在启用 https 的生产中满足您的请求时,它给了我以下响应:
字符串(130)“{“statusCode”:401,“message”:“invalid_token”,“errors”:[{“code”:“invalid_token”,“message”:“invalid_token”}],“error”:“invalid_token “}”
此错误清楚地表明,您需要access token在 CURL 请求中添加作为标头。
另请注意,curl 状态代码为 401,这意味着您无权执行此请求,您必须添加访问令牌。