Cordova SDK - Supporting Referrer Short Links

Creating Short Referrer Links

Generate short, shareable referrer links that enable user-to-user attribution and track app installs from organic referrals.

Version Requirement: This functionality requires SDK version 3.1.8 or higher. Short links remain active for 30 days after creation.


Overview

What Are Short Referrer Links

Short links transform long, parameter-filled Singular Links into compact, secure URLs convenient for sharing via SMS, social media, or in-app invitations.

Create short links dynamically so users can share them with friends to invite them to download and use your app. Each short link tracks the referring user, enabling you to measure viral growth and attribute new installs to specific advocates.


Implementation Requirements

Required Components

Gather these elements before creating a short referrer link:

  • Singular Link: A base tracking link that directs users to your app download. See Singular Links FAQ for setup instructions
  • Dynamic Parameters: Optional custom parameters to add context to the link. View available options in Tracking Link Parameters
  • Referrer Information: Name and ID of the user sharing the link to enable attribution of new installs back to the referrer

SDK Method

CreateReferrerShortLink

Generate a short referrer link with custom parameters and a callback handler for success and error states.

Method Signature:

cordova.plugins.SingularCordovaSdk.createReferrerShortLink(
    baseLink: string,
    referrerName: string,
    referrerId: string,
    passthroughParams: Object,
    resultHandler: Object
): void

Parameters:

  • baseLink: The original Singular tracking link URL
  • referrerName: Display name of the referring user
  • referrerId: Unique identifier for the referring user
  • passthroughParams: Object containing additional dynamic parameters (optional, pass empty object or null if none)
  • resultHandler: Object with onSuccess and onError callback functions

For complete method documentation, see createReferrerShortLink reference.


Basic Usage Example

Create a short link with custom parameters and implement sharing logic in the success callback.

JavaScript
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
  // Create custom parameters for the link
  var parameters = {
    channel: 'sms',
    campaign_id: 'summer_promo_2025',
    referral_type: 'friend_invite'
  };

  // Define result handler
  var resultHandler = {
    onSuccess: function(shortLink) {
      // Success - short link was created
      console.log('Generated short link:', shortLink);
      
      // Share the link using Cordova social sharing plugin
      shareLink(shortLink);
    },
    onError: function(error) {
      // Error occurred during link creation
      console.error('Error creating short link:', error);
      alert('Failed to create share link. Please try again.');
    }
  };

  // Generate the short referrer link
  cordova.plugins.SingularCordovaSdk.createReferrerShortLink(
    'https://sample.sng.link/D52wc/cuvk?pcn=test',  // Base Singular Link
    'John Doe',                                      // Referrer name
    'user_12345',                                    // Referrer ID
    parameters,                                      // Custom parameters
    resultHandler                                    // Callback handler
  );
}

function shareLink(shortLink) {
  // Use Cordova social sharing plugin
  if (window.plugins && window.plugins.socialsharing) {
    window.plugins.socialsharing.share(
      'Join me on this awesome app!',
      'App Invitation',
      null,
      shortLink
    );
  } else {
    // Fallback: Copy to clipboard
    copyToClipboard(shortLink);
    alert('Link copied to clipboard: ' + shortLink);
  }
}

function copyToClipboard(text) {
  // Use Cordova clipboard plugin if available
  if (cordova.plugins.clipboard) {
    cordova.plugins.clipboard.copy(text);
  }
}

Advanced Implementation

Implement a complete referral system with retry logic, loading states, and clipboard fallback.

