如何在 WordPress 中使用 cURL 发送 POST 请求?

How to send POST request with a cURL in WordPress?

我需要向 Cloudflare API 发送 POST 请求, 他们的 API 例子是:

curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
     -H "X-Auth-Email: user@example.com" \
     -H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
     -H "Content-Type: application/json" \
     --data '{"purge_everything":true}

我一直在尝试从我的 functions.php 文件发出 POST 请求。这是我的代码:

$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'my_url' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array(
            'X-Auth-Email' => 'my_email',
            'X-Auth-Key' => 'cf_api_key',
            'Content-Type' => 'application/json',
        ));
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode( '{"purge_everything":true}' ));
$result = curl_exec($curl);
curl_close($curl);

    var_dump($result);

我收到了这个回复

'''{"success":false,"errors":[{"code":9106,"message":"Missing X-Auth-Key, X-Auth-Email or Authorization headers"}]} bool(true) '''

我应该在哪里以及如何放置我的 X-Auth-Key 等?

你必须使用 http 标头数组作为单个值,用双点分隔,而不是作为键值对:

请看这个例子:

$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'my_url' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array(
            'X-Auth-Email: my_email',
            'X-Auth-Key: cf_api_key',
            'Content-Type: application/json',
        ));
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, ["purge_everything"=>true] );
$result = curl_exec($curl);
curl_close($curl);

    var_dump($result);