如何使用php curl正确调用API?我收到401的http状态码

时间:2019-04-04 08:01:36

标签: php curl postman

我试图在php curl中调用API(使用无记名令牌授权),但得到响应401。

我尝试使用邮递员的代码,但与此同时出现了另一个错误。我已经包含了代码。卷边是第一个功能。我有一个不同的API获取承载令牌,并且工作正常,但是当我将承载令牌传递给我的php Curl请求时,我得到401的http状态代码

function restRequestDispute($method, $endpoint, $data, $content_type, $token) 
{

            $ch = curl_init($endpoint);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 300);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                        array("Authorization: Bearer " . $token,
                            "Content-type: $content_type", 
                              "Accepts: application/json"));
                             // 'Content-Length: 0'));
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_ENCODING, '');
            $method = strtoupper($method);

            switch ($method) {
                case "GET":
                    curl_setopt($ch, CURLOPT_HTTPGET, true);
                    break;
                case "DELETE":
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                    break;
                case "PUT":
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                case "POST":
                //return $data;
                    //curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                    break;
                default:
                    throw new Exception("Error: Invalid HTTP method '$method' $endpoint");
                    return null;
            }

            $oRet = new StdClass;
            $oRet->response = json_decode(curl_exec($ch));

            $oRet->status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            return $oRet;

}

function createDispute()
{
    try{
    $local_date = $date;
    $method ="POST";
    $content_type="application/json";

    $accessToken  = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiU2hlcmlmZi5PcGVsIiwiZXhwIjoxNTU0MzE2ODAzLCJpc3MiOiJ1cC1uZy5jb20iLCJhdWQiOiJ1cC1uZy5jb20ifQ.8LN6gcoDEpb2i8h9NA0Z_PNxRLweaHh44PN5nbfER10";
    $params = array (
        "issuerrrn"=> "003409137690",
        "transactionamount"=> "-7100",
        "localtransactiondate"=> "20181210",
        "logcomment"=> "comment",
        "amountdispenced"=>"0",
        "currentstatus"=> "NotStarted",
        "transitionaction"=> "GoodsServicesNotReceived"

        );

    $endpoint="https://172.**.*.***:***/api/DisputeWIthIssRrn?issuerrrn=003409137690&transactionamount=-7100&localtransactiondate=20181210&logcomment=comment&amountdispenced=0&currentstatus=NotStarted&transitionaction=GoodsServicesNotReceived";       

    $response = restRequestDispute($method, $endpoint, "", $content_type, $accessToken);

    return $response;
    } catch(Exception $e){

        $returned_result  =  ["error" => ["status" => "Exception", "data" => $e->getMessage()]];
        return $returned_result;

    }   

} 

1 个答案:

答案 0 :(得分:1)

我对您的curl函数有一点点修改,将一些内容稍微移动了一点,并添加了几件事-一件事是输出中增强的调试信息,另一件事是在其中使用了cainfo SSL选项。希望对您有帮助

function restRequestDispute($method, $endpoint, $data, $content_type, $token){
    try{

        /* you can freely download cacert.pem from the internet - always use when performing SSL communications in cURL */
        $cacert = '/path/to/your/cacert.pem';
        /* add additional debug info to this stream */
        $vbh = fopen('php://temp', 'w+');


        $method = strtoupper( $method );

        $ch = curl_init( $endpoint );
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_ENCODING, '');
        curl_setopt($ch, CURLOPT_HTTPHEADER,
                    array(
                        "Authorization: Bearer " . $token,
                        "Content-type: $content_type",
                        "Accepts: application/json"
                        )
                    );


        if( parse_url( $endpoint,PHP_URL_SCHEME )=='https' ){
            curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
            curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
            curl_setopt( $ch, CURLOPT_CAINFO, $cacert );
        }

        /* set the options for enhanced debugging */
        curl_setopt( $ch, CURLOPT_VERBOSE, true );
        curl_setopt( $ch, CURLOPT_NOPROGRESS, true );
        curl_setopt( $ch, CURLOPT_STDERR, $vbh );

        switch( $method ) {
            case "GET":
                curl_setopt($ch, CURLOPT_HTTPGET, true );
            break;
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE" );
            break;
            case "PUT":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT" );
            break;
            case "POST":
                curl_setopt($ch, CURLOPT_POST, true );
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data );
            break;
            default:
                throw new Exception("Error: Invalid HTTP method '$method' $endpoint");
                return null;
        }

        $oRet = new StdClass;
        $oRet->response = json_decode( curl_exec( $ch ) );
        $oRet->status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $oRet->errors   = curl_error( $ch );

        /* add verbose information to the output for enhanced debugging */
        rewind( $vbh );
        $oRet->verbose = stream_get_contents( $vbh );
        fclose( $vbh );

        curl_close( $ch );
        return $oRet;

    }catch( Exception $e ){
        exit( $e->getMessage() );
    }
}

如果检查$oRet->verbose$response->verbose的输出时函数返回,您应该会看到更多信息,这些信息已帮助我很多次解决了curl请求的问题。

看看您如何调用上述函数,我注意到了这一点:

`restRequestDispute( $method, $endpoint, "", $content_type, $accessToken );`

应该不是

`restRequestDispute( $method, $endpoint, $params, $content_type, $accessToken );`