curl API请求在Postman中工作,但在PHP脚本中不工作(请求体必须包含以下参数:'grant_type')

brccelvz  于 9个月前  发布在  Postman
关注(0)|答案(1)|浏览(118)

我有一个API请求,我正试图从中获取令牌。
在Postman中,调用工作正常,我得到一个带有令牌的响应。
然而,当我抓取Postman生成的代码(使用相同的设置)时,我得到以下错误:

{"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: 096b2d08-2a58-46b9-80a1-701867418c00\r\nCorrelation ID: c96623e2-475f-48c5-bced-a1e87a557705\r\nTimestamp: 2023-05-08 16:01:55Z","error_codes":[900144],"timestamp":"2023-05-08 16:01:55Z","trace_id":"096b2d08-2a58-46b9-80a1-701867418c00","correlation_id":"c96623e2-475f-48c5-bced-a1e87a557705","error_uri":"https://login.microsoftonline.com/error?code=900144"}

这对我来说是不寻常的,因为我在body参数中清楚地使用了grant_type。
以下是我的PHP代码:

<?php
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.myendpoint.com/api/oauth2/v2.0/token',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array(
            'client_id' => '--hidden-for-obvious-reasons--',
            'client_secret' => '--hidden-for-obvious-reasons--',
            'grant_type' => 'client_credentials',
            'scope' => 'https://api.myendpoint.com/.default'
        ),
        CURLOPT_HTTPHEADER => array(
        'Content-Type: application/x-www-form-urlencoded',
        'Ocp-Apim-Subscription-Key: hidden-for-obvious-reasons'
        ),
    ));

    $response = curl_exec($curl);

    if (curl_errno($curl)) {
        echo 'cURL Error: ' . curl_error($curl);
        exit;
    }

    curl_close($curl);

    echo "<pre>$response</pre>";
?>

我“认为”这可能是因为我正在本地测试脚本,端点可能需要来自https://的请求-然而,当我上传到我的服务器时,它产生了同样的错误。
我也发现了这个线索:https://stackoverflow.com/questions/52129890/get-curl-request-only-works-in-postman-but-not-in-php,并尝试了许多建议,从那里,但似乎没有什么做的伎俩,那里也。
有什么想法,我可能错过了,或者为什么它可能不会拿起身体中的grant_type?

vsmadaxz

vsmadaxz1#

@ Abronsius教授的评论是正确的。我只需要将content-type从application/x-www-form-urlencoded改为multipart/form-data,这就成功了。

相关问题