PHP Guzzle基本认证和承载令牌


PHP Guzzle with basic auth and bearer token

我正在尝试与infojobs-api建立连接,文档解释了如何以这种方式进行连接:

GET/api/1/application HTTP/1.1
主持人:api.infojobs.net授权:Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==,承载07d18face -77ea-461f-9bfe-a5e9d98deb3d

(https://developer.infojobs.net/documentation/user-oauth2/index.xhtml)

这是我的代码:

$basicauth = new Client(['base_uri' => 'https://api.infojobs.net']);
$credentials = base64_encode(CLIENT_ID .':' . CLIENT_SECRET ) ;
$newresponse = $basicauth->request(
  'GET',
  'api/1/curriculum',
  ['debug' => true], 
  ['auth' => 
    ['Basic', $credentials] ,
    ['Bearer', $acceso->access_token]
  ]
)->getBody()->getContents();
d($newresponse);

API/Guzlle给我返回这个错误:

致命错误:Uncaught GuzzleHttp'Exception'ClientException:客户端错误:GET https://api.infojobs.net/api/1/curriculum导致401 No Autorizado响应:{"error":"102","error_description":"Client credentials not valid","timestamp":"2016-06-25T14:08:54.774Z"}在/app/供应商/guzzlehttp/狂饮/src/异常/RequestException.php: 107

所以我做错了什么,但我不知道错在哪里。

有什么主意吗?

奥斯卡·

当我看到你的请求的HTTP头:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==,Bearer 07d18fac-77ea-461f-9bfe-a5e9d98deb3d

您有一个包含逗号分隔值的Authorization标头。他们彼此并不分离。所以你不能像你所做的那样从Guzzle的auth键中获益。

你应该做的是手动设置授权头:

$newresponse = $basicauth->request(
    'GET',
    'api/1/curriculum',
    ['debug'   => true], 
    ['headers' => 
        [
            'Authorization' => "Basic {$credentials},Bearer {$acceso->access_token}"
        ]
    ]
)->getBody()->getContents();

对于post call,这对我来说很有效:

$guzzle = new Client(['base_uri' => self::APIURL]);
$raw_response = $guzzle->post($endpoint, [
  'headers' => [ 'Authorization' => 'Bearer ' . $publicKey ],
  'body' => json_encode($data),
]);
$response = $raw_response->getBody()->getContents();