Skip to content

Instantly share code, notes, and snippets.

@avantassel
Created February 1, 2019 12:50
Show Gist options
  • Save avantassel/8ae6260efd4ade9642cac6aa4f585af4 to your computer and use it in GitHub Desktop.
Save avantassel/8ae6260efd4ade9642cac6aa4f585af4 to your computer and use it in GitHub Desktop.
Verifying requests from Slack in PHP
<?php
/*
Verifying requests from Slack
https://api.slack.com/docs/verifying-requests-from-slack
The slack message has two buttons, Approve and Deny
verify the request from Slack and update approved or denied
*/
$raw_body = file_get_contents('php://input');
$response = ["message" => "success"];
if(empty($_POST['payload'])){
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
}
// slack signing secret
$SLACK_SIGNING_SECRET = '';
$body = urldecode($_POST['payload']);
$message = json_decode($body, true);
if(empty($_SERVER['HTTP_X_SLACK_SIGNATURE']) || empty($_SERVER['HTTP_X_SLACK_REQUEST_TIMESTAMP'])){
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
} else {
$version = explode("=", $_SERVER['HTTP_X_SLACK_SIGNATURE']);
$timestamp = $_SERVER['HTTP_X_SLACK_REQUEST_TIMESTAMP'];
$token = $message['token'];
$sig_basestring = "{$version[0]}:$timestamp:$raw_body";
$hash_signature = hash_hmac('sha256', $sig_basestring, $SLACK_SIGNING_SECRET);
if(!hash_equals($_SERVER['HTTP_X_SLACK_SIGNATURE'], "v0=$hash_signature")){
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
}
}
if(empty($message['callback_id']) || empty($message['actions'])){
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
}
// use the callback_id and action to perform app function
// database update or response
$approved = $message['actions'][0]['value'];
//callback_id has a database table id
$response = myDatabaseCall($message['callback_id'], $approved);
// update response
$response = $message['original_message'];
// remove buttons
$response['attachments'][0]['actions'] = [];
// update pretext
if($approved == '1'){
$response['attachments'][0]['color'] = 'good';
$response['attachments'][0]['pretext'] = "<@{$message['user']['name']}> Approved this {$type[0]}.";
} else {
$response['attachments'][0]['color'] = 'danger';
$response['attachments'][0]['pretext'] = "<@{$message['user']['name']}> Denied this {$type[0]}.";
}
header('Content-Type: application/json');
echo json_encode($response);
?>
@xvilo
Copy link

xvilo commented May 17, 2023

$token from line 26 seems unused, is this correct?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment