Skip to main content Skip to footer

Using Visitor WEB API for Targeted Marketing

Internet browsers are capable of collecting considerable amounts of data about a visitor. In the era of E-commerce, this information is useful for marketing products to a specific audience based on:

  1. Geographic location
  2. Type of device (mobile or desktop)
  3. Returning users or first-time users

The ComponentOne Web API v1 includes Visitor API. It retrieves browser-specific information for targeted marketing.

Visitor API features include:
Using Visitor WEB API for Targeted Marketing

Using Visitor WEB API for Targeted Marketing

Using Visitor WEB API for Targeted Marketing

Instances Where Visitor API is Useful:

  • Geographic location-targeted marketing: An e-commerce company wants to run a Black Friday special in the United States, the geographical location pulled from Visitor API allows the company to target Americans, and give them discounts automatically.

  • Sessions based marketing: A company gives additional discounts to first-time visitors using the first/initial session details from the Visitor API. This helps the e-commerce website target this audience and increase their customer registrations.

  • Redirecting traffic: The e-commerce firm uses the isMobile property and redirects traffic to their mobile app for users currently using mobile browsers.

How the Visitor API Works

  • The browser sends a JavaScript (JS) file request to the Visitor API server
  • At the server, the IP address or longitude/latitude is parsed from the request
  • Once the IP address or longitude/latitude is found, the server communicates with the configured location provider (IP2Location/GoogleMapLocation)
  • The location provider returns the location information for the requested IP address or latitude/longitude to the server
  • The server converts the data in JSON format and attaches it to the JS file and sends it to the client
  • The JS file contains the complete location data in JSON format
  • At the client-side, the location data can be accessed using the visitor.getData() method (illustrated below)

Configuring the Visitor API on the Server:

Now we create an ASP.NET Core application to consume this API.

Step 1: Installing the Visitor API Package

The Visitor API package is installed in one of two ways:

  1. Installed from the NuGet manager in the existing API project.
  2. Created using a new API project using C1Templates.

Configuring NuGet Package in the Existing Project:

Install the Visitor API package in the existing project with these steps:

  1. Right-click on Dependencies in Solution Explorer.
  2. Select Manage NuGet Packages.
  3. Click the Browse tab and type, “C1.AspNetCore.Api.Visitor” in the Search dropdown (see image below).

  4. Select the required version and click install.

Create a Project Using the C1Template:

If you do not have a Web API project in your ASP.NET Core application project, you may add the ComponentOne Visitor API to your project with the following steps using a C1Template.

  • Create a new project in Visual Studio 2019.
  • Search C1 Web API Application.
    • Select “C1 Web API Application for ASP.NET Core (.NET Framework)” template.
    • Click Next.
  • Provide the Name, Location, and Solution name for the project. Click OK.
  • Select ASP.NET Core 2.2 or higher (see image below):

  1. Click OK (The project will install all the required packages).
  2. Select Manage NuGet Packages.
  3. Click the Browse tab and type “C1.AspNetCore.Api.Visitor” in the search dropdown (see attached image).

  4. Select the required version. Click Install.

Using either of the above methods, install the required packages in the Web API project.

Step 2: Configuring the IP Service for API

The Visitor API needs to configure the Location database or call the Google Map API to find the correct information for the client.

Configuring the IP2Location Database:

  • The IP2Location Database provides the solution to determine the country, region or state, city, latitude, longitude, ZIP code and time zone of origin for any IP address in a few simple steps:
  • Retrieve the IP address from the networking protocol or server-side variable of the Web server.
  • Translate the IP address to an IP number in decimal format to speed up the database query.
  • Reverse lookup the IP number from the IP2Location™ database to pinpoint the exact geographical location.

The Visitor API has a built-in provider to find a visitor's location based on their IP Address. It requires a connection string to the Ip2Location database. It works with ip-country-region-city-latitude-longitude-zipcode-timezone database and MS SQL server. You can easily set up the database by following their instructions.

To setup IP2Location Database, we can go with the following steps:

  1. Download the database from the link provided
  2. Connect to MSSqlServer
  3. Create the table and import the database using the following code snippet
IP2Location DataBase Import
// Create Table
CREATE DATABASE ip2location
GO

USE ip2location
GO

CREATE TABLE [ip2location].[dbo].[ip2location_db11](
    [ip_from] float NOT NULL,
    [ip_to] float NOT NULL,
    [country_code] nvarchar(2) NOT NULL,
    [country_name] nvarchar(64) NOT NULL,
    [region_name] nvarchar(128) NOT NULL,
    [city_name] nvarchar(128) NOT NULL,
    [latitude] float NOT NULL,
    [longitude] float NOT NULL,
    [zip_code] nvarchar(30) NOT NULL,
    [time_zone] nvarchar(8) NOT NULL
) ON [PRIMARY]
GO

CREATE INDEX [ip_from] ON [ip2location].[dbo].[ip2location_db11]([ip_from]) ON [PRIMARY]
GO

CREATE INDEX [ip_to] ON [ip2location].[dbo].[ip2location_db11]([ip_to]) ON [PRIMARY]
GO
//Import DataBase
BULK INSERT [ip2location].[dbo].[ip2location_db11]
    FROM 'C:\[path to your CSV file]\IP2LOCATION-LITE-DB11.CSV'
    WITH
    (
        FORMATFILE = 'C:\[path to your DB11.FMT file]\DB11.FMT'
    )
