NPM Package

Please begin with the installation and then you can move on to this.

In the installation section, we discussed on how to create Campaign and Referral Links for our AwesomeApp using Referral-API API(s) and dashboard interface.

With campaign in place, we now wish to capture every visit made to our website through the referral links and track various actions performed by referred users. For this we can make use of the NPM package Referral-API offers.

Step 1: Installation

We need to first install NPM package using following command:

Your Terminal

npm i referralapi

Step 2: Initialize Package

Now we are required to initialize the Referral API Class, since Referral-API Package follows a singleton approach, we are required to initialize it once and use its instance throughout our web-app.

Invoke ReferralAPI methods, including initialization, exclusively on the client-side to ensure compatibility and prevent errors related to server-side and client-side code execution.

Thus we would initialize it on the root of our project, assuming we are using “React” for our client side code, and root of our project is “App.js”, I would initialize it like this with api-key and the campaign-id:

App.js

import ReferralAPI from "referralapi"
import {useEffect} from "react"

const App = ({children}) => {
    useEffect(() => {
        const referral = new ReferralAPI('your_api_key', 'your_campaign_id');
    }, [])
}

With this initialization in place, when a user is directed to your website through a referral link, ReferralAPI automatically stores information about the referral link as a cookie. This cookie remains active for 30 days. The presence of this cookie signifies that the current user accessing the website arrived via a referral link.

Whenever any user accesses your website while the referral cookie is present, the Referral-API logs an action with the action_type set to "VISIT. You can view the statistics in the analytics tab of a campaign dashboard.

In the installation section, we discussed about creating links using Referral-API's API or dashboard interface. However you can create and fetch referral links using our NPM Package, eliminating the need for making explicit API calls. We can do this by calling createReferralLink function that NPM Package offers.

For our "Summer Referral Bonanza", let us allow one referral link to be associated with every user of ours. Thus before creating a referral link, we are required to check if a referral link exists for our user, for this we can make use of getReferralLinks function.

createReferralLink function takes an optional parameter referrer_id and returns a referral link object.

getReferralLinks function requires referrer_id as argument and retrieves a list of referral links associated with the specified referrer_id for a particular campaign. If no such links exist, the function returns an empty list.

We can implement the following code snippet to generate and retrieve referral links, which will be displayed on the banner of our AwesomeApp Dashboard, enticing users to participate in the "Summer Referral Bonanza" campaign:

Dashboard.js

import ReferralAPI from "referralapi"
import {useState, useEffect} from "react"

export default function Dashboard() {
    const referralAPI = ReferralAPI.getInstance();
    const [referralLink, setReferralLink] = useState("");

    useEffect(() => {
        fetchReferralLink()
    }, [])

    async function fetchReferralLink() {
        while (!referralAPI.isReady()) {
            // Waits untill referralAPI is ready, always better to wait referral api to be initialized.
            await new Promise(resolve => setTimeout(resolve, 100)); // Wait for 100 milliseconds before checking again
        }

        // Assuming we have authenticated user's email address handy. For this example we are using email address as referrer id.
        referralAPI.getReferralLinks(referrer_id).then(async (res) => {
            if (res.length == 0) {
                const referralLink = await referralAPI.createReferralLink(referrer_id);
                setReferralLink(referralLink.referral_link);
            } else {
                setReferralLink(res[0].referral_link);
            }
        }).catch((err) => {

        })
    }

    return (
        <Banner> referralLink </Banner>
    )
}

Step 4: Tracking Referrals - Referred Users

When users share referral links, there's a possibility that the link may be clicked by existing users of our website. However, the primary goal of our referral program is to expand our user base. Therefore, we aim to differentiate between new users and existing users who arrive on our website through referral links. This distinction allows us to accurately track and attribute new user acquisitions to our referral program, ensuring that our metrics reflect the program's effectiveness in attracting and retaining new users.

ReferralAPI provides functionality to create "Referred User", using createReferredUser function.

The createReferredUser function requires the referred_user_id, an arbitrary string that uniquely identifies a user of your website. It associates a "referred_user_id" with only one referral link belonging to the campaign. This function is responsible for creating a "Referred User" when invoked in the presence of a referral link cookie. It returns Referred User Object in case the referred user gets created otherwise returns null. We can invoke this function when there is successful signup as following:

Signup.js

