Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Basilakis/ab837c387985f92e80c4959ca61c95df to your computer and use it in GitHub Desktop.
Save Basilakis/ab837c387985f92e80c4959ca61c95df to your computer and use it in GitHub Desktop.
EDD Create Coupon from Slack - Allow creating a coupon `/coupon $20` or `/coupon 20%` in Slack
<?php
/*
Plugin Name: EDD Create Coupon from Slack
Plugin URL: http://gravityview.co
Description: Allow creating a coupon `/coupon [%]` in Slack
Version: 1.0
Author: Katz Web Services, Inc.
Author URI: http://katz.co
Contributors: katzwebservices
*/
/**
* @return void|bool
*/
function kws_edd_slack_coupon_command() {
// UPDATE WITH YOUR OWN TOKEN HERE
$token = 'your-slack-command-token-here';
# Check to see if a token has been passed as well
if ( ! isset( $_REQUEST['token'] ) || ( $_REQUEST['token'] !== $token ) ) {
return false;
}
// If just `/coupon` is sent, the default is 20%
$coupon_amount = isset( $_REQUEST['text'] ) ? esc_attr( $_REQUEST['text'] ) : '20%';
// Percent by default. Pass $123 for flat amount off
if( preg_match('/\$/', $coupon_amount ) ) {
$coupon_amount = str_replace( '$', '', $coupon_amount );
$coupon_amount = floatval( $coupon_amount );
$coupon_type = 'flat';
$coupon_name = '$'.$coupon_amount .' Off';
} else {
$coupon_amount = str_replace( '%', '', $coupon_amount );
$coupon_type = 'percent';
$coupon_name = $coupon_amount .'% Off';
}
# Check that the token is the one that was set in Slack
if ( $token === $_REQUEST['token'] && !empty( $coupon_amount ) ) {
$coupon_code = strtoupper( wp_generate_password( 10, false ) );
$discount_id = kws_edd_slack_create_coupon( $coupon_name, $coupon_code, $coupon_amount, $coupon_type );
echo 'Discount #'. $discount_id.' created for '.$coupon_name.': '.$coupon_code;
# We need to exit or you will send a bunch of html that Slack won't be able to handle
exit();
}
}
add_action( 'init', 'kws_edd_slack_coupon_command' );
/**
* @param string $coupon_name
* @param $coupon_code
* @param int $amount
* @param string $type
* @param string $expiration
* @return string
*/
function kws_edd_slack_create_coupon( $coupon_name = '', $coupon_code, $amount = 20, $type = 'percent', $expiration = '' ) {
if( ! is_callable( 'edd_store_discount' ) ) {
return;
}
$meta = array(
'name' => $coupon_name,
'code' => $coupon_code,
'type' => $type, // 'flat' or anything else is 'percent'
'amount' => $amount,
'start' => '',
'expiration' => ( empty( $expiration ) ? date( 'm/d/Y', strtotime("+1 week") ) : '' ),
);
$discount_number = edd_store_discount( $meta );
return $discount_number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment