# Tutorials

{% hint style="success" %}

## Customer Example: How Bolt.new Powered Their Viral Referral Program with GrowSurf’s API

See our in-depth technical [blog post](https://growsurf.com/blog/how-boltnew-powered-their-viral-referral-program-with-growsurfs-api) on how a GrowSurf customer implemented the API, webhooks, and reward metadata to scale their referral program to millions of users.
{% endhint %}

## Table of contents

The following examples use **Node.js**.

| Scenario                                                                                                                                                                                 |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Example 1: Trigger a referral on qualifying action (e.g, on conversion, purchase or upgrade)](#example-1-trigger-a-referral-on-qualifying-action-e.g-on-conversion-purchase-or-upgrade) |
| [Example 2: Trigger a referral on signup event](#example-2-trigger-a-referral-on-signup-event)                                                                                           |
| [Example 3: Get a participant's details](#example-3-get-a-participants-details)                                                                                                          |
| [Example 4: Delete a list of participants](#example-4-delete-a-list-of-participants)                                                                                                     |

## Example 1: Trigger a referral on qualifying action (e.g, on conversion, purchase or upgrade)

{% hint style="info" %}

### **Airbnb as an example**

> ***"**&#x53;end a friend $40 in Airbnb credit. You’ll get $20 when they travel and $75 when they host."*

Follow this tutorial if your program's [referral trigger](https://support.growsurf.com/article/188-what-triggers-a-referral) is *Qualifying Action,* where a referrer only receives credit when the person they referred signs up AND performs a certain qualifying action.
{% endhint %}

This requires two API calls to GrowSurf.

### [Step 1: Make sure you have authentication set up](https://docs.growsurf.com/developer-tools/rest-api/..#getting-started)

### Step 2: Add the participant

{% hint style="warning" %}
**Important Note:** If your program is configured to add participants automatically through a form on your website ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LgbRcVrYaKYUhQVctKK%2F-LgbS62PrNqHiJm-qwdI%2FScreen%20Shot%202019-06-05%20at%207.42.50%20PM.png?alt=media\&token=85e064ce-4bac-4617-9481-f80215478d51)), skip this ste&#x70;**.**
{% endhint %}

First, in the code where you capture the new user's email, add them to your GrowSurf program as a participant with the [**`POST`**` ``Add participant`](https://docs.growsurf.com/developer-tools/api-reference#add-participant) method. Alternatively, you can use the JavaScript method [`growsurf.addParticipant()`](https://docs.growsurf.com/integrate/javascript-web-api/api-reference#add-participant) instead to add participants.

The example below is what that code could look like when using the REST API.

**Code Example**

{% code title="signup.js" %}

```javascript
const request = require("request");

let options = {
  method: 'POST',
  url: 'https://api.growsurf.com/v2/campaign/4pdlhb/participant',
  headers: { 
    Authorization: 'Bearer <YOUR_API_KEY>'
  },
  json: true
};

const signUp = user => {    
    // Set the body of the GrowSurf API request
    options.body = user;
    
    // Send the API request to add the user as a new participant in your GrowSurf program
    request(options, (error, response, body) => {
      if (error) {
        throw new Error(error);
      }
      const growsurfId = body.id;
      // Save the new user to your database (optional)
      saveUser(user, growsurfId);
    });
};
```

{% endcode %}

**At line 21,** we set the GrowSurf participant ID as a variable called `growsurfId`.

**At line 23**, `saveUser(user, growsurfId)` is an example function you would use to save the GrowSurf participant ID to the new user in your database. We will use this `growsurfId`  value later for triggering a referral.

{% hint style="info" %}

### **Don't want to save the `growsurfId` to your database?**

The participant's`email` can be used instead of the `growsurfId` to trigger a referral later. If you have access to the participant's email then there is no need to persist the `growsurfId` into your database.
{% endhint %}

**At line 11**, the `user`  argument passed into `signUp(user)` is an Object that looks like this:

```javascript
{
  email: 'sally_mayweathers9448@gmail.com',
  firstName: 'Sally', // Optional, but recommended for anti-fraud purposes
  lastName: 'Mayweathers', // Optional, but recommended for anti-fraud purposes
  ipAddress: 1.2.1.827, // Optional, but recommended for anti-fraud purposes
  fingerprint: 'dwah12iu3hi1u2h', // Optional, but recommended for anti-fraud purposes
  referredBy: '1cca8d', // The referrer's unique GrowSurf ID. Can also be the referrer's unique email address
  metadata: {
    phoneNumber: '+1 415-123-4567',
    country: 'USA',
    zipCode: '94303'
  } 
}
```

* **At lines 2 and 3,** we pass in `firstName` and `lastName`. These will be used for anti-fraud purposes, as well as in referred friend motivator elements, if enabled.
* **At line 4**, we pass in the user's IP address, which will be used for anti-fraud purposes.
* **At line 5**, we pass in the user's browser fingerprint, which will be used for anti-fraud purposes. You can use a library like [fingerprintjs](https://github.com/fingerprintjs/fingerprintjs) to get this value.
* **At line 6**, we use `referredBy` to associate this new user with a referrer. This value can be the referrer's email address or unique GrowSurf ID (you may want to use [`growsurf.getReferrerId()`](https://docs.growsurf.com/developer-tools/javascript-sdk/api-reference#get-referrer-id) to retrieve the referrer ID).
* **At line 7**, we save a shallow `metadata` Object to the GrowSurf Participant. This is optional, but is useful for viewing specific participant information in your GrowSurf dashboard ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfiWyhm5z0L0AN3V1o_%2F-Lficu90C8YEPgrdhKyA%2FScreen%20Shot%20on%202019-05-25%20at%2018%3A56%3A33.png?alt=media\&token=1d3a352f-652e-4d13-83bd-aab4aa7ae369)).