GO

By executing the Select query makes sure that the database imports correctly.

Follow the instructions to find the connection string.
In the Startup.cs file, write the following code:

public void ConfigureServices(IServiceCollection services)
{
...
services.ConfigureVisitor(builder =>
{
builder.UseIp2Location(Configuration.GetConnectionString("IP2LocationConnectionString"));
});
}

Configuring the Google Maps API:

Google Maps API is a paid service that requires an API Key. Google Maps works on the client-side. It needs the visitor’s client browser to send a request to the geolocation API to lookup the visitor's addresses based on their latitude and longitude, while the visitor client script loads in the background.

This parses the response from the Google Maps geocoding API and stores the value back in the visitor’s client.

Visitor API has a built-in provider that helps to find Visitor geometry location using the Google Maps API.

In the Startup.cs file, we need to write the following code:

public void ConfigureServices(IServiceCollection services)
{
...
services.ConfigureVisitor(builder =>
{
builder.UseGoogleMapLocation(Configuration["AppSettings:GoogleMapApiKey"]);
});
}

Note: Calling the UseWithoutLocationProvider() instead of UseIp2Location() and UseGoogleMapLocation() configuration methods, provides client information without GeoLocation information.

In this case, Visitor API returns all data except the geo piece of the data (geo.countryName, geo. countryCode, etc.).

public void ConfigureServices(IServiceCollection services)
{
...
services.ConfigureVisitor(builder =>
{
builder.UseWithoutLocationProvider();
});
}
Step 3: Include the JS Script

Make a server call to the Visitor API and get the client information. Include the JS file in the NuGet packages to make a server call and store the information on the client machine. The JS file is included in the application either synchronously or asynchronously. Therefore, you can fetch the data synchronously or asynchronously.

Refer to the following code to fetch the data from server:

Synchronous:

<script src="{host}/api/visitor/visitor-client.min.js"></script> 
<script> 
     var visitorData= window.visitor.getData(); 
     console.log(visitorData); 
</script> 

Asynchronous:

<script> 
    function onVisitorLoaded(visitorData){
          console.log(visitorData);
    }
</script> 
<script async defer src="{host}/api/visitor/visitor-client.min.js?callback=onVisitorLoaded"></script>
<script>
     /* In case data needs to be fetched on some event or action */ 
    function getData() { 
         window.visitor.getDataAsync(function (visitorData)
            {
               console.log(visitorData);
            }); 
    } 
</script> 

Result Data:

{
  "ip": {
    "address": "45.115.191.188"
  },
  "geo": {
    "countryCode": "IN",
    "countryName": "India",
    "regionName": "Uttar Pradesh",
    "cityName": "Noida",
    "latitude": 28.58,
    "longitude": 77.33,
    "zipCode": "201301",
    "timeZone": "+05:30"
  },
  "locale": {
    "countryCode": "us",
    "languageCode": "en"
  },
  "session": {
    "visits": 1,
    "start": "2020-05-07T04:41:21.839Z",
    "last_visit": "2020-05-07T04:41:21.839Z",
    "url": "https://demos.componentone.com/aspnet/5/webapiexplorer/Visitor/AvailableVariables",
    "path": "/aspnet/5/webapiexplorer/Visitor/AvailableVariables",
    "referrer": "",
    "referrer_info": {
      "host": "demos.componentone.com",
      "path": "/aspnet/5/webapiexplorer/Visitor/AvailableVariables",
      "protocol": "https:",
      "port": 80,
      "search": "",
      "query": {}
    },
    "search": {
      "engine": null,
      "query": null
    }
  },
  "firstSession": {
    "visits": 13,
    "start": "2020-04-25T03:11:34.818Z",
    "last_visit": "2020-05-07T04:41:21.839Z",
    "url": "https://demos.componentone.com/aspnet/5/webapiexplorer/Visitor",
    "path": "/aspnet/5/webapiexplorer/Visitor",
    "referrer": "https://demos.componentone.com/aspnet/5/webapiexplorer",
    "referrer_info": {
      "host": "demos.componentone.com",
      "path": "/aspnet/5/webapiexplorer",
      "protocol": "https:",
      "port": 80,
      "search": "",
      "query": {}
    },
    "search": {
      "engine": null,
      "query": null
    },
    "prev_visit": "2020-05-07T04:41:04.784Z",
    "time_since_last_visit": 17055
  },
  "browser": {
    "name": "Chrome",
    "version": "81.0.4044.129",
    "majorVersion": 81
  },
  "os": {
    "name": "Windows",
    "version": "10",
    "platform": "x64"
  },
  "device": {
    "name": "",
    "version": "",
    "screen": {
      "resolution": "1920x1080",
      "width": 1920,
      "height": 1080
    },
    "viewport": {
      "resolution": "1920x778",
      "width": 1920,
      "height": 778
    },
    "isTablet": false,
    "isMobile": false
  }
}

Visitor Web API Explorer Live Demo

Manish Gupta

Manish Gupta

Senior Software Engineer
comments powered by Disqus