import ReferralAPI from "referralapi"

export default function SignUpPage() {
  const referralAPI = ReferralAPI.getInstance();

  const handleSignUp = async () => {
      try {
          const response = await axios.post('/signup', { email, password });

          // Checks if referralAPI has been initialized
          if (referralAPI.isReady()) {
              const referralResponse = await referralAPI.createReferredUser(email);
              // Optionally handle response
          }
      } catch (error) {
          // Handle any error
      }
  };

  return (

  // Sign up page code goes here

  <Button onClick={handleSignUp}>
  Sign Up</Button>

  )
}

Therefore, any new user who signs up and is directed to the website through a referral link will be categorized as a "Referred User." These users can be viewed under the Referrals tab on the dashboard.

This also solves one part of our problem, that is tracking successful Signups for our “Summer Referral Bonanza”

Step 5: Tracking Funnels

While we've successfully tracked new sign-ups through our referral program, our focus often extends beyond mere registrations. We're keen to understand the subsequent actions these new users take on our platform, as it enables us to tailor rewards for referrers accordingly. By delving deeper into user behavior post-signup, we can identify valuable engagement metrics such as purchases, subscriptions, or other desired actions.

ReferralAPI offers the createAction function to facilitate tracking and rewarding user actions beyond sign-ups. This function necessitates specifying an action_type as a string, along with metadata - a JSON Object and an optional parameter, referred_user_id.

When utilizing the createAction function without specifying a referred_user_id, it records an action for any user browsing your website while a referral cookie is present. This method treats both existing users and referred users equally, as they are both identified by the presence of the referral cookie. This inclusive approach aids in assessing the overall effectiveness of the referral program, providing insights into user engagement regardless of referral status. Additionally, it enables tracking of actions that may be initiated by unauthenticated users, contributing to a comprehensive understanding of user behavior and program impact.

For example, on AwesomeApp's blog section, users have the option to anonymously like blog posts. By leveraging referral tracking mechanisms, we can monitor the engagement levels of users who arrive through referral links. This includes tracking the number of users who visit our blog section via referral links and the subset of those users who further engage with the content by liking blog posts. This comprehensive approach enables us to assess the effectiveness of our referral program in driving traffic to our blog and fostering user engagement with the content.

Returning to the core objective of any Referral Program, it is essential to effectively track and analyze the actions taken by newly referred users. That is where the referred_user_id field comes in handy.

In the context of AwesomeApp Referral Program, we wish to track every purchase made by the referred user. We can incorporate the following code after successful purchase of any product. Assuming that after successful payment, user is directed to a order confirmation page, where we can call this function:

Successful-Payment.js

import ReferralAPI from "referralapi"

export default function SuccessfulPayment(props) {
    const referralAPI = ReferralAPI.getInstance();
    referralAPI.createAction("PURCHASED_PRODUCT", {"productIds" : props.productId}, email);

}

So, in this scenario, the createAction function is invoked every time any user purchases product(s). However, ReferralAPI only creates actions for those purchases that are done by the "Referred Users".

To achieve this, ReferralAPI checks if the provided referred_user_id (in this case, the user's email, since it serves as the user ID in the campaign design) is present in the Campaign's Referred User section. If the referred_user_id is found, ReferralAPI adds the action and associates it with the referred user. However, if the referred_user_id is not found, ReferralAPI simply ignores the request, as it indicates that the action was not performed by a referred user.

createAction function returns Action Object in case action gets successfully created otherwise returns null.

Please note to create successful action pinning to a referred user, it is not necessary to have a referral cookie, only thing necessary is that provided referred_user_id had already been associated with the camapaign as a "Referred User". However for creating action without pinning it to any user, presence of cookie is important.

In certain scenarios, validating operations like successful purchases of subscriptions through the frontend may not be feasible due to security concerns. In such cases, the validation process is typically handled by our backend or server-side code. As an alternative, actions can be created by directly making a call to the Referral-API's Action API.

Do check out sandbox for better understanding of integration with npm package.

Rewarding Users

This is still under work in progress. In the meantime, you can make use of webhooks to recieve the realtime updates about your referral program enabling you to promptly release rewards to participants.

Please reach out to inquire about a specific rewarding solution.

Next Steps

Checkout out API Reference for detailed guide about each of the methods discussed in this tutorial.