### **Step 3: Trigger the referral**

{% hint style="warning" %}
**Important Note:** Make sure your program's referral trigger is set to *Sign Up + Qualifying Action* ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LnvqQyyEju4bLT4R5PC%2F-LnvsusHI0xFY2PJcJzB%2FScreen%20Shot%202019-09-04%20at%206.42.06%20PM.png?alt=media\&token=21db3d41-f20b-4887-833c-8109205cbc89)). If the referral trigger is set to *Sign Up*, triggering referrals will not work since referral credit has already been provided.
{% endhint %}

Now at any future date [within the referral credit window](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfTU5fPPuEimujYPBlL%2F-LfTUYdelF4Itf1vXW9T%2FScreen%20Shot%20on%202019-05-22%20at%2015%3A42%3A38.png?alt=media\&token=b1bd5196-2825-4229-b280-0c1240b0b30e), if this new participant performs the goal event, then referral credit will be awarded to their referrer. To trigger the referral, use the [**`POST`**` ``Trigger referral by participant ID`](https://docs.growsurf.com/developer-tools/api-reference#trigger-referral-by-participant-id) method.&#x20;

The example below is what that code could look like.

**Code Example**

{% code title="purchase.js" %}

```javascript
const request = require("request");

let options = {
  method: 'POST',
  headers: { 
    Authorization: 'Bearer <YOUR_API_KEY>'
  },
  json: true
};

const purchase = growsurfId => {
    // ...code that makes the purchase...

    // Set the GrowSurf API request URL with the participant's ID
    options.url = `https://api.growsurf.com/v2/campaign/4pdlhb/participant/${growsurfId}/ref`;

    // Send the API request to trigger the referral
    request(options, (error, response, body) => {
      if (error) {
        throw new Error(error);
      }
      // Check to see if the referral was triggered successfully
      const { success, message } = body.success;
      if(success) {
        console.log('Referral trigger success!');
      } else {
        console.log('Referral trigger failed :( ', message);
      }
    });
};
```

{% endcode %}

**At line 11**, we passed a `growsurfId` argument, which is the GrowSurf participant's unique ID and is required in the API call. If you do not have access to the `growsurfId` of the participant, the participant `email` can be used instead.

{% hint style="info" %}

### **Remember to set up reward fulfillment automation**

Make sure you have [Webhooks](https://docs.growsurf.com/developer-tools/webhooks) or [Zapier](https://docs.growsurf.com/integrations/zapier) set up so that rewards automatically get fulfilled to the participant once they reach a reward goal.
{% endhint %}

## Example 2: Trigger a referral on signup event

{% hint style="info" %}

### **Dropbox as an example**

> ***"**&#x46;or every friend you refer, you’ll both receive an extra 250MB in cloud storage."*

Follow this tutorial if your program's [referral trigger](https://support.growsurf.com/article/188-what-triggers-a-referral) is *Signup Event*, where a referrer receives credit when the person they referred signs up with their email address.
{% endhint %}

This requires just one API call to GrowSurf.

### [Step 1: Make sure you have authentication set up](https://docs.growsurf.com/developer-tools/rest-api/..#getting-started)

### Step 2: Add the participant (and trigger the referral at the same time)

{% hint style="warning" %}
**Important Notes:**

* If your program is configured to add participants automatically through a form on your website ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LgbRcVrYaKYUhQVctKK%2F-LgbS62PrNqHiJm-qwdI%2FScreen%20Shot%202019-06-05%20at%207.42.50%20PM.png?alt=media\&token=85e064ce-4bac-4617-9481-f80215478d51)), skip this ste&#x70;**.**
* Make sure your program's referral trigger is set to *Signup Event* ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-Lnvt7uOcb1oD4xpY-jJ%2F-Lnvtjtp4i_3zpP2Yag7%2FScreen%20Shot%202019-09-04%20at%206.40.09%20PM.png?alt=media\&token=58dea9be-eb47-42c0-b1af-cb392c246e6b)).
  {% endhint %}

In the code where you capture the new user's email, add them to your GrowSurf program as a participant with the [**`POST`**` ``Add participant`](https://docs.growsurf.com/developer-tools/api-reference#add-participant) method.

The example below is what that code could look like.

**Code Example**

{% code title="signup.js" %}

```javascript
const request = require("request");

