Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce Slack Slash Command WordPress plugin
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'dbi', 'slash-woo/', array(
'methods' => 'POST',
'callback' => 'slack_woo_command',
) );
} );
function slack_woo_command( $request ) {
$command = filter_input( INPUT_POST, 'command', FILTER_SANITIZE_STRING );
if ( empty( $command ) || '/woo' !== $command ) {
return false;
}
if ( ! function_exists( 'WC') ) {
return false;
}
if ( ! defined( 'DBI_SLACK_SECRET' ) || ! verify_slack_signed_secret( $request, DBI_SLACK_SECRET ) ) {
return false;
}
$interval = 'week';
$interval_whitelist = array( 'week', 'month', 'year' );
$text = filter_input( INPUT_POST, 'text', FILTER_SANITIZE_STRING );
if ( $text ) {
$parts = explode( ' ', $text );
if ( in_array( trim( $parts[0] ), $interval_whitelist ) ) {
$interval = $parts[0];
}
}
$interval_name = $interval;
if ( 'week' === $interval ) {
$interval = '7day'; // For Woo backwards compatibility
}
$total = get_woo_orders_total( $interval );
return array(
'text' => sprintf( '*Sales Report* This %s: *%s*', ucfirst( $interval_name ), html_entity_decode( get_woocommerce_currency_symbol()) . number_format( $total ) ),
);
}
function get_woo_orders_total( $interval ) {
include_once( WC()->plugin_path() . '/includes/admin/reports/class-wc-admin-report.php' );
include_once( WC()->plugin_path() . '/includes/admin/reports/class-wc-report-sales-by-date.php' );
$report = new WC_Report_Sales_By_Date();
$report->calculate_current_range( $interval );
$report_data = $report->get_report_data();
return $report_data->net_sales;
}
function verify_slack_signed_secret( $request, $secret ) {
$version = 'v0';
$body = $request->get_body();
$timestamp = $request->get_header( 'X-Slack-Request-Timestamp' );
if ( $timestamp > time() + 300 ) {
return false;
}
$sig_basestring = "{$version}:{$timestamp}:{$body}";
$hash = hash_hmac( 'sha256', $sig_basestring, $secret );
$local_signature = "{$version}={$hash}";
$remote_signature = $request->get_header( 'X-Slack-Signature' );
if ( $remote_signature !== $local_signature ) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.