将CURL语句转换为php脚本时遇到问题

时间:2019-03-06 08:50:49

标签: php curl

我正在尝试将以下CURL语句转换为PHP脚本,并且遇到问题。

curl -s -S -i -v --cert /etc/ssl/certs/TestCertificate.p12:password --cert-type p12 --cacert /etc/ssl/certs/TLSRootCA.pem --tlsv1.1 --header "Content-Type: application/json" https://example1.com/api/paymentrequests --data '{ "payeePaymentReference" : "0123456789", "callbackUrl" : "https://example2.com/callback.php", "payerAlias" : "345689123", "payeeAlias" : "123456789", "amount" : "10", "currency" : "USD", "message" : "Testing callback server" }'

这是我的php脚本:

    <?php
    class APIController
    {
        public static function getRoutes()
        {
            $routes = [];

            $routes[] = new Route('GET /api', function () {
                $url = "https://example1.com/api/paymentrequests";
                $ch = curl_init();

                $data =
                    [
                        'payeePaymentReference' => '0123456789',
                        'callbackUrl'           => 'https://example2.com/callback.php',
                        'payerAlias'            => '345689123',
                        'payeeAlias'            => '123456789',
                        'amount'                => '10',
                        'currency'              => 'USD',
                        'message'               => 'Testing callback server'
                    ];

                $data_string = json_encode($data);

                $options = array(
                    CURLOPT_CUSTOMREQUEST   => 'POST',
                    CURLOPT_RETURNTRANSFER  => true,
                    CURLOPT_URL             => $url ,
                    CURLOPT_VERBOSE         => true,
                    CURLOPT_CAINFO          => '/etc/ssl/certs/TLSRootCA.pem',
                    CURLOPT_SSLCERT         => '/etc/ssl/certs/TestCertificate.p12',
                    CURLOPT_SSLCERTPASSWD   => 'password',
                    CURLOPT_SSLCERTTYPE     => 'P12',
                    CURLOPT_POST            => true,
                    CURLOPT_POSTFIELDS      => $data_string,
                    CURLOPT_HTTPHEADER      => [
                    'Content-Type: application/json'
                    ]
                );

                curl_setopt_array($ch , $options);

                $output = curl_exec($ch);

                if(!$output)
                {
                    echo "Curl Error : " . curl_error($ch);
                }
                else
                {
                    echo htmlentities($output);
                }

                return false;
            });

            return $routes;

        }

    }

$testObject = new APIController();

$testObject->getRoutes();

echo htmlentities($output);

?>

在命令行中运行CURL语句,将成功调用回调脚本并显示HTTP 201(显示成功的呼叫响应)。但是,当我运行php脚本时,没有显示任何内容,并且未调用回调脚本。感谢您指出我做错了什么。

1 个答案:

答案 0 :(得分:0)

使用curl_errno而不是if(!$output)来检查curl请求是否存在错误

if (curl_errno($ch)) {
    echo "Curl Error : " . curl_error($ch);
}