let options = {
  method: 'POST',
  url: 'https://api.growsurf.com/v2/campaign/4pdlhb/participant',
  headers: { 
    Authorization: 'Bearer <YOUR_API_KEY>'
  },
  json: true
};

const signUp = user => {    
    // Set the body of the GrowSurf API request
    options.body = user;
    
    // Send the API request to add the user as a new participant in your GrowSurf program
    request(options, (error, response, body) => {
      if (error) {
        throw new Error(error);
      }
      
      // Save the new user to your database (Optional)
      saveUser();
    });
};
```

{% endcode %}

**At line 12**, the `user`  argument passed into `signUp(user)` is an Object that looks like this:

```javascript
{
  email: 'sally_mayweathers9448@gmail.com',
  firstName: 'Sally', // Optional, but recommended for anti-fraud purposes
  lastName: 'Mayweathers', // Optional, but recommended for anti-fraud purposes
  ipAddress: 1.2.1.827, // Optional, but recommended for anti-fraud purposes
  fingerprint: 'dwah12iu3hi1u2h', // Optional, but recommended for anti-fraud purposes
  referredBy: '1cca8d', // The referrer's unique GrowSurf ID. Can also be the referrer's unique email address  
  referralStatus: 'CREDIT_AWARDED',
  metadata: {
    phoneNumber: '+1 415-123-4567',
    country: 'USA',
    zipCode: '94303'
  } 
}
```

* **At lines 2 and 3,** we pass in `firstName` and `lastName`. These will be used for anti-fraud purposes, as well as in referred friend motivator elements, if enabled.
* **At line 4**, we pass in the user's IP address, which will be used for anti-fraud purposes.
* **At line 5**, we pass in the user's browser fingerprint, which will be used for anti-fraud purposes. You can use a library like [fingerprintjs](https://github.com/fingerprintjs/fingerprintjs) to get this value.
* **At line 6**, we use `referredBy` to associate this new user with a referrer. This value can be the referrer's email address or unique GrowSurf ID (you may want to use [`growsurf.getReferrerId()`](https://docs.growsurf.com/developer-tools/javascript-sdk/api-reference#get-referrer-id) to retrieve the referrer ID)
* **At line 7**, we set `referralStatus` to be `CREDIT_AWARDED`. This triggers the referral credit at the same time that this new participant is added (and it overrides the program referral trigger ([what's a referral trigger?](https://support.growsurf.com/article/188-what-triggers-a-referral)) that was set from the *Installation* step of the *Program Editor* ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfU6JzlO17UzeyVOQcZ%2F-LfU6SW-uc8zI2uuzeah%2FScreen%20Shot%20on%202019-05-22%20at%2018%3A36%3A23.png?alt=media\&token=6204ba21-12b5-4630-90e3-f6117230d7f9)).
  * **Note:** `referralStatus` must be used with `referredBy`, or else it will be ignored.
* **At line 8**, we save a shallow `metadata` Object to the GrowSurf Participant. This is optional, but is useful for viewing specific participant information in your GrowSurf dashboard ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfiWyhm5z0L0AN3V1o_%2F-Lficu90C8YEPgrdhKyA%2FScreen%20Shot%20on%202019-05-25%20at%2018%3A56%3A33.png?alt=media\&token=1d3a352f-652e-4d13-83bd-aab4aa7ae369)).

{% hint style="info" %}

### **Remember to set up reward fulfillment automation**

Make sure you have [Webhooks](https://docs.growsurf.com/developer-tools/webhooks) or [Zapier](https://docs.growsurf.com/integrations/zapier) set up so that rewards automatically get fulfilled to the participant once they reach a reward goal.
{% endhint %}

## Example 3: Get a participant's details

Let's say you want to display a participant's referral progress/stats/rewards in your website or mobile app. With the REST API, you can fetch [`Participant`](https://docs.growsurf.com/developer-tools/api-objects#participant)s and [`ParticipantReward`](https://docs.growsurf.com/developer-tools/api-objects#participantreward)s  by using either of the following API methods:

* [**`GET`**` ``Get participant by email`](https://docs.growsurf.com/developer-tools/api-reference#get-participant-by-email)
* [**`GET`**` ``Get participant by ID`](https://docs.growsurf.com/developer-tools/api-reference#get-participant-by-id)

### [Step 1: Make sure you have authentication set up](https://docs.growsurf.com/developer-tools/rest-api/..#getting-started)

### Step 2: Retrieve a participant by email

Let's say your server calls your database to retrieve user details and in that same call you want to send their participant information by using their unique email.&#x20;

The example below is what that code could look like.

**Code Example**

```javascript
const request = require("request");

