6 min read

Implementing Location-Based Coupons: A Comprehensive Step-by-Step Guide

Implementing Location-Based Coupons: A Comprehensive Step-by-Step Guide
Photo by Perry Merrity II / Unsplash

Introduction

There are directories worldwide, and as we know, not all economies are the same. In some countries, a subscription can be costly, creating a roadblock for potential subscribers.

What if you could offer a country-based coupon to make subscriptions more affordable? By tailoring discounts to different regions, you make it easier for users to subscribe, helping your directory grow its audience and increase revenue.

That’s the problem we’re tackling here. By offering country-specific discounts, you can boost sign-ups and help more users access the benefits of your directory.

How it works

Creating a custom widget

Let’s start by creating a custom widget where all the code will be stored:

  1. Visit managemydirectory.com and navigate to Toolbox > Widget Manager in the left sidebar.
  2. Click the “New Widget” button (blue).
  3. Name the widget “location-based-coupon”.
  4. Copy and paste the code below to add all the functionality and design:

<?php
// TESTING CONFIGURATION
$enableTestIP = false; // Enable/disable IP testing mode
$testIP = '80.207.161.250'; // IP address for testing purposes

// Retrieve client IP address from different possible sources
// This handles cases where the user might be behind a proxy or load balancer
$client  = $_SERVER['HTTP_CLIENT_IP'] ?? null;
$forward = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? null;
$remote  = $_SERVER['REMOTE_ADDR'] ?? null;

$ip = 'Unknown';

// Validate the IP more robustly
if ($enableTestIP) {
    $ip = $testIP;
} else if (filter_var($client, FILTER_VALIDATE_IP)) {
    $ip = $client;
} elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
    $ip = $forward;
} elseif (filter_var($remote, FILTER_VALIDATE_IP)) {
    $ip = $remote;
}

// Make API request to get geolocation data from ip-api.com
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<http://ip-api.com/json/>" . $ip);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request
$ipDataInput = curl_exec($ch);

// Convert the JSON response to an associative array
$geoIpFormat = json_decode($ipDataInput, true);

// Close cURL
curl_close($ch);

// Check if a valid response was received
if (isset($geoIpFormat['status']) && $geoIpFormat['status'] === 'success') {
    displayGeographicCoupon($w, $geoIpFormat);
}

function displayGeographicCoupon($w, $geoIpFormat) {
    // Establish database connection using WHMCS configuration
    $con = mysqli_connect(
        $w['whmcs_database_host'],
        $w['whmcs_database_user'],
        $w['whmcs_database_password'],
        $w['whmcs_database_name']
    );

    if (!$con) {
        return false;
    }

    $countryCode = mysqli_real_escape_string($con, $geoIpFormat['countryCode']);
    $currentDate = date('Y-m-d');
    
    // Build SQL query to find valid geographic-specific coupons
    // Conditions:
    // 1. Coupon code starts with country code
    // 2. Current date is within the valid date range
    // 3. Usage limit not exceeded
    $selectCoupon = "SELECT *, notes FROM tblpromotions 
        WHERE code LIKE '$countryCode-%' 
        AND startdate <= '$currentDate'
        AND (expirationdate >= '$currentDate' OR expirationdate = '0000-00-00')
        AND (maxuses = 0 OR uses < maxuses)";
    $selectCouponQuery = mysqli_query($con, $selectCoupon);

    if ($selectCouponQuery && mysqli_num_rows($selectCouponQuery)) {
        $coupons = mysqli_fetch_assoc($selectCouponQuery);
        
        // Format the discount message based on coupon type
        // Supported types: Percentage, Fixed Amount, Price Override
        $discountMessage = '';
        switch ($coupons['type']) {
            case 'Percentage':
                $discountMessage = $coupons['value'] . '% off';
                break;
            case 'Fixed Amount':
                $discountMessage = '$' . $coupons['value'] . ' off';
                break;
            case 'Price Override':
                $discountMessage = 'special price of $' . $coupons['value'];
                break;
            default:
                $discountMessage = 'discount';
        }
        

        // Build the coupon display message
        // If custom notes exist, use them; otherwise, use the default template
        $couponMessage = !empty($coupons['notes']) 
            ? $coupons['notes']
            : '<span class="flag-icon flag-icon-' . strtolower($countryCode) . '"></span> <strong>Good news!</strong> You have a ' . $discountMessage . ' coupon. Use code <strong>' . $coupons['code'] . '</strong> at checkout to save!';

        // Output the coupon alert with flag icon and dismissible functionality
        echo '
            <link rel="stylesheet" href="<https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/css/flag-icon.min.css>">
            <div class="alert alert-success alert-dismissible fade in text-center" style="margin: 0;border-radius: 0;" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                ' . $couponMessage . '
            </div>
        ';
    }

    mysqli_close($con);
}
?>

  1. Finally, click “Save Changes”.
  2. Here’s what the banner will look like:

Adding the widget

Now that we’ve created the widget, we need to place it where we want it displayed. In this case, we want to show the banner with the coupon on all pages, so we’ll add it to the widget called “Bootstrap Theme - Header”.

  1. Visit managemydirectory.com and navigate to Toolbox > Widget Manager in the left sidebar.
  2. Search for “Bootstrap Theme - Header”.
  3. If this widget is the default one, go to Actions > Customize.
  4. If the widget is custom, click “Edit”.
  5. At the top of the code, paste the following line:
<?php echo widget("location-based-coupon"); ?>
  1. Finally, click “Save Changes”.

Creating our coupons

We’re almost done with the setup—now let’s create our coupons.

For example, let’s say my directory is based in North America, and I want to offer a unique coupon for Canada, Mexico, and the U.S., with a different discount for each country.

  1. Visit managemydirectory.com and navigate to Finance > Coupon Codes in the left sidebar.
  2. Click “New Coupon Code +”.
  3. Configure the coupon using the options Brilliant Directories offers. If you need more details, refer to the official documentation.
  4. Important: To make this work, the coupon code must start with the country code and a dash, like this:
  • MX-LOVE for Mexico
  • US-LOVE for the U.S.
  • CA-LOVE for Canada
Note: This naming format is essential. It tells the system which coupon to apply based on the user’s country.

How to Customize the Message in the Banner

If you’re comfortable with code, you can customize the message directly on line 101.

But if seeing code makes you panic, there’s an easier way! Just use the “Internal Admin Notes” field in the coupon setup.

If there’s content in this field, the plugin will automatically detect it and use that as the banner message—simple as that.

Here’s an example of a custom message:

Hi, Hey! I noticed you are coming from Mexico where the subscription may be a bit expensive. I support Parity Purchasing Power — I want to make this subcription affordable for everyone around the world. If you need it, use the code MX-LOVE for an extra 35% off the listed prices.

QA

After all the hard work, it’s time for the fun and exciting part—testing! 😁

Here are a few options for testing your setup:

  • Use a VPN to view your site as if you’re in different countries.
  • Use a website preview tool to see how your site looks in various locations.
  • Enable dev mode (added in the code) to test country-specific features.

Let’s go through each option:

VPN:

If you have a VPN, you know how to use it. But if you don’t, I recommend this one: Surfshark. I’ve been using it for a while now, and it’s simple to use—just choose the country, and that’s it!

Website Preview Tool

With this option, you can see a preview of your site as it appears in other countries. The tool I recommend for this is GeoPeeker. Just enter your website URL, and you’ll receive images from different countries.

Here’s what I got, and if you click on any image, you can see a larger view.

In this example, we can see how the banner with the coupon is displayed in Australia.

Dev Mode:

At the beginning of the code, I’ve included a section for testing purposes. You can enable the dev mode and add the IP address of the country you want to test.

Here’s a demo of how to do it:

0:00
/0:31
Don’t forget to turn off the dev mode by changing the value to false.

Note:

One way I find IP addresses from other countries is by searching in Google: “country IP whatismyipaddress” and selecting a result from the page whatismyipaddress.com. It always works for me! If you have another method, feel free to leave it in the comments below.

Conclusion

Congratulations! You’ve now implemented location-based coupons in your directory.

I understand that this may have been a challenge depending on your experience with the platform and web development. However, I encourage you to give it a try.

I sincerely hope you enjoyed this tutorial as much as I enjoyed creating it. I put a lot of effort into this, and I would love for you to consider signing up! 🙌

If you successfully completed the process, please let us know in the comment section below!


That's all for now. Thanks for reading!