如何使用PHP在授权代码和客户端机密的帮助下获得fortnox访问令牌


How to get fortnox access token with the help of authorization code and client secret using PHP?

我在fortnox中有一个沙盒帐户,我正试图使用以下代码获取访问令牌,但我一直收到相同的错误:

$requestMethod = "GET";
$ch = curl_init();
$options = array(
    'Authorization-Code: '. AUTHORIZATION_CODE .'',
    'Client-Secret: '. CLIENT_SECRET .'',
    'Content-Type: '. CONTENT_TYPE .'',
    'Accept: '. ACCEPTS .''
);
curl_setopt ($ch, CURLOPT_CAINFO, "/xampp/htdocs/cacert.pem");
curl_setopt($ch, CURLOPT_URL, "https://api.fortnox.se/3/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, $options);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestMethod);
$curlResponse = curl_exec($ch);
$info = curl_getinfo($ch);
//echo 'Took ' . $info['total_time'] . ' seconds for url ' . $info['url'];
echo $curlResponse;
if ($curlResponse === FALSE) {
    echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);

错误:PHP/4.5.37无法登录、访问令牌或客户端密钥丢失(2000311(。

我使用下面的代码获得Access-Token,这与您的代码非常接近。它对我来说很好。

错误页面中描述了您的错误,但它不会为您已经显示的文本添加任何新内容。

请注意,您只能检索Access-Token一次,请查看Fortnox文档中的"身份验证"部分。

每个授权码只能检索一次访问令牌,多个具有相同授权码的请求将使授权码和访问令牌无效。

public function actionRetrieveAccessToken($authCode, $clientSecret)
{
    $headers = [
        'Authorization-Code: ' . $authCode,
        'Client-Secret: ' . $clientSecret,
        'Content-Type: application/json',
        'Accept: application/json',
    ];
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://api.fortnox.se/3/');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $responseText = curl_exec($curl);
    $response = json_decode($responseText, true);
    if (isset($response['ErrorInformation'])) {
        echo 'Request failed with error messages:' . PHP_EOL;
        echo $response['ErrorInformation']['Error'] . ': ';
        echo $response['ErrorInformation']['Message'];
        echo ' (' . $response['ErrorInformation']['Code'] . ')' . PHP_EOL;
    } else {
        echo 'Access Token: ' . $response['Authorization']['AccessToken'] . PHP_EOL;
    }
}
$content_type = 'application/json';
$api_url="api url here";
$curl = curl_init();
$headers = array(
        'Content-Type: '.$content_type.'',
        'Authorization : '.'Bearer ' . $this->access_token
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($data)) 
{
    $data = json_encode($data);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($curl);
logthis($response,"utils");
curl_close($curl);