How to handle a GitHub webhook POST request?

I’d like to start by saying that I wasn’t sure if this was the right place to post this question, so if it isn’t please point me in the right direction.

Ok, so I have a GitHub webhook that is triggered whenever there’s a commit comment and I can’t figure out how to handle it in my WordPress website. I won’t go into detail of what I want to do with it because first I have to receive a response from the webhook.

In the GitHub webhook settings I set the Payload URL to mywpsite.com/github.php where github.php is a file I created to handle the request. I tried to see if I was actually receiving anything by doing

if(!empty($_POST)) {
                echo "There is something here!";
                echo "</br>";

                function printArray($array){
                    foreach ($array as $key => $value){
                        echo "$key => $value";
                        if(is_array($value)){ //If $value is an array, print it as well!
                            printArray($value);
                        }  
                    } 
                }

                printArray($_POST);
} else {
    echo "There is nothing here :(";
} ?>

but I always get There is nothing here :( which means I’m always getting an empty array. GitHub says that the webhook was sent successfully and no matter how many times I redeliver it, I receive nothing.

I found this question in Stack Overflow asking basically the same question but for Java. Unfortunately I don’t know enough Java to translate the answer. I have also seen several tools to handle GitHub webhooks but none assumes use with WordPress.

Any ideas will be greatly appreciated. Thanks.

1 Answer
1

First, you seem to misunderstand how PHP handles incoming POST request. It only exists in that instance webhook is making request. If you load that page in a browser there won’t be any POST data, unless you are submitting some.

To properly check that request was received you should log results from that file and check the file before and after webhook ping.

Second, you are not quite doing this “in” WordPress yet. Creating your own PHP files as endpoints in WP installation is problematic technique which is rarely used.

If you do want to properly integrate this within WP installation you should be using appropriate native endpoint and WP APIs to handle it. For POST requests one sematically fitting option would be wp-admin/admin-post.php. Though if you can’t customize remote payload (set action parameter) and use fitting hooks you will have to do your own check for context.

Leave a Comment