phpslack-apislack-dialog

Can't validate Slack dialog fields. response_url call always fails


I am trying to build a slack dialog, triggered by a slash command. The dialog pops up correctly, and when the user submits the data, slack hits an endpoints on my server.

From that moment there are two possible outcomes:

  1. Everything is good and I post a confirmation to the user
  2. The data submitted by the user does not pass my app's validation and I need to let the user know.

Let's focus on #2 for a second:

I am getting a response_url that seems valid (https:\/\/hooks.slack.com\/app\/MY-APP-ID\/433197747012\/kQANkbvc3lIViVyLSJKR695z)

For testing, I'd like to simulate a validation error with one of my fields, so I do this in my endpoint:

$errors = [
        'errors' => [
            [
                'name' => 'vendor_email',
                'error' => 'sorry, I do not like this dude'
            ]
        ]
    ];
// define the curl request
$ch = curl_init();
// $decoded->response_url does contain the correct slack URL...

curl_setopt($ch, CURLOPT_URL, $decoded->response_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($errors));

// execute curl request
$response = curl_exec($ch);
error_log(" -- response_url response: " . json_encode($response). "\n", 3, './runtime.log');

// close
curl_close($ch);

The response I am getting from hitting the response_url is this:

{\"ok\":false,\"error\":\"invalid_request_data\"}

What am I doing wrong?

****** EDIT ************

Even when not going the CURL route, and just doing this:

return json_encode($errors)

will just close the dialog after submission, and will not trigger any validation error.


Solution

  • The respond_url is not for replying to submissions (e.g. for validation errors), but for sending a message back to the user in the channel.

    Once the user completes the dialog you will get a request from Slack. You need to directly respond to that request. You can respond either with an empty response if everything was ok - or with a list of errors for validation. The response must be in JSON and occur within 3 seconds.

    To respond all you need to do is echo your error array in JSON. Also make sure to correctly set the header to JSON, like so:

    header('Content-Type: application/json');
    echo json_encode($errors);
    

    If you have no errors just echo nothing to automatically send a HTTP 200 OK.

    See also here in the documentation about how to correctly respond to a submission.