let options = {
	method: 'GET',
	headers: {
  		Authorization: 'Bearer <YOUR_API_KEY>'
  	}
};

const getUserDetails = userEmail => {
	// ...Call your database to get user details...
	// ...code here...

	// Get the GrowSurf participant's details
	request(options, (error, response, body) => {
		options.url = `https://api.growsurf.com/v2/campaign/4pdlhb/participant/${userEmail}`;
	 	if (error) {
			throw new Error(error);
		}
		console.log(body);
	});
};
```

**At line 10**, we passed `userEmail` so we could set it in the GrowSurf API URL at line 16.

**At line 20**, `console.log` would print something like this:

```javascript
{
    "id": "f8g9nl",
    "firstName": "Gavin",
    "lastName": "Belson",
    "referralCount": 2,
    "shareUrl": "https://piedpiper.com?grsf=f8g9nl",
    "email": "gavin@hoolie.com",
    "createdAt": 1552404738928,
    "fraudRiskLevel": "LOW",
    "fraudReasonCode": "UNIQUE_IDENTIY",
    "isWinner": true,
    "shareCount": {
        "email": 10,
        "facebook": 1,
        "pinterest": 1,
        "twitter": 11
    },
    "impressionCount": 2,
    "referrals": [
        "i9g2bh",
        "xua4sq"
    ],
    "referralSource": "PARTICIPANT",
    "referralStatus": "CREDIT_AWARDED",
    "referrer": {
        "id": "h8kp6l",
        "firstName": "Richard",
        "lastName": "Hendricks",
        "referralCount": 5,
        "shareUrl": "https://piedpiper.com?grsf=h8kp6l",
        "email": "richard@piedpiper.com",
        "createdAt": 1552402661449,
        "referralSource": "DIRECT",
        "fraudRiskLevel": "LOW",
        "fraudReasonCode": "UNIQUE_IDENTIY",
        "isWinner": true,
        "shareCount": {
            "email": 20,
            "facebook": 11,
            "linkedin": 0,
            "pinterest": 3,
            "twitter": 12
        },
        "impressionCount": 14,
        "referrals": [
            "0dveu7",
            "f8g9nl",
            "j0hbym",
            "m5xm9l",
            "w01fil"
        ]
    }
}
```

## Example 4: Delete a list of participants

Let's say you want to delete a list of participants in your GrowSurf Campaign. With the REST API, you can use the [**`DELETE`**` ``Remove Participant by Email`](https://docs.growsurf.com/developer-tools/rest-api/api-reference#remove-participant-by-email) endpoint to loop through a CSV list of participants to accomplish this.

**Code Example (Node.js)**

In this example, we've provided two sample files you may download and use. Follow the instructions below:

1. Replace `API_KEY` and `CAMPAIGN_ID` at lines 1 and 2 in the `script.js` file, respectfully.
2. Replace the email addresses in the `emails.csv` file with your own list of participants that you want to delete (keep the column header labeled as "Email")
3. Run `npm install request require csv-parser` to install dependencies
4. Run `node script.js` to run the script

{% tabs %}
{% tab title="script.js" %}
{% code title="script.js" lineNumbers="true" %}

```javascript
const API_KEY = "ABC123FS9GM2FBJFZ68T7JNAMRCZ" // Replace with your own API key
const CAMPAIGN_ID = "2x3b5c";                  // Replace with your campaign ID

