2

I am trying to extend the Wordpress REST API with an endpoint that takes Zoom webhooks. Zoom requires a response within 3 seconds or will blacklist your endpoint address, but the processing that I want to do when I receive a webhook takes longer than 3 seconds.

What options do I have for returning a response from the WP REST API immediately but then carrying on execution?

Ideas:

  • exec() a child process in the background then return the response (but this might be a security risk)
  • Write a flag to the filesystem then return the response. A regular cron job will spot the flag and do the processing (but this will result in a delay in the process being done depending on how frequently the cron job is scheduled)

For non-WP scenarios I've seen solutions proposed that use fastcgi_finish_request() but I'm not sure how I could return a result from my callback function using this.

1 Answer 1

1

One thing you can do in WordPress is to dispatch a non blocking new request to itself, and then resume the response.

Something like this:

$action_name = 'sample_action';
$url = add_query_arg(
    [
        'action' => $action_name,
        'nonce'  => \wp_create_nonce( $action_name ),
    ],
    admin_url( 'admin-ajax.php' )
);

$body = [ 'your data' ];

// trigger a non-blocking request.
wp_remote_post(
    $url,
    [
        'timeout'   => 0.01,
        'blocking'  => false,
        'body'      => $body,
        'cookies'   => $_COOKIE,
        'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
    ]
);

// return rest response and free the request.
return rest_ensure_response( 'success' );

And then, you add the usual callbacks to handle the admin ajax call:

add_action( 'wp_ajax_' . $action_name, 'so_377405_callback' );
add_action( 'wp_ajax_nopriv_' . $action_name, 'so_377405_callback' );

function so_377405_callback() {

    // Don't lock up other requests while processing.
    session_write_close();

    if ( ! isset( $_REQUEST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( $_REQUEST['nonce'] ), 'sample_action' ) ) {
        wp_die();
    }

    // ... do stuff

    wp_die();

}

Is 3 years too late for a response?

1
  • By no means is it too late, I found myself asking the same question relatively recently! Commented Feb 26, 2024 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.