← Back to E-commerce Integration
🟣

WooCommerce Integration

Step-by-step guide to adding VoucherTrack vouchers to your WooCommerce store

What You'll Need
  • • WordPress with WooCommerce installed
  • • Access to your theme's functions.php or a custom plugin
  • • Your VoucherTrack API key
  • • ~30 minutes for setup

Overview

This integration lets customers enter VoucherTrack codes in the standard WooCommerce coupon field. The code validates against VoucherTrack in real-time and automatically records redemptions when orders complete.

Step 1: Store Your API Key Securely

Add your API key to wp-config.php (never hardcode it in theme files):

// Add to wp-config.php (before "That's all, stop editing!")
define('VOUCHERTRACK_API_KEY', 'your_api_key_here');

Step 2: Add the Integration Code

Add this code to your theme's functions.php or create a simple plugin:

<?php
/**
 * VoucherTrack Integration for WooCommerce
 * Validates voucher codes at checkout and records redemptions on order completion
 */

// Validate VoucherTrack codes when coupon is applied
add_filter('woocommerce_coupon_is_valid', 'vouchertrack_validate_coupon', 10, 2);
function vouchertrack_validate_coupon($valid, $coupon) {
    $code = strtoupper($coupon->get_code());
    
    // Skip if it's a regular WooCommerce coupon (check if it exists in WC)
    $wc_coupon = new WC_Coupon($code);
    if ($wc_coupon->get_id() > 0) {
        return $valid; // Let WooCommerce handle its own coupons
    }
    
    // Call VoucherTrack validation
    $response = wp_remote_get(
        "https://www.vouchertrack.io/api/webhook/validate/{$code}",
        array(
            'headers' => array(
                'X-API-Key' => VOUCHERTRACK_API_KEY
            ),
            'timeout' => 10
        )
    );
    
    if (is_wp_error($response)) {
        throw new Exception(__('Could not validate voucher. Please try again.', 'woocommerce'));
    }
    
    $data = json_decode(wp_remote_retrieve_body($response), true);
    
    if (!$data['valid']) {
        $error = isset($data['error']) ? $data['error'] : 'Invalid voucher code';
        throw new Exception($error);
    }
    
    // Store voucher data in session for later use
    WC()->session->set('vouchertrack_voucher_' . $code, $data);
    
    return true;
}

// Apply VoucherTrack discount to cart
add_action('woocommerce_cart_calculate_fees', 'vouchertrack_apply_discount');
function vouchertrack_apply_discount($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    
    foreach ($cart->get_applied_coupons() as $code) {
        $voucher_data = WC()->session->get('vouchertrack_voucher_' . strtoupper($code));
        
        if ($voucher_data && $voucher_data['valid']) {
            $cart_total = $cart->get_subtotal();
            
            // Check minimum spend
            if (!empty($voucher_data['minimum_spend']) && $cart_total < $voucher_data['minimum_spend']) {
                continue; // Don't apply if minimum not met
            }
            
            // Calculate discount based on type
            $discount = 0;
            if ($voucher_data['discount_type'] === 'percentage') {
                $discount = $cart_total * ($voucher_data['discount_value'] / 100);
            } elseif ($voucher_data['discount_type'] === 'fixed') {
                $discount = min($voucher_data['discount_value'], $cart_total);
            }
            
            if ($discount > 0) {
                $cart->add_fee(
                    sprintf('VoucherTrack: %s', $voucher_data['discount_description']),
                    -$discount,
                    false // Not taxable
                );
            }
        }
    }
}

// Record redemption when order is completed
add_action('woocommerce_order_status_completed', 'vouchertrack_record_redemption');
add_action('woocommerce_order_status_processing', 'vouchertrack_record_redemption');
function vouchertrack_record_redemption($order_id) {
    $order = wc_get_order($order_id);
    
    // Check if we've already processed this order
    if ($order->get_meta('_vouchertrack_recorded')) {
        return;
    }
    
    foreach ($order->get_coupon_codes() as $code) {
        $code = strtoupper($code);
        
        // Call VoucherTrack redemption endpoint
        $response = wp_remote_post(
            'https://www.vouchertrack.io/api/webhook/redemption',
            array(
                'headers' => array(
                    'X-API-Key' => VOUCHERTRACK_API_KEY,
                    'Content-Type' => 'application/json'
                ),
                'body' => json_encode(array(
                    'code' => $code,
                    'transaction_amount' => (float) $order->get_total(),
                    'order_reference' => $order->get_order_number(),
                    'redeemed_at' => current_time('c')
                )),
                'timeout' => 10
            )
        );
        
        if (!is_wp_error($response)) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (!empty($data['success'])) {
                $order->add_order_note(
                    sprintf('VoucherTrack: Code %s redeemed successfully', $code)
                );
            }
        }
    }
    
    // Mark as processed
    $order->update_meta_data('_vouchertrack_recorded', 'yes');
    $order->save();
}

// Allow VoucherTrack codes to be entered as coupons (even if not in WC database)
add_filter('woocommerce_coupon_code_is_valid', 'vouchertrack_allow_external_coupons', 10, 3);
function vouchertrack_allow_external_coupons($valid, $coupon_code, $coupon) {
    // If WooCommerce says invalid and it might be a VoucherTrack code, let it through
    if (!$valid) {
        // Check if it looks like a VoucherTrack code (contains hyphen typically)
        if (strpos($coupon_code, '-') !== false) {
            return true; // Allow validation to proceed
        }
    }
    return $valid;
}

Step 3: Test the Integration

  1. Add a product to your cart
  2. Go to checkout and enter a VoucherTrack code in the coupon field
  3. Verify the discount appears correctly
  4. Complete a test order and check it appears in VoucherTrack dashboard
✅ What This Integration Handles
  • • Real-time validation against VoucherTrack API
  • • Percentage and fixed-amount discounts
  • • Minimum spend enforcement
  • • Automatic redemption recording on order completion
  • • Works alongside regular WooCommerce coupons
  • • Order notes for audit trail
⚠️ Limitations
  • • Does not create virtual WooCommerce coupons (uses fees instead)
  • • "Free item" discount type needs custom handling for your products
  • • Requires PHP 7.4+ and WordPress 5.0+

Troubleshooting

"Could not validate voucher" error

Check your API key is correct in wp-config.php and that your server can reach vouchertrack.io (some hosts block outgoing requests).

Discount not appearing

Check minimum spend requirements. The voucher may be valid but cart total doesn't meet the threshold.

Redemption not recorded

Redemptions are recorded when order status changes to "processing" or "completed". Check your order workflow.

Alternative: Plugin Installation

Prefer not to edit code? Contact us for a ready-made WordPress plugin that handles everything with a settings page.