const request = require('request');
const csv = require("csv-parser");
const fs = require("fs");

async function removeParticipant(participantEmail) {
  const headers = {
    "Authorization": `Bearer ${API_KEY}`,
    'Content-Type': 'application/json'
  };
  const url = `https://api.growsurf.com/v2/campaign/${CAMPAIGN_ID}/participant/${participantEmail}`;
  const options = {
    'method': 'DELETE',
    'url': url,
    'headers': headers
  };
  request(options, function (error, response) {
    if (error) {
      throw new Error(error);
    } else {
      const responseBody = JSON.parse(response.body);
      if (responseBody.success) {
        console.log(`✅ ${participantEmail} removed successfully`);
      } else {
        console.log(`❌ Error removing ${participantEmail} (${responseBody.message})`);
      }
    }
  });
}

async function main() {
  const reader = fs.createReadStream("emails.csv").pipe(csv());
  for await (const row of reader) {
    if (row["Email"]) {
      const participantEmail = row["Email"];
      await removeParticipant(participantEmail);
      await new Promise(resolve => setTimeout(resolve, 1000)); // Slow down by 1 second per request
    }
  }
}

main();
```

{% endcode %}
{% endtab %}

{% tab title="emails.csv" %}
{% code title="emails.csv" lineNumbers="true" %}

```csv
Email
person1@company.com
person2@company.com
person3@company.com
```

{% endcode %}
{% endtab %}
{% endtabs %}

**Some other notes:**

* The script will begin deleting participants one by one, waiting 1 second between each request to comply with our [rate limit policy](https://docs.growsurf.com/developer-tools/rest-api/api-guidelines#rate-limits).
* The script will display progress and status updates for each deletion operation.
* Depending on the number of participants, the deletion process may take some time. Please be patient.
