验证 mailchimp 的 url 的 GET 状态

Validate GET status of a url for mailchimp

我创建了一个在 mailchimp 中创建批处理 webhook 的函数,以便在批处理操作完成后提交回调。如下所示:

// register mailchimp batch webhook
    $responseWH = wp_remote_post( 'https://' . substr($mcApi,strpos($mcApi,'-')+1) . '.api.mailchimp.com/3.0/batch-webhooks' ,array(
        'headers' => array(
        'method' => 'POST',
        'Authorization' => 'Basic ' . base64_encode( 'user:'. $mcApi )
        ),
        'body' => json_encode(array(
                'url' => 'http://90660d72b8be.ngrok.io/wp-json/lubuvna/v2/batch/2810471250791421617231098394447326550803'
        ))

));

上面的代码意味着,当一个批处理操作完成时,MC 应该调用这个url: http://90660d72b8be.ngrok.io/wp-json/lubuvna/v2/batch/2810471250791421617231098394447326550803

如果这个 url 被调用,那么脚本将 运行 并通知我操作完成并更新 wordpress 中的 post。

但是由于 header 状态代码是 404,mailchimp 没有将 url 添加到批处理 webhook.. 相反我得到以下错误:

{
    "type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
    "title": "Invalid Resource",
    "status": 400,
    "detail": "The resource submitted could not be validated. For field-specific details, see the 'errors' array.",
    "instance": "05a4430f-c68f-46a5-82af-3b95332d6fe83",
    "errors": [
        {
            "field": "url",
            "message": "We couldn't verify the URL is working. Please double check and try again. HTTP Code: 500"
        }
    ]
}

当 Mailchimp 尝试向指定的 URL 发出 GET 请求时,我如何 return header 中的 200 状态,同时添加批处理 webhook?他们需要一个有效的 url。 mailchimp batch webhook

我在本地主机中使用 ngrok 进行连接,当我添加一个 URL 像 http://90660d72b8be.ngrok.io/wp-content/plugins/my-plugin/inc/batch/import.php 时,它可以工作,因为该文件实际上存在于插件目录中

但是当添加 URL http://90660d72b8be.ngrok.io/wp-json/lubuvna/v2/batch/2810471250791421617231098394447326550803

我可以看到 mailchimp 发出了一个 get 请求,代码状态为 404,如屏幕截图所示

我最终使用了以下方法:

function myplugin_registered_rest_routes() {

    // batch operation finished
    register_rest_route('myplugin/v2', '/batch/(?P<id>\d+)', 
        array(
            array('methods' => ['POST', 'GET'],
                 'callback' => 'my_awesome_func'
            )
        ) 
    );
}

add_action( 'rest_api_init', 'myplugin_registered_rest_routes' );

数组的另一个选项,如@04FS 答案:

register_rest_route('myplugin/v2', '/batch/(?P<id>\d+)', 
        array(
            array('methods' => 'GET',
                 'callback' => 'my_awesome_func',
            ), 
            array('methods' => 'POST',
                 'callback' => 'my_awesome_func'
            )
        ) 
    );

解析url请求的另一个选项。使用 wordpress 时不常见 API:

add_action('parse_request', 'register_endpoint', 0);

function register_endpoint() {
    global $wp;

    if ($wp->request == 'wp-json/myplugin/v2/batch/2810471250791421617231098394447326550803') {
        header("HTTP/1.1 200 OK");
        exit;
    }
}