首页 > 解决方案 > curl请求中的Xero授权不成功错误

问题描述

我在从 Xero 访问联系人时遇到问题。我不断收到错误 - AuthorizationUnsuccessful

请在下面找到我用来发送请求的代码以及我得到的响应:

'scopes' => ('openid', 'email', 'profile', 'offline_access', 'accounting.settings', 'accounting.contacts' ) 在我的 xero 配置文件中

请求在 Postman 中传递

    <?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.xero.com/api.xro/2.0/Contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer eyJh.......N6mbaw",
"cache-control: no-cache",
"postman-token: 51048d11-4f31-ba27-16c7-48739f14c6f0",
"xero-tenant-id: e8672ad4-ea92-4698-87aa-a69f5b049265"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>

Response:
{
"Type": null,
"Title": "Unauthorized",
"Status": 401,
"Detail": "AuthorizationUnsuccessful",
"Instance": "14ae9993-dc1b-4d8d-a4c0-15b2c343f337",
"Extensions": {}
}

您的帮助将不胜感激。

标签: laravelapicurl

解决方案


在你的标题中,我认为不需要postman-token,所以它应该看起来像,

CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Authorization: Bearer eyJh.......N6mbaw",
"Cache-control: no-cache",
"Xero-tenant-id: e8672ad4-ea92-4698-87aa-a69f5b049265"
)

注意大写的第一个字母。

另一种更简单、更有条理的选择是使用 guzzle,因为您使用的是 laravel(如果 > 5.1),您已经在 laravel 中拥有 guzzle 或者甚至可以使用 HTTP 客户端。


使用 Guzzle 你可以使用 Guzzle 来处理 curl 请求,

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;


public function yourFunction()
{
    try {
        $client = new Client();
        $guzzleResponse = $client->get(
                'https://api.xero.com/api.xro/2.0/Contacts', [
                'headers' => [
                    "Accept" => "application/json",
                    "Authorization" => "Bearer eyJh.......N6mbaw",
                    "Cache-control" => "no-cache",
                    "Xero-tenant-id" => "e8672ad4-ea92-4698-87aa-a69f5b049265"
                ],
                'allow_redirects' => [
                    'max' => 10,
                ],
                'connect_timeout' => 30
            ]);
        if ($guzzleResponse->getStatusCode() == 200) {
            $response = json_decode($guzzleResponse->getBody(),true);
        }
        
    } catch (RequestException $e) {
        // you can catch here 400 response errors and 500 response errors
        // see this https://stackoverflow.com/questions/25040436/guzzle-handle-400-bad-request/25040600
    } catch(Exception $e){
        //other errors 
    }
}

您可以参考guzzle docs中有关 guzzle 的更多信息


推荐阅读