JavaScript
// Referral Manager Implementation
var ReferralManager = {
  isGenerating: false,
  lastGeneratedLink: null,
  retryCount: 0,
  maxRetries: 3,

  generateShortLink: function(userId, userName, baseLink, callback) {
    var self = this;
    
    if (self.isGenerating) {
      console.log('Link generation already in progress');
      return;
    }

    self.isGenerating = true;
    self.showLoadingIndicator();

    var parameters = {
      channel: 'in_app',
      campaign_id: 'organic_referral',
      user_tier: 'premium',
      referral_timestamp: Date.now().toString()
    };

    var resultHandler = {
      onSuccess: function(shortLink) {
        self.isGenerating = false;
        self.lastGeneratedLink = shortLink;
        self.retryCount = 0;
        self.hideLoadingIndicator();
        
        console.log('Short link generated:', shortLink);
        
        // Track link generation
        cordova.plugins.SingularCordovaSdk.event('referral_link_created');
        
        if (callback) {
          callback(null, shortLink);
        }
      },
      onError: function(error) {
        console.error('Error generating link:', error);
        
        // Retry logic with exponential backoff
        if (self.retryCount < self.maxRetries) {
          var delay = Math.pow(2, self.retryCount) * 1000; // 1s, 2s, 4s
          self.retryCount++;
          
          console.log('Retrying in ' + delay + 'ms... (Attempt ' + 
                     self.retryCount + '/' + self.maxRetries + ')');
          
          setTimeout(function() {
            self.isGenerating = false;
            self.generateShortLink(userId, userName, baseLink, callback);
          }, delay);
        } else {
          // Max retries reached
          self.isGenerating = false;
          self.retryCount = 0;
          self.hideLoadingIndicator();
          
          if (callback) {
            callback(error, null);
          }
        }
      }
    };

    // Generate the link
    cordova.plugins.SingularCordovaSdk.createReferrerShortLink(
      baseLink,
      userName,
      userId,
      parameters,
      resultHandler
    );
  },

  shareReferralLink: function(userId, userName, baseLink) {
    var self = this;
    
    self.generateShortLink(userId, userName, baseLink, function(error, shortLink) {
      if (error) {
        // Use fallback if available
        if (self.lastGeneratedLink) {
          self.copyToClipboard(self.lastGeneratedLink);
          alert('Failed to generate new link, but your previous referral link has been copied to clipboard!');
        } else {
          alert('Failed to generate referral link. Please check your connection and try again.');
        }
      } else if (shortLink) {
        // Success - share the link
        self.shareViaPlugin(shortLink);
      }
    });
  },

  shareViaPlugin: function(shortLink) {
    var self = this;
    
    if (window.plugins && window.plugins.socialsharing) {
      window.plugins.socialsharing.shareWithOptions(
        {
          message: 'Join me on this awesome app!',
          url: shortLink,
          chooserTitle: 'Share via'
        },
        function(result) {
          console.log('Share completed:', result.completed);
          if (result.completed) {
            // Track successful share
            cordova.plugins.SingularCordovaSdk.event('referral_link_shared');
          }
        },
        function(error) {
          console.error('Share error:', error);
          // Fallback to clipboard
          self.copyToClipboard(shortLink);
          alert('Link copied to clipboard!');
        }
      );
    } else {
      // No share plugin available - copy to clipboard
      self.copyToClipboard(shortLink);
      alert('Referral link copied to clipboard: ' + shortLink);
    }
  },

  copyToClipboard: function(text) {
    if (cordova.plugins && cordova.plugins.clipboard) {
      cordova.plugins.clipboard.copy(text);
      console.log('Copied to clipboard:', text);
    }
  },

  showLoadingIndicator: function() {
    // Show loading UI
    var loader = document.getElementById('loading-indicator');
    if (loader) {
      loader.style.display = 'block';
    }
  },

  hideLoadingIndicator: function() {
    // Hide loading UI
    var loader = document.getElementById('loading-indicator');
    if (loader) {
      loader.style.display = 'none';
    }
  }
};

// Usage example
document.addEventListener('deviceready', function() {
  // Setup share button
  document.getElementById('share-button').addEventListener('click', function() {
    var userId = 'user_12345';
    var userName = 'John Doe';
    var baseLink = 'https://sample.sng.link/D52wc/cuvk?pcn=test';
    
    ReferralManager.shareReferralLink(userId, userName, baseLink);
  });

  // Setup copy button
  document.getElementById('copy-button').addEventListener('click', function() {
    if (ReferralManager.lastGeneratedLink) {
      ReferralManager.copyToClipboard(ReferralManager.lastGeneratedLink);
      alert('Link copied to clipboard!');
    } else {
      alert('Please generate a link first');
    }
  });
}, false);

Implementation Best Practices

Error Handling

Implement robust error handling in the callback to manage network failures, invalid parameters, or server issues.

  • Retry Logic: Implement exponential backoff for transient network errors
  • User Feedback: Display clear error messages when link creation fails
  • Fallback Option: Provide alternative sharing methods (e.g., share the full Singular Link if short link creation fails)
  • Validation: Verify parameters before calling createReferrerShortLink to catch issues early

Tracking and Analytics

Leverage referrer information to build viral loops and measure organic growth.

Best Practice: Use consistent referrer IDs that match your internal user identification system. This enables you to:

  • Attribute new installs to specific referring users
  • Reward users for successful referrals
  • Track viral coefficient and K-factor metrics
  • Identify your most valuable brand advocates

Link Expiration

Plan for the 30-day link lifecycle in your sharing strategy.

Important: Short links expire after 30 days. For long-term campaigns or persistent share features, generate new short links periodically or use the full Singular Link as a fallback.


Common Use Cases

In-App Referral Programs

Enable users to invite friends directly from your app with personalized referral links.

  • Reward System: Track referrals and reward users for successful friend signups
  • Social Sharing: Integrate with Cordova social sharing plugins for SMS, WhatsApp, email, and social media
  • Personal Invites: Include referrer name in the shared message for personalization

User-Generated Content

Create shareable links when users generate content they want to share with others.

  • Content Attribution: Track which content drives the most app installs
  • Creator Recognition: Attribute new users to content creators for gamification
  • Campaign Tagging: Add dynamic parameters based on content type or category

Event Invitations

Generate unique links for event invitations that track which attendees bring new users.

  • Event Context: Include event ID and details in link parameters
  • Attendee Tracking: Measure viral spread from event to event
  • Network Effects: Identify events with the highest conversion rates

Required Cordova Plugins

Recommended Plugins

Install these Cordova plugins to enhance the referral link sharing experience.

Social Sharing Plugin:

cordova plugin add cordova-plugin-x-socialsharing

Clipboard Plugin:

cordova plugin add cordova-plugin-clipboard

Note: While these plugins are not required for generating short links, they significantly enhance the user experience by enabling native sharing and clipboard functionality.