# Referd Developers Docs

Welcome to Referd Developers Docs, here you can find your guide for an easy and seamless integration with Referd.

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td></td><td><strong>iOS</strong></td><td></td><td><a href="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FXz6OTeHlFsXub8uVGeKs%2FiOS.svg?alt=media&amp;token=791c222a-86cd-4344-8caf-ddcfd3b7296f">iOS.svg</a></td><td><a href="/installing-referd/referd-for-ios">iOS</a></td></tr><tr><td></td><td><strong>Android</strong></td><td></td><td><a href="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FXsX2FNXHPBwUE9raJGyI%2FAndriod.svg?alt=media&amp;token=535a22ad-1aa0-4c28-bbfa-d855bc87f0c6">Andriod.svg</a></td><td><a href="/installing-referd/referd-for-android">Android</a></td></tr><tr><td></td><td><strong>React Native</strong></td><td></td><td><a href="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FP1I4LBQWdViqH70ZqOzy%2FReact.svg?alt=media&amp;token=80434a26-0515-48a1-bf3d-183fc5129826">React.svg</a></td><td><a href="/installing-referd/referd-for-react">React Native</a></td></tr><tr><td></td><td><strong>Flutter</strong></td><td></td><td><a href="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FNh43eXWFOjmNedKnYgrS%2FFlutter.svg?alt=media&amp;token=4ce42a8c-abb5-464e-8caf-2f47c93f1dc0">Flutter.svg</a></td><td><a href="/installing-referd/referd-for-flutter">Flutter</a></td></tr><tr><td></td><td><strong>Generic Mobile App</strong></td><td></td><td><a href="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FXAtULhsYdqMIstDwi578%2FMobile-App.svg?alt=media&amp;token=418cec68-42a5-4f99-902e-0d687030c2be">Mobile-App.svg</a></td><td><a href="/installing-referd/referd-for-generic-mobile-app">Generic Mobile App</a></td></tr></tbody></table>

<br>


# Introduction

\
**Referd** is a comprehensive referral program designed for business owners, enabling them to incentivize users by rewarding them for successful referrals. When users refer a friend, both parties stand to receive gifts. These gifts can either be selected from a diverse range of gift cards that can be bought from our platform or can be customized by business owners for their users.

Our platform features a user-friendly widget for seamless reward redemption, making it easy for users to claim their incentives. Additionally, **Referd** provides detailed analytics through a dedicated analytics page, offering insights into user referral activities. To enhance user engagement ,push and email notifications are also available, ensuring a robust and rewarding referral experience for both businesses and users alike.

**Referd** Docs is where you can find all the resources you need to start integrating our engagement, rewards, and retention experience to your customer. These resources should take you through our fast and easy integration guide with little effort. You will find all needed resources on APIs and mobile integration SDKs.

Jump to any article you need to check through the sidebar on your left-hand side. You can also navigate to our ordered articles through the forward and backward buttons below.

You can integrate with **Referd** using our [REST APIs](/api-reference/overview-on-referd-apis) that are organized around REST principles. Our APIs have resource-oriented URLs, accepts form-encoded request bodies and return JSON-encoded responses.

In addition to the REST API, **Referd** has official libraries\SDKs for different programming languages and mobile platforms. Integrating **Referd** into your app or website can begin as soon as you create a **Referd** account, all you have to do is to check the Guided steps depending on your technology for:

1. [Android Native](/installing-referd/referd-for-android)
2. [iOS Native](/installing-referd/referd-for-ios)
3. [React Native](/installing-referd/referd-for-react)
4. [Flutter](/installing-referd/referd-for-flutter)
5. [Generic Mobile App](/installing-referd/referd-for-generic-mobile-app)

Or directly use our REST APIs.


# iOS

This section takes you through a step-by-step journey to integrate Referd into your iOS app through these guides


# Getting Started

Install the Referd iOS SDK into your app

The **Referd** SDK for iOS enables you to use the show **Referd** user profile in your app, track app user events, integrate referrals and display **Referd's** in-app push notifications.

## Installation

Follow the below steps to start installing the iOS SDK to your app

#### **1. Add Cocoapods to Your Project**

{% hint style="info" %}
If your project is using CocoaPods, skip to the next part of this article, [Add Referd Pod](#id-2.-add-referd-pod).
{% endhint %}

* Open the terminal window
* Navigate to the root folder of your Xcode project
* Run the following command in terminal

```objectivec
$ pod init
```

* Close Xcode if open then open your project’s newly created .xcworkspace
* Your project is now using CocoaPods to install dependencies

#### **2. Add Referd Pod**

* Add the code below in your Podfile which was created by CocoaPods

```ruby
source 'https://github.com/CocoaPods/Specs.git'
target 'YourAppName' do
           use_frameworks!
           pod 'Gameball',
End
```

* Navigate to your project’s root folder in a terminal window
* Run the command below in terminal

```objectivec
$ pod install
```

* Referd will install several Pods that it has as dependencies.

{% hint style="success" %}
When the Pod command finishes execution, you will have Referd installed and ready to use.
{% endhint %}

{% hint style="info" %}
Referd is also available through **\[Swift Package Manager]**. To install it, simply search for 'Referd' or add the repo URL:

```
https://github.com/gameballers/gameball-ios.git
```

{% endhint %}

## Initialization

Import the SDK into the created pod, using CocoaPods, to setup the **Referd** Widget in the best way for your use-case.

In order to use Referd you must configure a GameballApp.

* Import our pod to your viewController

```objectivec
import Gameball
```

* Create a global GameballApp variable in your viewController to access anywhere within your viewController

```swift
var gameball: Gameball?
```

* Then initialize it as the following:

```swift
gameball = Gameball(
    apiKey: "YOUR_API_KEY", // The only required field
    lang: "ar",
    shop: "MyShop",
    platform: "iOS",
    completion: { [weak self] in // Completion block when SDK init is completed
        guard let self = self else {return}
        // You can enable showing profile, registering player, etc. see next section
    }
)
```

## &#x20;<a href="#user-registration" id="user-registration"></a>

| Parameter    | Required | Description                                                                                                                                                                                                                                                                                                                                                 |
| ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`     | Required | Client API key                                                                                                                                                                                                                                                                                                                                              |
| `lang`       | Optional | <p>Your platform language preference to view <strong>Referd</strong> Widget with. <strong>Note:</strong> The language provided should be as per configured languages in your account. If not provided the Referd profile widget will be shown with your account default language.</p><p><strong>Example:</strong> <code>"en"</code>, <code>"fr"</code>.</p> |
| `completion` | Optional | Completion block that gets called when the initialization of the SDK is completed                                                                                                                                                                                                                                                                           |

{% hint style="info" %}
You may also check the sample project [here](https://github.com/gameballers/gameball-ios/tree/master/Example) to view full implementation.
{% endhint %}


# Initialize Referd User Profile

Show your users's profile including all details and progress on your iOS app.

Showing the **Referd** widget on your mobile application is slightly different than showing it on the website. You have two options; first, if you want to design your customer interface, you will use our set of REST APIs.\
\
The other option as this section elaborates, is through using our iOS SDK.

Using the SDK, you can open the **Referd** user profile from a button in your app, programmatically when someone does something, or from a persistent button that sits over your app’s UI.

When you trigger the **Referd** user profile, your user is presented with a home screen. This is configurable inside **Referd** to change how it looks and what’s presented.

From there, your user can check his progress across different **Referd** programs as per your configurations.

<figure><img src="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FXcTIA8yqOOlts6FbUE1R%2Fimage%20(4).png?alt=media&amp;token=7c6e6b59-8448-440d-8256-aed4dcd40e15" alt=""><figcaption></figcaption></figure>

**Referd’s** views are accessible through the code below. You just need to use it on any button action.

## Register User

The **Register User** method is used to create or update user accounts at **Referd**. This API call should be made when the user successfully logs in or whenever there are updates to the user's account information.

```swift
// After completion block is called from init the SDK, you can register player

self.gameball?.registerPlayer(
    playerUniqueId: "UNIQUE_PLAYER_ID", // The only required field
    deviceToken: "firebase_token",
    playerAttributes: [
        "custom_attribute": "custom_value",
        "country": "Egypt"
    ],
    completion: { (playerId, error) in // Completion block after registeration is complete
    // You either get Referd playerId or error
})
```

The below is description of register user parameters

<table data-header-hidden><thead><tr><th width="212">Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Required</strong></td><td><strong>Description</strong></td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td><strong>Yes</strong></td><td><p>Unique identifier for the user in your database.</p><p>Could be database ID, random string, email or anything that uniquely identifies the user.</p></td></tr><tr><td><code>deviceToken</code></td><td><strong>string</strong></td><td><strong>No</strong></td><td>Firebase token obtained from Firebase SDK to avail <strong>Referd</strong> to send notifications to the user.</td></tr><tr><td><code>playerAttributes</code></td><td><strong>dictionary</strong></td><td><strong>No</strong></td><td>Any custom parameters you want to attach to the user.</td></tr><tr><td><code>completion</code></td><td><strong>Completion block</strong></td><td><strong>Yes</strong></td><td>Returns either <strong>Referd</strong> user ID or error in registration.</td></tr></tbody></table>

{% hint style="success" %}
Every time the **Referd View** is initialized with a new **PlayerUniqueId** , the user profile is created or updated at **Referd** side. You may consider enriching your Referd's user profile with attributes that are not available to the UI by using server side [Create\Update User API](/api-reference/api-reference/player#post-create-player)
{% endhint %}

{% hint style="warning" %}
**Choose an Unchangeable Player Unique ID**

**Referd** user profile gets created using the **`playerUniqueId`**. It is highly recommended to have the unique ID as an identifier that would NEVER be changed. If this unique ID changes for a given user , you risk losing all original data for that user on **Referd**. Accordingly, it is NOT recommended to use email address or mobile number as the unique ID as both can be changed by the user at anytime.
{% endhint %}

To generate **Device Token (FCM Token)** you can use Firebase latest SDK you can put this code in AppDelegate or your ViewController to get the token and once you get the token you can call the above method to register and Launch Referd&#x20;

```swift
// Based on latest Firebase documentation you can generate token by

       Messaging.messaging().token { token, error in
          if let error = error {
            print("Error fetching FCM registration token: \(error)")
          } else if let token = token {
            print("FCM registration token: \(token)")
              // you can save the token anyware then use it while launching Referd
          }
        }
```

Once the **APIKey** and **playerUniqueId** have been registered, Referd views can be made visible to the user. So ideally, **`registerPlayer`** is called after the **`completion block`** of the SDK initalization.

## Show the widget

To show the Referd user profile that contains the user details, user challenges, and the leaderboard use the ***showProfile*** SDK function.

```swift
@IBAction func didTapLaunch(_ sender: UIButton) {
    gameball?.showProfile(
        playerUniqueId: "UNIQUE_PLAYER_ID",
        openDetail: "custom_detail",
        hideNavigation: false,
        completion: { viewController, errorMessage in
            guard let gameBallVC = viewController else {return}
            gameBallVC.modalPresentationStyle = .fullScreen
            self.present(gameBallVC, animated: true, completion: nil)
        }
    )
}
```

Upon user action, you can use **`showProfile`** function to show the widget. The **`completion`** block tells you that the **`viewController`** is ready and you can present it the way you want, for example by default if you don't explicitly specify **`modalPresentationStyle`**, it'll appear as modal. If you want it full screen, you can specify it like the above example.

| Parameter        | Type        | Required | Description                                                                                                                               |
| ---------------- | ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `playerUniqueId` | **String**  | Required | Unique identifier for the user in your database.Could be database ID, random string, email or anything that uniquely identifies the user. |
| `openDetail`     | **String**  | Optional | Specify if you want the widget to open on a specific view. Possible values are `details_referral`                                         |
| `hideNavigation` | **Boolean** | Optional | Set to true to stop widget navigation otherwise leave as null                                                                             |

{% hint style="info" %}
You may also check the sample project [here](https://github.com/gameballers/gameball-ios/tree/master/Example) to view full implementation.
{% endhint %}


# Track User Events

Start sending your users' events on your platform to Referd.

Start sending your users' **events** on your app or platform to **Referd**, along with any **metadata** that describes the event. Depending on your **Referd** programs configuration, the user can be rewarded based on the sent events.

Every `Track Event` call records a single user action. We call these “**events**”. We recommend that you make your event names human-readable, so that everyone can know what they mean instantly.

**Event metadata** are extra pieces of information you can tie to events you track. They can be anything that will be useful while designing your program.

Tracked **events** can be app events or server side events depending on how you would like to design your programs. App events can be sent to **Referd** via the methods available in the SDK below. For server side events you can use [Track Events API](/api-reference/api-reference/event).

To send User events from your app to Referd, you can use the **`sendEvents`** that takes array of **`Event`** which takes **`eventName`**&#x6F;f type string and **`parameters`**&#x6F;f type dictionary to be sent with the event.

### **Send Events example**

```swift
let events: [Event] = [
    Event(eventName: "coin_purchase", params: ["price": "100", "currency": "USD"]),
    Event(eventName: "click_X_screen", params: ["screen_name": "X_Y_Z", "source": "A_B_C"]),
]
gameball?.sendEvents(
    playerUniqueId: "UNIQUE_PLAYER_ID",
    events: events
)
```


# Push Notifications

Integrate your app with Referd push notifications and interactive in-app messaging.

**Referd** uses Firebase to deliver maximum experience in your app. This includes push notifications, interactive in-app messaging and referrals support.

![](https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2Fgit-blob-f1b68e583e5af1affdb33c31e69eef37f6324682%2Fin-App-notifications-Mobile\(2\).png?alt=media)

### Configure Referd With Your Firebase

Before you start, you must configure your Firebase on your Referd account. Follow the steps in [Configure your Firebase account on Referd for mobile push notifications](https://help.tryreferd.com/en/articles/8668480-get-your-referd-integration-details) article from our Help Center related to push notifications.

### Handling Push Notifications Integration

Configure notifications as usual and add two more methods using our SDK. This is normal integration for general firebase notifications configuration, so here is a how-to guide.

1\. Add the below to the **AppDelegate** class

```swift
Inherit :UNUserNotificationCenterDelegate, MessagingDelegate
Add var gameballApp: Gameball?
```

2\. Then put these lines **didFinishLaunchingWithOptions()** in **AppDelegate**

```swift
FirebaseApp.configure()
registerForPushNotifications()
```

3\. Add these stack of lines to the **AppDelegate** class

```swift
    func registerForPushNotifications() {
        UNUserNotificationCenter.current()
            .requestAuthorization(options: [.alert, .sound, .badge]) {
                [weak self] granted, error in
                UNUserNotificationCenter.current().delegate = self
                Messaging.messaging().delegate = self
                guard granted else { return }
                self?.getNotificationSettings()
        }
    }

    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
```

4\. Here we need to add this method to register token to **Referd** in this method

```swift
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
                let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
                let token = tokenParts.joined()
        if let refreshedToken = InstanceID.instanceID().token() {
            print("InstanceID token: (refreshedToken)")
            self.gameballApp?.registerDevice(withToken: refreshedToken)
        }
    }
```

5\. Here we need to add this method to let **Referd** handle everything related to Referd Widget

```swift
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        gameballApp?.notificationPopUP(notification: notification)
    }
```

Your users can now receive push notifications from **Referd**.


# Go-Live Checklist

Use this checklist to ensure a smooth transition when taking your integration live.

If you are a developer, or had a developer perform an integration for you between your web application and **Referd**. You should also consider the following items before going live.

{% hint style="info" %}
During development, you can use your account Test Key to authenticate your requests. Once integration is completed and validate you can swap to Production API Key.
{% endhint %}

### Step 1 : Install Referd SDK

* [ ] Install and import **Referd** SDK into your App
* [ ] Initialize **Referd** SDK

*If you will be using **Referd** in-app notifications or referrals*

* [ ] Install and import Firebase SDKs into your App

### Step 2 : Register Your Player

* [ ] Send player data to **Referd** within your login\registration flows.

### Step 3 : Referd User Widget Integration

* [ ] Show **Referd** user profile widget within your App experience

👑 *If your building your own UI components to maintain your branding*

* [ ] Custom UI components are build and integrated with **Referd** within your web\app UI

### Step 4 : Tracking User events

* [ ] User events are sent to **Referd** with correspondent metadata and properties to track UI events within your App
* [ ] User events are sent to **Referd** with correspondent metadata and properties to track server side events related to the user

### Step 5 : Integrate Notifications

* [ ] Add the Firebase dependency to your project.
* [ ] Add SDK code snippet to show [in-app notifications](/installing-referd/referd-for-ios/push-notifications-on-ios)

### Step 6 : Referrals Tracking

* [ ] Invoke SDK referral method upon successful user registration.


# Android

This section takes you through a step-by-step journey to integrate Referd into your Android app through these guides


# Getting Started

Install the Referd Android SDK into your app

**Referd's** Android SDK enables you to use the show **Referd** user profile in your app, track app user events, integrate referrals and display Referd's in-app push notifications.

## Setting up Referd SDK

Follow the below steps to start installing **Referd's** Android SDK to your app.

Add JitPack repository to your project's *build.gradle* (or *settings.gradle* if you're on newer versions) file.

```gradle
dependencyResolutionManagement {
    ...
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}
```

Add the following dependency to the application's *build.gradle* file to import Referd's SDK into your project.

```gradle
dependencies {
    ...
    implementation 'com.github.gameballers:gb-mobile-android:1.2.10'  
}
```

{% hint style="info" %}
Make sure that you added the INTERNET permission in your application's ***AndroidManifest.xml** file as follows:*

<pre class="language-xml"><code class="lang-xml"><strong>&#x3C;manifest xmlns:android="http://schemas.android.com/apk/res/android"
</strong>xmlns:tools="http://schemas.android.com/tools">
    ...
    &#x3C;uses-permission android:name="android.permission.INTERNET" />
    ...
&#x3C;/manifest>
    
</code></pre>

{% endhint %}

### To install Firebase Google Play Services dependencies

The SDK uses Firebase Dynamic Links to track referrals and Firebase Messaging for sending push notifications, you'll need to add the following dependencies.

```gradle
dependencies {
    ...
    // Make sure to include this dependency even if you won't include Firebase Messaging
    implementation platform('com.google.firebase:firebase-bom:<latest_version>')
    // Firebase Dynamic Links only - must be included
    implementation "com.google.firebase:firebase-dynamic-links"    
    // Firebase Messaging only - optional depending on whether or not you want to use FCM
    implementation 'com.google.firebase:firebase-messaging'  
}
```

{% hint style="info" %}
For the latest Firebase SDK (BOM, Cloud Messaging, Deep Links, and Google Services) versions check their [release notes](https://firebase.google.com/support/release-notes/android).
{% endhint %}

You also need to add *google-services* plugin to your application.

**App's** *build.gradle* file:

```gradle
plugins {
    ...
    id 'com.google.gms.google-services'
}
```

**Project**'s *build.gradle* file:

```gradle
buildscript{
    ...
    dependencies {
        ...
        classpath 'com.google.gms:google-services:<latest_version>'

    }
}
```

{% hint style="info" %}
Don't forget to include your *google-services.json* to your *app* root after registering it to a Firebase project.

Follow [this](https://firebase.google.com/codelabs/fcm-and-fiam#0) tutorial to learn more on how to register your Android application to Firebase.
{% endhint %}

## Initialize Refer SDK

### Create a GameballApp instance

o create a GameballApp instance you need to call the **getInstance** method and pass it a **Context** instance of the current ***Activity*** holding the GameballApp.

{% tabs %}
{% tab title="Java" %}

```java
GameballApp gameballApp = GameballApp.getInstance(getApplicationContext());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val gameballApp = GameballApp.getInstance(applicationContext)
```

{% endtab %}
{% endtabs %}

#### Initialize GameballApp Instance

To initialize GameballApp instance in your application class, use the **init** method which takes the following parameters:

<table data-header-hidden><thead><tr><th width="231">Parameter</th><th width="90">Type</th><th width="103">Required</th><th>Description</th></tr></thead><tbody><tr><td><strong>Parameter</strong></td><td>Type</td><td><strong>Required</strong></td><td><strong>Description</strong></td></tr><tr><td><code>APIKey</code></td><td><strong>string</strong></td><td><strong>Yes</strong></td><td>Client API key</td></tr><tr><td><code>lang</code></td><td><strong>string</strong></td><td><strong>No</strong></td><td><p>Your platform language preference to view <strong>Referd</strong> Widget with.</p><p><strong>Note:</strong> The language provided should be as per configured languages in your account. If not provided the <strong>Referd</strong> profile widget will be shown with your account default language</p><p><strong>Example:</strong> <code>"en"</code>, <code>"fr"</code>.</p></td></tr></tbody></table>

{% tabs %}
{% tab title="Java" %}
{% code fullWidth="true" %}

```java
// Using the instantiated instance of GameballApp
gameballApp.init("{{your API Key}}", "{{lang}}", "{{your Platform name}}", "{{your Shop name}}");

//You can access the init method directly as follows
GameballApp.getInstance(getApplicationContext()).init("{{your API Key}}", "{{lang}}", "{{your Platform name}}", "{{your Shop name}}");
```

{% endcode %}
{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// Using the instantiated instance of GameballApp
gameballApp.init("{{your API Key}}", "{{lang}}", "{{your Platform name}}", "{{your Shop name}}")

//You can access the init method directly as follows
GameballApp.getInstance(applicationContext).init("{{your API Key}}", "{{lang}}", "{{your Platform name}}", "{{your Shop name}}")
```

{% endtab %}
{% endtabs %}

### Initialize Firebase Push Notifications

To be able to use Firebase Push Notifications feature through Referd you'd need to first initialize firebase device token by calling the following method right after the ***init*** method or before the registration of the user.

{% tabs %}
{% tab title="Java" %}

```java
// Using the instantiated instance of GameballApp
gameballApp.initializeFirebase();
```

{% endtab %}
{% endtabs %}


# Initialize Referd User Profile

Show your players's profile including all details and progress on your Android app.

Showing the Referd widget on your mobile application is slightly different than showing it on the website. You have two options; first, if you want to design your customer interface, you will use our set of REST APIs.\
\
The other option as this section elaborates, is through using our android SDK.

Using the SDK, you can open the **Referd** user profile from a button in your app, programmatically when someone does something, or from a persistent button that sits over your app’s UI.

When you trigger the **Referd** user profile, your player is presented with a home screen. This is configurable inside **Referd** to change how it looks and what’s presented.

From there, your user can check his progress across different **Referd** programs as per your configurations.

<figure><img src="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FXcTIA8yqOOlts6FbUE1R%2Fimage%20(4).png?alt=media&amp;token=7c6e6b59-8448-440d-8256-aed4dcd40e15" alt=""><figcaption></figcaption></figure>

## Showing Referd Profile

To show the Referd player profile that contains the user details, user challenges, and the leaderboard use **showProfile()** SDK method.

<table data-header-hidden><thead><tr><th width="214">Parameter</th><th width="110">Type</th><th width="115">Required</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>Activity</code></td><td><strong>Activity</strong></td><td><strong>Yes</strong></td><td>Current activity instance holding the GameballApp which will be used in showing the User's profile.</td></tr><tr><td><code>PlayerUniqueId</code></td><td><strong>String</strong></td><td><strong>Yes</strong></td><td><p>Unique identifier for the user in your database.</p><p>Could be database ID, random string, email or anything that uniquely identifies the user.</p></td></tr><tr><td><code>openDetail</code></td><td><strong>String</strong></td><td><strong>No</strong></td><td>Specify if you want the widget to open on a specific view. Possible values are <code>details_referral</code></td></tr><tr><td><code>hideNavigation</code></td><td><strong>Boolean</strong></td><td><strong>No</strong></td><td>Set to true to stop widget navigation otherwise leave as null.</td></tr></tbody></table>

{% tabs %}
{% tab title="Java" %}

```java
gameballApp.showProfile(this, "{{playerUniqueId}}", "{{openDetail}}", "{{hideNavigation}}");
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
gameballApp.showProfile(this, "{{playerUniqueId}}", "{{openDetail}}", "{{hideNavigation}}")
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Use showProfile as a parameter to collect the activity or the fragment you are going to show the profile in. Just create a button and call this method in the onClick() method of this button.
{% endhint %}

**Change Profile Widget language**

***`changeLanguage(String language)`***

Use `changeLaguage` SDK method to change the widget language.The language provided should be as per configured languages in your account. If not provided the **Referd** profile widget will be shown with your account default language

**Example:** `"en"`, `"fr"`.

## Register/Update User&#x20;

You should register your users with **Referd**. This can be done using **`registerPlayer`**&#x6D;ethod which can be used to create or update the player details at **Referd**. Ideally, it is called when your login or register network call is successful.

<table data-header-hidden><thead><tr><th width="220">Parameter</th><th width="110">Type</th><th width="115">Required</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>PlayerUniqueId</code></td><td><strong>string</strong></td><td><strong>Yes</strong></td><td><p>Unique identifier for the user in your database.</p><p>Could be database ID, random string, email or anything that uniquely identifies the user.</p></td></tr><tr><td><code>PlayerAttributes</code></td><td><strong>object</strong></td><td><strong>No</strong></td><td>PlayerAttributes is a builder class with set of properties that you want to set for the user.</td></tr><tr><td><code>Activity</code></td><td><strong>Activity</strong></td><td><strong>Yes</strong></td><td>Current activity instance holding the GameballApp which will be used in detecting the referal code from the dynamic link.</td></tr><tr><td><code>Intent</code></td><td><strong>Intent</strong></td><td><strong>Yes</strong></td><td>An intent instance that will be used in combination with the Activity to detect the referal code from the dynamic link.</td></tr><tr><td><code>CallBack</code></td><td><strong>function</strong></td><td><strong>No</strong></td><td>Callback is used for providing the developer with the response status and payload.</td></tr></tbody></table>

{% hint style="success" %}
Everytime the **SDK** is initialized with a new p**layerUniqueId** , the user profile is created or updated at **Referd** side. You may consider enriching your Referd's user profile with attributes that are not avialable to the UI by using server side [Create\Update User API](/api-reference/api-reference/player#post-create-player)
{% endhint %}

{% hint style="warning" %}
**Choose an Unchangeable Player Unique ID**

**Referd** user profile gets created using the **`playerUniqueId`**. It is highly recommended to have the unique ID as an identifier that would NEVER be changed. If this unique ID changes for a given player, you risk losing all original data for that user  on **Referd**. Accordingly, it is NOT recommended to use email address or mobile number as the unique ID as both can be changed by the user at anytime.
{% endhint %}

**`PlayerAttributes`Object**

PlayerAttributes is a builder class that helps in creation of the PlayerAttributes with the common attributes mentioned below, all of these attributes are **optional** to use.

<table><thead><tr><th width="207">Method</th><th>Parameter Name</th><th>Type</th></tr></thead><tbody><tr><td>withDisplayName</td><td>displayName</td><td>string</td></tr><tr><td>withFirstName</td><td>firstName</td><td>string</td></tr><tr><td>withLastName</td><td>lastName</td><td>string</td></tr><tr><td>withEmail</td><td>email</td><td>string</td></tr><tr><td>withGender</td><td>gender</td><td>string</td></tr><tr><td>withMobileNumber</td><td>mobileNumber</td><td>string</td></tr><tr><td>withDateOfBirth</td><td>dateOfBirth</td><td>string</td></tr><tr><td>withJoinDate</td><td>joinDate</td><td>string</td></tr><tr><td>withCustomAttribute</td><td>(key, value)</td><td>(string, string)</td></tr></tbody></table>

#### An example to create *PlayerAttributes* object

{% tabs %}
{% tab title="Java" %}

```java
PlayerAttributes playerAttributes = new PlayerAttributes.Builder()
        .withDisplayName("John Doe")
        .withFirstName("John")
        .withLastName("Doe")
        .withMobileNumber("0123456789")
        .withCustomAttribute("{key}", "{Value}")
        .build();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val playerAttributes = PlayerAttributes.Builder()
    .withDisplayName("John Doe")
    .withFirstName("John")
    .withLastName("Doe")
    .withMobileNumber("0123456789")
    .withCustomAttribute("{key}", "{Value}")
    .build()
```

{% endtab %}
{% endtabs %}

The previous example will return an object of PlayerAttributes with DisplayName “Jack”

### Register the User

Using the previously created GameballApp instance or by creating a new one, call the ***RegisterPlayer()*** method as shown below

{% tabs %}
{% tab title="Java" %}

```java
gameballApp.registerPlayer(
    "{{uniquePlayerId}}", 
    playerAttributes, 
    this, 
    this.getIntent(), 
    new Callback<PlayerRegisterResponse>() {
        @Override
        public void onSuccess(PlayerRegisterResponse playerRegisterResponse) {
            // TODO Handle on success result.
        }
    
        @Override
        public void onError(Throwable e) {
            // TODO Handle on failure result.
        }
});
```

{% endtab %}
{% endtabs %}


# Track Referd Events

Start sending your users' events on your platform to Referd.

Start sending your users' **events** on your app to **Referd**, along with any **metadata** that describes the event. Depending on your **Referd** programs configuration, the user can be rewarded based on the sent events.

Tracked **events** can be app events or server side events depending on how you would like to design your programs. App **events** can be sent via the available SDK interface and server-sdie **events** can be sent to **Referd** via the [Track Events API](/api-reference/api-reference/event).

Every `Track Event` call records a single user action. We call these “**events**”. We recommend that you make your event names human-readable, so that everyone can know what they mean instantly.

**Event metadata** are extra pieces of information you can tie to events you track. They can be anything that will be useful while designing your program.

To send Player events from your app to **Referd**, you can use the **`sendEvent`** method as shown below.

<table data-header-hidden><thead><tr><th width="220">Parameter</th><th width="110">Type</th><th width="115">Required</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>Event</code></td><td><strong>Event Object</strong></td><td><strong>Yes</strong></td><td>Event body that is being sent to Referd's dashboard.</td></tr><tr><td><code>CallBack</code></td><td><strong>function</strong></td><td><strong>No</strong></td><td>Callback is used for providing the developer with the status of the request as a boolean whether it succeeded or not or with an error if any.</td></tr></tbody></table>

**`SendEvent`** interface sends an **`Event`**&#x6F;bject to **Referd**. Where the **`Event`**&#x6F;bject is a wrapper holding a single or list of events. To add an event you should use the **`sendEvent`** method and pass to it th&#x65;**`Event`**&#x6F;bject you have created.

***SendEvent*** is a builder class that helps in creation of the **Event** with the common attributes mentioned below, all of these attributes are **optional** to use.

<table><thead><tr><th width="207">Method</th><th>Parameter Name</th><th>Type</th></tr></thead><tbody><tr><td>AddUniquePlayerId</td><td>UniquePlayerId</td><td>String</td></tr><tr><td>AddEventName</td><td>eventName</td><td>string</td></tr><tr><td>AddEmail</td><td>email</td><td>string</td></tr><tr><td>AddMobile</td><td>mobileNumber</td><td>string</td></tr><tr><td>AddeventMetaData</td><td>(key, value)</td><td>(string, Object)</td></tr></tbody></table>

{% tabs %}
{% tab title="Java" %}

```java
Event event = new Event.Builder()
        .AddUniquePlayerId("player123")
        .AddEventName("purchase_completed")
        .AddEmail("jack@domain.com")
        .AddMobile("0123456789")
        .AddEventMetaData("purchase_price", 19.99)
        .build();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val event = Event.Builder()
    .AddUniquePlayerId("player123")
    .AddEventName("purchase_completed")
    .AddEmail("jack@domain.com")
    .AddMobile("0123456789")
    .AddEventMetaData("purchase_price", 19.99)
    .build()
```

{% endtab %}
{% endtabs %}

### Send the Event

Using the previously created GameballApp instance or by creating a new one, call the ***SendEvent()*** method as shown below.

{% tabs %}
{% tab title="Java" %}

```java
gameballApp.sendEvent(event, new Callback<Boolean>() {
    @Override
    public void onSuccess(Boolean aBoolean) {
        // TODO Handle on success result
    }

    @Override
    public void onError(Throwable e) {
        // TODO Handle on failure result
    }
});
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
gameballApp.sendEvent(event, object : Callback<Boolean?> {
    override fun onSuccess(aBoolean: Boolean?) {
        // TODO Handle on success result
    }

    override fun onError(e: Throwable) {
        // TODO Handle on failure result
    }
})
```

{% endtab %}
{% endtabs %}


# Push Notifications

Integrate your app with Referd push notifications and interactive in-app messaging.

Referd uses Firebase to deliver maximum experience in your app. This includes push notifications, interactive in-app messaging.

![](https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2Fgit-blob-de218867c1ccdeaecee50a08596d6986e30bef14%2Fin-App-notifications-Mobile\(2\)%20\(1\).png?alt=media)

### Configure Referd With Your Firebase

Before you start, you must configure your Firebase on your Referd account. Follow the steps in [Configure your Firebase account on Referd for mobile push notifications](https://help.tryreferd.com/en/articles/8668480-get-your-referd-integration-details) article from our Help Center related to push notifications.

### Handling Push Notifications Integration

Add the following code line to the first line of the **onMessageReceived** method in your **FirebaseMessagingService** class.

{% tabs %}
{% tab title="Java" %}

```java
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (GameBallApp.getInstance(this).isGameBallNotification(remoteMessage))
        return;

    // TODO: your code here
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
override fun onMessageReceived(message: RemoteMessage) {
    super.onMessageReceived(message)
    
    if (GameBallApp.getInstance(this).isGameBallNotification(remoteMessage)) 
        return

        // TODO: your code here
}
```

{% endtab %}
{% endtabs %}

Your users can now receive push notifications from **Referd**.


# Go-Live Checklist

Use this checklist to ensure a smooth transition when taking your integration live.

If you are a developer, or had a developer perform an integration for you between your web application and Referd. You should also consider the following items before going live.

{% hint style="info" %}
During development, you can use your account Test Key to authenticate your requests. Once integration is completed and validate you can swap to Production API Key.
{% endhint %}

### Step 1 : Install Referd SDK

* [ ] Install and import Referd SDK Dependency into your App.
* [ ] Install Firebase Dynamic Links Dependency.

*If you will be using Referd in-app notifications*

* [ ] Install and import Firebase Messaging SDKs into your App.

### Step 2 : Initalize Referd SDK

* [ ] Insatntiate GameballApp instance.
* [ ] (Optional) Create Player Attributes.
* [ ] Send user data to **Referd** within your login\registration flows.

### Step 3 : Referd User Profile (Widget Integration)

* [ ] Show Referd user profile widget within your App experience

👑 *If your building your own UI components to maintain your branding*

* [ ] Custom UI components are build and integrated with **Referd** within your web\app UI

### Step 4 : Tracking User events

* [ ] User events are sent to Referd with correspondent metadata and properties to track UI events within your App
* [ ] User events are sent to Referd with correspondent metadata and properties to track server side events related to the user


# React Native

This section takes you through a step-by-step journey to integrate Referd into your React native app through these guides


# Getting Started

Install the Referd React Native SDK into your app

The Referd Android and iOS package, enables you to use the show Referd user profile in your app, track app user events, integrate referrals and display Referd's in-app push notifications.

## Installation <a href="#installation" id="installation"></a>

Follow the below steps to start installing react native SDK package to your app

* Install package using npm

```typescript
npm install --save react-native-gameball
```

* Install prerequisite packages using npm

```bash
npm install react-native-modal react-native-push-notification-popup
```

{% hint style="info" %}
react-native-modal and react-native-push-notification-popup packages are required to use gameball package.
{% endhint %}

{% hint style="info" %}
Fetch API is used for network communications, conversion of response to json is needed in order to read the response\
res => res.json()
{% endhint %}

## Initialization

In order to use Referd SDK, apply the below step to the **main JS file (index or app)**.

**Import Referd Widget**

```typescript
import {GameballWidget} from ‘react-native-gameball’;
```

**Initialize Referd Widget**

```typescript
GameballWidget.init(gameball_apiKey, lang, shop, platform, deepLinks )
```

| Parameter         | Type       | Required | Description                                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `gameball_apiKey` | string     | Required | Client API key                                                                                                                                                                                                                                                                                                                                                   |
| `lang`            | **string** | Optional | <p>Your platform language preference to view <strong>Referd</strong> Widget with.</p><p><strong>Note:</strong> The language provided should be as per configured languages in your account. If not provided the Referd profile widget will be shown with your account default language</p><p><strong>Example:</strong> <code>"en"</code>, <code>"fr"</code>.</p> |

## Register User

Register user method is used to create or update users at Referd. It is called when your login network call is successful.

First, import Referd SDK as follows:

```typescript
import {GameballSDK} from 'react-native-gameball';
```

then

```typescript
GameballSDK.registerPlayer({
      "playerUniqueId": playerId,
      "playerTypeId": playerTypeId,
      "deviceToken": playerDeviceToken,
      "playerAttributes": {
        "displayName": "Alex",
        "email": "example@example.com",
        "gender": "m",
        "mobileNumber": "01099999999",
        "dateOfBirth": "2019-08-18T10:11:34.478Z",
        "joinDate": "2019-08-18T10:11:34.478Z" 
       }
}).then(res => res.json()).then(jsonResponse => {...}) // on success
```

Once the **APIKey** and **playerUniqueId** have been registered, Referd views can be made visible to the user.

<table data-header-hidden><thead><tr><th width="225">Param</th><th width="127">Required</th><th>Description</th><th>Type</th></tr></thead><tbody><tr><td>Param</td><td>Required</td><td>Description</td><td>Type</td></tr><tr><td><code>playerUniqueId</code></td><td>Required</td><td>PlayerUniqueId is a unique ID for you user, for example UUID or username. The PlayerUniqueId is to be provided by the client and must be unique for each user.</td><td>String</td></tr><tr><td><code>playerTypeId</code></td><td>Optional</td><td>Each User type has an ID</td><td>Integer</td></tr><tr><td><code>playerAttributes</code></td><td>Optional</td><td>PlayerAttributes is a builder class which you will use to add or update your player info to Referd. </td><td>Object</td></tr><tr><td><code>deviceToken</code></td><td>Optional</td><td>Mobile device token used for push notifications<br><strong>Note:</strong> Should be sent along with <code>osType</code></td><td>String</td></tr></tbody></table>

{% hint style="warning" %}
**Choose an Unchangeable Player Unique ID**

Referd user profile gets created using the **`playerUniqueId`**. It is highly recommended to have the unique ID as an identifier that would NEVER be changed. If this unique ID changes for a given user, you risk losing all original data for that user on Referd. Accordingly, it is NOT recommended to use email address or mobile number as the unique ID as both can be changed by the user at anytime.
{% endhint %}


# Initialize Referd User Profile

Show your user's profile including all details on React-native app.

Showing the **Referd** widget on your mobile application is slightly different than showing it on the website. You have two options; first, if you want to design your customer interface, you will use our set of REST APIs. \
\
The other option as this section elaborates, is through using our react native SDK.

Using the SDK, you can open the **Referd** user profile from a button in your app, programmatically when someone does something, or from a persistent button that sits over your app’s UI.

When you trigger the **Referd** user profile, your player is presented with a home screen. This is configurable inside **Referd** to change how it looks and what’s presented.

From there, your user can check his progress across different **Referd** programs as per your configurations.

<figure><img src="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FXcTIA8yqOOlts6FbUE1R%2Fimage%20(4).png?alt=media&amp;token=7c6e6b59-8448-440d-8256-aed4dcd40e15" alt=""><figcaption></figcaption></figure>

To show the **Referd** user profile that contains the user details use the below steps.

```typescript
import {GameballWidget} from 'react-native-gameball';
```

There are two ways to view the widget.

### Show as standalone screen

```markup
<GameballWidget />
```

### **Show as** Modal

```markup
<GameballWidget 
  modal={true}
/>
```

and then to open the widget you need to call the **showProfile** function on the ref property of the widget

Example on running the widget as a Modal:

#### Class component

```tsx
return (
      <View style={{ flex: 1 }}>
        <Button
          title={'open widget'}
          onPress={() => this.widget.showProfile()}
        />
        <GameballWidget
          ref={(ref) => this.widget = ref}
          modal={true}
        />
      </View>
)
```

#### Functional component

```tsx
const ref = createRef();
return (
  <View>
    <Button title="Open modal" onPress={() => ref.current.showProfile()} />
    <GameballWidget modal={true} ref={ref} />
  </View>
)
```

### Advanced Techniques: Deep Links

In certain scenarios, where you offer a product as a free reward, you might want to showcase this product within the Referd widget along with a deep link. When users click on the deep link, they will be seamlessly redirected to the product page within your app, where they can obtain more information and take further action. To enable this functionality, you need to follow the steps outlined below.

1. Create a custom Referd widget that is based on the default widget and implemented as a ForwardRefRenderFunction.
2. Override the WebView's 'onShouldStartLoadWithRequest' event with a customized implementation.
   * In this implementation, detect URLs that begin with '{your\_app\_deep\_link\_prefix}://' to identify deep links specific to your app.
   * Handle these deep links using the main app's action to process and dispatch them, instead of relying on the WebView."


# Track User Events

Start sending your users' events on your platform to Referd.

Start sending your users' **events** on your app to **Referd**, along with any **metadata** that describes the event. Depending on your **Referd** programs configuration, the user can be rewarded based on the sent events.

Tracked **events** can be app events or server side events depending on how you would like to design your programs. App **events** can be sent via the avialable SDK interface and server-sdie **events** can be sent to **Referd** via the [Track Events API](/api-reference/api-reference/event).

Every `Track Event` call records a single user action. We call these “**events**”. We recommend that you make your event names human-readable, so that everyone can know what they mean instantly.

**Event metadata** are extra pieces of information you can tie to events you track. They can be anything that will be useful while designing your program.

To send Player events from your app to **Referd**, you can use the **`sendEvent`** SDK interface as below.

Import **Referd Sdk**

```typescript
import {GameballSdk} from 'react-native-gameball';
```

Sending event without metadata in the form {String: any}

```typescript
GameballSdk.sendEvent({"review": {}})
.then(response => console.log(response)) // on success
.catch(error => console.log(error)) // on error
```

Sending event with different metadata in the form {String: {String: any}}

```typescript
GameballSdk.sendEvent({
    "Buy": {         
     "Amount": "100",
      "Type": “Electronics”
     }}).then(response => console.log(response)) // on success
    .catch(error => console.log(error)) // on error
```


# Push Notifications

Integrate your app with Referd push notifications and interactive in-app messaging.

Referd uses Firebase to deliver maximum experience in your app. This includes push notifications, interactive in-app messaging.

![](https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2Fgit-blob-a66f2be73d572c61caf08b67884cf8000620a8ae%2Fimage%20\(11\).png?alt=media)

### Configure Referd With Your Firebase

Before you start, you must configure your Firebase on your **Referd** account. Follow the steps in [Configure your Firebase account on Referd for mobile push notifications](https://help.tryreferd.com/en/articles/8668480-get-your-referd-integration-details) article from our Help Center related to push notifications.

### Handling Push Notifications Integration

For notifications handling, add this code to the **`onNotification`** function in your app:

```typescript
onNotification: (notification) => {
// you need to check the platform because firebase send the notification based on the platform

if (Platform.OS === 'android') { // Android
          if(notification.isGB){
                  // send notification direct to InAppNotification as described below
          }
        }
        else { // IOS
          if (notification.data.isGB) {
                  // send notification.data to InAppNotification as described below
          }
        }
}
```

Import **InAppNotification**

```typescript
import {InAppNotification} from 'react-native-gameball';
```

**InAppNotification** takes the following properties:

| Parameter      | Required     | Description                                         | Type         |
| -------------- | ------------ | --------------------------------------------------- | ------------ |
| `notification` | **Required** | Pass the notification data received from the server | Notification |

You can use it in different two ways: one is by adding it directly underneath the main app like shown.

```jsx
<Provider>
    <AppNavigator>
    <InAppNotification 
      notification={this.props.notification}
    />
</Provider>
```

Another approach is to have a separate component which handles the InAppNotification component and pass to it the data directly.

{% code title="SeparateComponent.tsx" %}

```jsx
render(){
    return(
    <InAppNotification
        readnotification={this.props.notification}
    />
   )
}
```

{% endcode %}

After that, add it underneath your main app component as follows.

```jsx
<Provider>
        <AppNavigator />
        <SeparateComponent/>
</Provider>
```

Your users can now receive push notifications from **Referd**.


# Go-Live Checklist

Use this checklist to ensure a smooth transition when taking your integration live.

If you are a developer, or had a developer perform an integration for you between your web application and **Referd**. You should also consider the following items before going live.

{% hint style="info" %}
During development, you can use your account Test Key to authenticate your requests. Once integration is completed and validate you can swap to Production API Key.
{% endhint %}

### Step 1 : Install Referd SDK

* [ ] Install and import **Referd** SDK into your App
* [ ] Initialize **Referd** SDK

*If you will be using **Referd** in-app notifications or referrals*

* [ ] Install and import Firebase SDKs into your App

### Step 2 : Register Your User

* [ ] Send user data to **Referd** within your login\registration flows.

### Step 3 : Referd User Widget Integration

* [ ] Show **Referd** user profile widget within your App experience

👑 *If your building your own UI components to maintain your branding*

* [ ] Custom UI components are build and integrated with **Referd** within your web\app UI

### Step 4 : Tracking User events

* [ ] User events are sent to **Referd** with correspondent metadata and properties to track UI events within your App
* [ ] User events are sent to **Referd** with correspondent metadata and properties to track server side events related to the user

### Step 5 : Integrate Notifications

* [ ] Add the Firebase dependency to your project.
* [ ] Add SDK code snippet to show [in-app notifications](/installing-referd/referd-for-android/push-notifications-on-android)

### Step 6 : Referrals Tracking

* [ ] Invoke SDK referral method upon successful user registration.


# Flutter

This section takes you through a step-by-step journey to integrate Referd into your Flutter app through these guides


# Getting Started

Install the Referd Flutter SDK into your app

The Referd SDK for Flutter enables you to use the show Referd user profile in your app, track app user events, integrate referrals.

## Installation

Follow the below steps to start installing the Flutter SDK to your app

### Use this package as a library

#### Depend on it

Run this command:

With Flutter:

```shell
 $ flutter pub add gameball
```

This will add a line like this to your package's pubspec.yaml (and run an implicit `flutter pub get`):

```yaml
dependencies:
  gameball: ^0.0.3
```

Alternatively, your editor might support `flutter pub get`. Check the docs for your editor to learn more.

#### Import it

Now in your Dart code, you can use:

```dart
import 'package:gameball/gameball.dart';
```


# Initialize Referd User Profile

Show your user's profile including all details and progress on your Flutter app.

Showing the **Referd** widget on your mobile application is slightly different than showing it on the website. You have two options; first, if you want to design your customer interface, you will use our set of REST APIs. \
\
The other option as this section elaborates, is through using our Flutter SDK.

Using the SDK, you can open the **Referd** user profile from a button in your app, programmatically when someone does something, or from a persistent button that sits over your app’s UI.

When you trigger the **Referd** user profile, your player is presented with a home screen. This is configurable inside **Referd** to change how it looks and what’s presented.

From there, your user can check his progress across different **Referd** programs as per your configurations.

<figure><img src="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FXcTIA8yqOOlts6FbUE1R%2Fimage%20(4).png?alt=media&amp;token=7c6e6b59-8448-440d-8256-aed4dcd40e15" alt=""><figcaption></figcaption></figure>

**Referd’s** views are accessible through the code below. You just need to use it on any button action.&#x20;

{% code overflow="wrap" %}

```swift
// If you want to create/Update User just create 
//Send with from string then convert it to json or create a json and sent it directly

let playerAttributesString =  '''
{
  "playerUniqueId": <PLAYER_ID>,
  "mobile": "+1234567",
  "email": "jon.snow@example.com",
  "playerAttributes": {
    "displayName": "Jon Snow",
  },
  "levelOrder": null
}
''';

 final Map<String, dynamic> playerData = jsonDecode(playerDataString);

```

{% endcode %}

<pre class="language-swift"><code class="lang-swift">     apiKey: &#x3C;YOUR_API_KEY>,
     playerUniqueId: &#x3C;YOUR_PLAYER_UNIQUE_ID>,
     lang: 'en',
<strong>     playerAttributes: playerData
</strong>   );
 

// In your widget just path thr context for the sdk like 
 gameball.openGameballView(context);
   
   
   
</code></pre>

Once the **APIKey** and **playerUniqueId** have been registered, **Referd** views can be made visible to the user.

The below is description of Initialization params

<table data-header-hidden><thead><tr><th width="210"></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Parameter</strong></td><td>Type</td><td><strong>Required</strong></td><td><strong>Description</strong></td></tr><tr><td><code>APIKey</code></td><td><strong>string</strong></td><td><strong>Yes</strong></td><td>Client API key</td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td><strong>Yes</strong></td><td><p>Unique identifier for the user in your database.</p><p>Could be database ID, random string, email or anything that uniquely identifies the user.</p></td></tr><tr><td><code>lang</code></td><td><strong>string</strong></td><td><strong>No</strong></td><td><p>Your platform language preference to view <strong>Referd</strong> Widget with.</p><p><strong>Note:</strong> The language provided should be as per configured languages in your account.</p><p><strong>Example:</strong> <code>"en"</code>, <code>"fr"</code>.</p></td></tr></tbody></table>

{% hint style="success" %}
Everytime the **Referd View** is initialized with a new **PlayerUniqueId** , the user profile is created or updated at **Referd** side. You may consider enriching your **Referd's** user profile with attributes that are not available to the UI by using server side [Create\Update User API](/api-reference/api-reference/player#post-create-player)
{% endhint %}

{% hint style="warning" %}
**Choose an Unchangeable Player Unique ID**

**Referd** user profile gets created using the **`playerUniqueId`**. It is highly recommended to have the unique ID as an identifier that would NEVER be changed. If this unique ID changes for a given user, you risk losing all original data for that user on **Referd**. Accordingly, it is NOT recommended to use email address or mobile number as the unique ID as both can be changed by the user at anytime.
{% endhint %}


# Track User Events

Start sending your users' events on your platform to Referd.

Start sending your users' **events** on your app or platform to **Referd**, along with any **metadata** that describes the event. Depending on your **Referd** programs configuration, the user can be rewarded based on the sent events.

Every `Track Event` call records a single user action. We call these “**events**”. We recommend that you make your event names human-readable, so that everyone can know what they mean instantly.

**Event data** are extra pieces of information you can tie to events you track. They can be anything that will be useful while designing your program.

Tracked **events** can be app events or server side events depending on how you would like to design your programs. App events can be sent to **Referd** via the methods available in the SDK below. For server side events you can use [Track Events API](/api-reference/api-reference/event).

To send user events from your app to **Referd**, you can use the **`sendEvent`** SDK methods.

### **Send Event With data**

```dart
 Future<Map<String, dynamic>> sendEvent(Map<String, dynamic> eventData) async {}
```

**Example**

```dart
//Send with Meta data, send with from string then convert it to json
// or create a json and sent it directly

let eventDataString = 
'''{
 "buy": {
  "product_id": "a123456",
  "price": 30,
  "product_category": "fashion"
  "product_tags": ["men", "new_collection"]
}
} ''';

    final Map<String, dynamic> eventData = jsonDecode(eventDataString);

   gameball.sendEvent(eventData).then((response) {
      print(response); // Success
    }).catchError((error) {
      print(error); // Error
    });
```


# Go-Live Checklist

Use this checklist to ensure a smooth transition when taking your integration live.

If you are a developer, or had a developer perform an integration for you between your web application and **Referd**. You should also consider the following items before going live.

{% hint style="info" %}
During development, you can use your account Test Key to authenticate your requests. Once integration is completed and validate you can swap to Production API Key.
{% endhint %}

### Step 1 : Install Referd SDK

* [ ] Install and import **Referd** SDK into your App
* [ ] Initialize **Referd** SDK

*If you will be using **Referd** in-app notifications or referrals*

* [ ] Install and import Firebase SDKs into your App

### Step 2 : Register Your User

* [ ] Send user data to **Referd** within your login\registration flows.

### Step 3 : Referd User Widget Integration

* [ ] Show **Referd** user profile widget within your App experience

👑 *If your building your own UI components to maintain your branding*

* [ ] Custom UI components are build and integrated with **Referd** within your web\app UI

### Step 4 : Tracking User events

* [ ] User events are sent to **Referd** with correspondent metadata and properties to track UI events within your App
* [ ] User events are sent to **Referd** with correspondent metadata and properties to track server side events related to the user

### Step 5 : Referrals Tracking

* [ ] Invoke SDK referral method upon successful user registration.


# Generic Mobile App

In this guide, we'll explore how to integrate **Referd** within your mobile app without using **Referd's** SDK. This can be helpful if your mobile app framework does not have an out of the box SDK provided by **Referd** like Flutter or ionic. Or you choose not to use the SDK for any reason. So let's get started!

Before we dive deeper into integrating **Referd** into your mobile app without using an SDK, let's first take a look at the common integration touch points that you'll encounter. These touch points are the areas in your app where you'll need to make changes to incorporate **Referd's** features seamlessly.

{% hint style="info" %}
This guide is not framework specific. Below is a general high level guideline illustrating how to integrate **Referd** with applicable mobile frameworks
{% endhint %}


# Initialize Referd User Profile

Show your user's profile including all details.

{% hint style="info" %}
This guide is not framework specific. Below is a general high level guideline illustrating how to integrate **Referd** with applicable mobile frameworks
{% endhint %}

## Referd user profile sync <a href="#docs-internal-guid-bda94c0c-7fff-97e0-f9f7-3b49e410cb1c" id="docs-internal-guid-bda94c0c-7fff-97e0-f9f7-3b49e410cb1c"></a>

The first touch point is the login/registration screen. This is where users create an account or sign in to an existing account in your app. **Referd** requires users' profiles to be synced to track their progress and reward them accordingly.

User profiles can be synced using the [Create User API](/api-reference/api-reference/player#post-create-player) method. Where it creates or updates the user's profile with each call.

It's recommended that the [Create User API](/api-reference/api-reference/player#post-create-player) is called with every login or account update.

{% hint style="info" %}
Depending on your app design, profile sync API calls can be made from your backend system or from within the app.
{% endhint %}

## Show **Referd U**ser Profile

The second touch point is to show the player's loyalty profile from **Referd** within your app. This is where users can view their progress and rewards.

There  integrate **Referd's** loyalty profile into your mobile app use the out-of-the-box widget.

**Referd** offers pre-built widget that you can easily add to your mobile app if your framework supports Webviews.

<figure><img src="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FfFEZUmTo2PBMcV0ogy9b%2Fimage%20(4).png?alt=media&amp;token=3610052e-0d82-4d03-a964-013104a40867" alt=""><figcaption></figcaption></figure>

let's illustrate the sequence to show **Referd** profile widget using Webview:

1. Add menu item to your app menu or user's profile page
2. Upon click, open Webview that points to a self-hosted webpage with **Referd** widget scripts embedded in it.
3. Pass user's data to Webview

The first step is to create a blank HTML page and host it at your desirable domain path as below

*`https://yourdomain.com/webview-address/index.html`*

This created empty page will be responsible to load **Referd** widget for your mobile app user.

On page header include **Referd** widget loading script.

```javascript
<script>
    window.GbLoadInit = function(){
        GbSdk.init({
            playerUniqueId: '{{playerUniqueId}}',
            lang: 'en',
            playerAttributes:{},
            APIKey: '{{Your_API_Key}}'
        });
    };
</script>
<script defer src="https://assets.gameball.co/widget/js/gameball-init.min.js"></script>
```

For mobile app case, a new parameter must exist in the loading script

```javascript
mobile:true
```

So the loading script would be as below

```javascript
<script>
    window.GbLoadInit = function(){
        GbSdk.init({
            playerUniqueId: '{{playerUniqueId}}',
            lang: 'en',
            playerAttributes:{},
            APIKey: '{{Your_API_Key}}',
            mobile:true
        });
    };
</script>
<script defer src="https://assets.gameball.co/widget/js/gameball-init.min.js"></script>
```

### Pass user data to your Webview <a href="#how-to-pass-data-from-chatfuel-to-your-webview" id="how-to-pass-data-from-chatfuel-to-your-webview"></a>

The widget will display user's profile depending on the passed parameters to the init script. In order to pass user's data from your mobile app to Webview\Referd's widget, there are two options depending on your framework capabilities.

If the used framework supports passing params\variables to Webview you can pass logged in user profile data directly to the Webview and inject them to **Referd** widget loading script.

The other option is to pass players data to **Referd** loading script via query strings while loading Webview as below example

*`https://yourdomain.com/webview-address?playerUniqueId={{playerUniqueId}}&displayName={{displayName}}`*

Once the data is added to the query string, you can use JavaScript to retrieve the data and pass it to the **Referd** widget script. Here's an example of how you can do this:

<pre class="language-javascript"><code class="lang-javascript">&#x3C;script>
    // Get the query string parameters
<strong>    const queryString = window.location.search;
</strong>    const urlParams = new URLSearchParams(queryString);

    // Get the user's email and display name from the query string
<strong>    const playerUniqueId= urlParams.get('playerUniqueId');
</strong>    const userDisplayName = urlParams.get('displayname');

    window.GbLoadInit = function(){
        GbSdk.init({
            playerUniqueId: {{playerUniqueId}},
            mobile:true,
            playerAttributes: {
                displayName: {{displayName}}
            },
            lang: 'en',
            APIKey: '{{Your_API_Key}}'
        });
    };
&#x3C;/script>
</code></pre>

By following the steps outlined above, you can easily pass user data to the widget script and provide your users with a seamless and personalized experience.

{% hint style="warning" %}
If you choose to go with using the pre-built widget in a Webview. You need to take care of the Webview interactions within your app. How the user can navigate from and to the Webview easily. We recommend showing the Webview as a modal with a back button on top.
{% endhint %}


# Track User Events

Start sending your users' events on your platform to Referd.

Start sending your users' **events** on your app to **Referd**, along with any **metadata** that describes the event. Depending on your **Referd** programs configuration, the player can be rewarded based on the sent events.

Tracked **events** can be app events or server side events depending on how you would like to design your programs. App **events** can be sent via the avialable SDK interface and server-sdie **events** can be sent to **Referd** via the [Track Events API](/api-reference/api-reference/event).

Every `Track Event` call records a single user action. We call these “**events**”. We recommend that you make your event names human-readable, so that everyone can know what they mean instantly.

**Event metadata** are extra pieces of information you can tie to events you track. They can be anything that will be useful while designing your program.


# Push Notifications

Integrate your app with Referd push notifications and interactive in-app messaging.

**Referd** webhooks can be used to avail push notifications for mobile users. This can be done by webhook subscriptions to receive notifications for particular events in **Referd** . After you have subscribed to a webhook, your app can execute a specific code immediately after specific events occur in **Referd** . Common webhook use cases include sending notifications to IM clients and pagers


# Go-Live Checklist

Use this checklist to ensure a smooth transition when taking your integration live.

If you are a developer, or had a developer perform an integration for you between your web application and **Referd**. You should also consider the following items before going live.

{% hint style="info" %}
During development, you can use your account Test Key to authenticate your requests. Once integration is completed and validate you can swap to Production API Key.
{% endhint %}

### Step 1 : Install Referd SDK

* [ ] Install and import **Referd** SDK into your App
* [ ] Initialize **Referd** SDK

*If you will be using **Referd** in-app notifications or referrals*

* [ ] Install and import Firebase SDKs into your App

### Step 2 : Register Your User

* [ ] Send user data to **Referd** within your login\registration flows.

### Step 3 : Referd User Widget Integration

* [ ] Show **Referd** user profile widget within your App experience

👑 *If your building your own UI components to maintain your branding*

* [ ] Custom UI components are build and integrated with **Referd** within your web\app UI

### Step 4 : Tracking User events

* [ ] User events are sent to **Referd** with correspondent metadata and properties to track UI events within your App
* [ ] User events are sent to **Referd** with correspondent metadata and properties to track server side events related to the user

### Step 5 : Integrate Notifications

* [ ] Add the notifications mechanism to your project

### Step 6 : Referrals Tracking

* [ ] Invoke SDK referral method upon successful user registration.


# Overview

This section gives a detailed guide on all Referd APIs that are needed during integration.

The **Referd** API is organized around [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer). Our API has predictable resource-oriented URLs, returns [JSON-encoded](http://www.json.org/) responses, and uses standard HTTP response codes, authentication, and verbs.\
\
In this section, you will find all the available APIs required across all **Referd** features as well as all the API methods that can be used in the SDKs.

## Authentication

Before using any of our API endpoints, you need to get familiar with how **Referd** authenticates any incoming requests. Which is described in details in the [**Authentication**](/api-reference/authentication) section.

## API Reference

**Referd** provides a set of endpoints which enables you to interact with and utilize **Referd** Engine efficiently. All supported endpoints are described as follows:

* [User](/api-reference/api-reference/player)
* [Event](/api-reference/api-reference/event)
* [Notifications](/api-reference/api-reference/notifications)

#### Base URL

The API base URL is the following, with v3.0 as our current version.

```http
https://api.gameball.co/api/{version}
```

{% hint style="info" %}
Check the following section to learn more about the [**API Reference**](/api-reference/api-reference).
{% endhint %}

<br>

## **API Endpoint Testing**

To facilitate efficient testing and exploration of our API endpoints, we provide a dedicated Postman collection. This collection encompasses a comprehensive set of API calls, streamlining your testing process. To make the most of this Postman collection, detailed instructions on how to use each API endpoint and harness its capabilities have been meticulously documented in [API Endpoint Testing Section](/api-reference/api-endpoint-testing).

## Errors

Learn more about common errors and their description in our [**Errors** ](/api-reference/error-codes)section.


# Authentication

The Referd API uses API keys to authenticate requests. You can view your API keys in the Referd Dashboard.

**Referd** APIs are authenticated using API Keys. API Keys add an additional layer of security to your account. The provided API Keys are namely, API Key and Secret Key (also defined as transaction key).

The API Key can be used for regular non-sensitive endpoints, for instance, create user, while the Secret Key is used along with the API Key when performing sensitive operations.

{% hint style="danger" %}
**Highly Important Note!** Your API keys carry many privileges, so be sure to keep them secure! Do not share your secret (transaction) key in publicly accessible areas such as GitHub, client-side code, and so forth.
{% endhint %}

Accordingly, you need to provide your account's API Key and (in some cases) Secret Key as well in the header with every request.&#x20;

{% hint style="warning" %}
**Note!** API requests executed without authentication will fail.
{% endhint %}

Below is an example of the authentication through API Key header.

```bash
curl --request POST \
  --url 'https://api.gameball.co/api/v3.0/integrations/event' \
  --header 'APIKey: ue7eh32eiwlsncoko08u8b'

```

Also, below is an example of the authentication using both API Key and Secret Key.

```bash
curl --request POST \
  --url 'https://api.gameball.co/api/v3.0/integrations/transaction/cashback' \
  --header 'APIKey: ue7eh32eiwlsncoko08u8b'
  --header 'SecretKey: kz7eh32eiwldlowbo08u5p'
```


# API Reference

Learn more about our available endpoints at Referd needed during integration.

{% hint style="info" %}
The API base URL is below with v3.0 as our current version.

`https://api.gameball.co/api/{version}`
{% endhint %}

The REST API is organized around the following endpoints:

| API Area                                                                         | Resource Area               | Description                                                                                                       |
| -------------------------------------------------------------------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| [<mark style="color:blue;">**User**</mark>](/api-reference/api-reference/player) | /integrations/player        | The player API is responsible for creating new users at **Referd** as well as updating users' data at **Referd**. |
| [**Event**](/api-reference/api-reference/event)                                  | /integrations/event         | The event API is used to submit user events to **Referd**.                                                        |
| [**Notifications**](/api-reference/api-reference/notifications)                  | /integrations/notifications | The Notifications API can be used to list the user's notifications and also to update its status once read.       |

Next, check each section to learn more about how to use each API area.


# User

The User API can be used to create, update and display users' information on Referd. Users are uniquely identified by playerUniqueId.

## Available Endpoints

<table data-header-hidden><thead><tr><th width="116.33333333333331">Type</th><th width="266">Description</th><th>Endpoint</th></tr></thead><tbody><tr><td>Type</td><td>Description</td><td>Endpoint</td></tr><tr><td><strong>POST</strong></td><td><a href="#post-create-user"><strong>Create User</strong></a></td><td>/integrations/player</td></tr><tr><td><strong>GET</strong></td><td><a href="#get-retrieve-user"><strong>Retrieve User</strong></a></td><td>/integrations/player/{playerUnqiueId}</td></tr><tr><td><strong>DELETE</strong></td><td><a href="#delete-delete-user"><strong>Delete User</strong></a></td><td>/integrations/player/{playerUnqiueId}</td></tr><tr><td><strong>GET</strong></td><td><a href="#get-users-coupons"><strong>User's Coupons</strong></a></td><td>/integrations/transactions/{playerUniqueId}/coupon</td></tr><tr><td><strong>GET</strong></td><td><a href="#get-users-referrals"><strong>Get User's Referrals</strong></a></td><td>/integrations/players/{playerUniqueId}/referrals</td></tr></tbody></table>

## POST - Create User

```http
https://api.gameball.co/api/v3.0/integrations/player
```

The API call is used to create or update a user in **Referd** with the provided attributes.

### Request

#### Header

| Attribute | Type       | **Required** | **Description** |
| --------- | ---------- | ------------ | --------------- |
| `APIKey`  | **string** | Yes          | Client API key  |

#### Body

| Attribute          | Type       | Required | Description                                                                                                                                                                                                               |
| ------------------ | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `playerUniqueId`   | **string** | Yes      | <p>Unique identifier for the user in your database.</p><p>Could be database ID, random string, email or anything that uniquely identifies the user.</p>                                                                   |
| `playerAttributes` | **object** | No       | <p>An <a href="#playerattributes-object"><strong>object</strong></a> with set of properties that you want to set for the user.<br>This object also includes a <code>custom</code>object inside for custom attributes.</p> |
| `deviceToken`      | **string** | No       | <p>The FCM token (Firebase Cloud Messaging) needed for sending mobile push notifications.<br>(Used only in case of mobile app)</p>                                                                                        |
| `osType`           | **string** | No\*     | <p>OS Type according to the mobile device used (if any).<br><strong>Note:</strong> Required in case <strong><code>deviceToken</code></strong> is sent in the payload (e.g. "android", "ios")</p>                          |

#### `playerAttributes` Object

<table data-header-hidden><thead><tr><th>Parameter</th><th width="192.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>displayName</code></td><td><strong>string</strong></td><td>User's display name.</td></tr><tr><td><code>firstName</code></td><td><strong>string</strong></td><td>User's first name.</td></tr><tr><td><code>lastName</code></td><td><strong>string</strong></td><td>User's last name.</td></tr><tr><td><code>mobile</code></td><td><strong>string</strong></td><td>User's mobile number.</td></tr><tr><td><code>gender</code></td><td><strong>string</strong></td><td>User's gender. Example: M or F, Male or Female.</td></tr><tr><td><code>email</code></td><td><strong>string</strong></td><td>User's email.</td></tr><tr><td><code>dateOfBirth</code></td><td><strong>string</strong></td><td><p>User's date of birth.</p><p><strong>Example:</strong> <code>"1980-09-19T00:00:00.000Z"</code></p></td></tr><tr><td><code>joinDate</code></td><td><strong>string</strong></td><td><p>User's join date at your system.</p><p><strong>Example:</strong> <code>"2019-09-19T21:06:29.158Z"</code></p></td></tr><tr><td><code>tags</code></td><td><strong>string</strong></td><td><p>Comma separated string of tags to be attached to the user.</p><p><strong>Example:</strong> <code>"VIP,Platinum"</code></p></td></tr><tr><td><code>country</code></td><td><strong>string</strong></td><td>Country of the user.</td></tr><tr><td><code>city</code></td><td><strong>string</strong></td><td>City of the user.</td></tr><tr><td><code>zip</code></td><td><strong>string</strong></td><td>ZIP of the user.</td></tr><tr><td><code>totalSpent</code></td><td><strong>float</strong></td><td>Total amount spent by user.</td></tr><tr><td><code>totalOrders</code></td><td><strong>int</strong></td><td>Total orders by user.</td></tr><tr><td><code>lastOrderDate</code></td><td><strong>date</strong></td><td>Last order date.</td></tr><tr><td><code>avgOrderAmount</code></td><td><strong>float</strong></td><td>Average order amount.</td></tr><tr><td><code>custom</code></td><td><strong>object</strong></td><td><p>Key value pairs of any extra player attributes.</p><p><code>{"class" : "E2022", "weight" : 78}</code></p></td></tr></tbody></table>

{% hint style="info" %}
To ensure that a referral is properly counted, it is a must that the newly created user includes the same **`email`**&#x6F;r **`mobile`**&#x69;n the **`playerAttributes`**(specified in the request body) same as provided during the referral landing page submission.
{% endhint %}

```javascript
{
   "playerUniqueId":"player123",
   "playerAttributes":{
      "displayName":"Jon Snow",
      "firstName": "Jon",
      "lastName": "Snow",
      "mobile": "+1234567",
      "email":"jon.snow@example.com",
      "gender":"M",
      "dateOfBirth":"1980-09-19T00:00:00.000Z",
      "joinDate":"2019-09-19T21:06:29.158Z",
       "country": "Egypt",
        "city": "Cairo",
        "zip": "18754",
      "tags": "VIP,Platinum",
      "custom":{
          "location":"Miami",
          "graduationDate":"2018-07-04T21:06:29.158Z",
          "isMarried":false
      }
    },
    "levelOrder": null
  }
```

### Response

| Parameter        | Type       | Description                                   |
| ---------------- | ---------- | --------------------------------------------- |
| `playerUniqueId` | **string** | Unique identifier for the user at **Referd.** |
| `gameballId`     | **string** | User's ID at **Referd**.                      |
| `referralLink`   | **string** | Referral URL.                                 |

**Sample Response**

```javascript
{
    "playerUniqueId": "player123",
    "gameballId": 160281869,
    "referralCode": "QQAF9B02734oKn",
    "referralLink": "https://invite.myrfrl.link/aa8d2507"
}
```

### Usage Examples

#### Example One

This example creates a new user at Referd, using `playerUniqueId`, `playerAttributes` with `custom` attributes.

{% tabs %}
{% tab title="cURL" %}

```javascript
curl -X POST -H 'apiKey: 807b041b7d35425988e354e1f6bce186' -d '{
  "playerUniqueId":"player123",
  "playerAttributes":{
      "displayName":"Jon Snow",
      "firstName": "Jon",
      "lastName": "Snow",
      "mobile": "+1234567",
      "email":"jon.snow@example.com",
      "gender":"M",
      "dateOfBirth":"1980-09-19T00:00:00.000Z",
      "joinDate":"2019-09-19T21:06:29.158Z",
      "country": "Egypt",
        "city": "Cairo",
        "zip": "18754",
      "custom":{
         "location":"Miami",
         "graduationDate":"2018-07-04T21:06:29.158Z",
         "isMarried":false
      }
   }

  }' -v -i 'https://api.gameball.co/api/v3.0/integrations/player'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Player.initialize_player({
   playerUniqueId:"player123",
   mobile: "+1234567",
   email: "jon.snow@example.com",
   "playerAttributes":{
      displayName:"Jon Snow",
      firstName: "Jon",
      lastName: "Snow",
      mobile: "+1234567",
      email:"jon.snow@example.com",
      gender:"M",
      dateOfBirth:DateTime.iso8601("1980-09-19T00:00:00.000Z"),
      joinDate:DateTime.iso8601("2019-09-19T21:06:29.158Z"),
      country: "Egypt",
        city: "Cairo",
        zip: "18754",
      tags: "VIP,Platinum",
    	custom:{
           location:"Miami",
           graduationDate:"2018-07-04T21:06:29.158Z",
           isMarried:false
        }
    }
  })
```

{% endtab %}

{% tab title="PHP" %}

```php
$playerAttributes = new \Gameball\Models\PlayerAttributes();
$playerAttributes->displayName = "Jon Snow";
$playerAttributes->firstName = 'Jon';
$playerAttributes->lastName = 'snow';
$playerAttributes->gender = 'M';
$playerAttributes->email = 'jon.snow@example.com';
$playerAttributes->dateOfBirth = '1978-01-11T00:00:00.000Z';
$playerAttributes->joinDate = '2021-09-19T21:06:29.158Z';
$playerAttributes->country= 'Egypt';
$playerAttributes->city= 'Cairo';
$playerAttributes->zip= '18754';
$playerAttributes->addCustomAttribute('isMarried' , true);
$playerAttributes->addCustomAttribute('location' , 'Miami');
$playerAttributes->addCustomAttribute('graduationDate' , '2018-07-04T21:06:29.158Z');

$playerRequest = \Gameball\Models\PlayerRequest::factory(
        "player123",
        null, // Mobile (not null according to your channel merging config)
        null, // Email (not null according to your channel merging config)
        $playerAttributes
);

$playerResponse = $gameball->player->initializePlayer($playerRequest);
```

{% endtab %}

{% tab title="Python" %}

```python
import gameball
gameball.api_key = "API_KEY"
gameball.transaction_key = "TRANSACTION_KEY"

# Initialize Player
player_request = gameball.playerObject("player123", 
    player_attributes = gameball.playerAttributes(
        "Jon Snow",
        "Jon",
        "Snow",
        "+1234567",
        "jon.snow@example.com",
        "M",
        "1980-09-19T00:00:00.000Z",
        "2019-09-19T21:06:29.158Z",
        "Egypt",
        "Cairo",
        "18754",
        tags="VIP,Platinum",
        custom={
            'location':"Miami",
            'graduationDate':"2018-07-04T21:06:29.158Z",
            'isMarried':False
        }
    )
)
player_response = gameball.initialize_player(player_request)
```

{% endtab %}

{% tab title=".NET" %}

```aspnet
using Gameball;
var Gameball = new Gameball.Gameball(apiKey: "API_KEY", secretKey: "SECRET_KEY");

var request = new PlayerRequest()
	{
		PlayerUniqueId = "player123",
		PlayerAttributes = new PlayerAttributes()
		{
			DisplayName = "Jon Snow",
			FirstName = "Jon",
			LastName = "Snow",
			Email = "jon.snow@example.com",
			Gender = "M",
			Mobile = "+1234567",
			DateOfBirth = new DateTime(1980, 9, 19),
			JoinDate = new DateTime(2019, 9, 19, 21, 6, 29, 158),
			Country:"Egypt",
			City:"Cairo",
			Zip:"18754"
		}
	};
var response = Gameball.InitializePlayer(request);
```

{% endtab %}
{% endtabs %}

#### Example Two

To complete the referral process, the new user must visit the referral link provided by the referrer and input their mobile phone number or email based on the client's specified configuration. Subsequently, a request should be sent to **Referd** to register this user. It is crucial that the new user re-enters the same **`email`**&#x6F;r **`mobile`**, which was initially provided on the landing page, within the **`playerAttributes`** sent in the create user request.

In the following example, a request is sent to **Referd** to create a user with the email `'tyrion@example.com'` who was successfully referred by another user. The **email** is included within the **`playerAttributes`**. To ensure the referral is counted, the user must input the same email during the referred player's registration on the landing page.

{% tabs %}
{% tab title="cURL" %}

```typescript
curl -X POST -H 'apiKey: 807b041b7d35425988e354e1f6bce186' -d '{
   "playerUniqueId":"player456",
   "playerAttributes":{
      "displayName":" Tyrion Lannister",
      "firstName":"Tyrion",
      "lastName":"Lannister",
      "email":"tyrion@example.com",
      "gender":"M",
      "dateOfBirth":"1978-01-11T00:00:00.000Z",
      "joinDate":"2019-09-19T21:06:29.158Z",
      "custom":{
         "location":"Miami",
         "graduationDate":"2018-07-04T21:06:29.158Z",
         "isMarried":false
  	}
   }
  }' -v -i 'https://api.gameball.co/api/v3.0/integrations/player'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Player.initialize_player({
   playerUniqueId:"player456",
   playerAttributes:{
      displayName:" Tyrion Lannister",
      firstName:"Tyrion",
      lastName:"Lannister",
      email:"tyrion@example.com",
      gender:"M",
      dateOfBirth:DateTime.iso8601("1978-01-11T00:00:00.000Z"),
      joinDate:DateTime.iso8601("2019-09-19T21:06:29.158Z"),
      custom:{
         location:"Miami",
         graduationDate:"2018-07-04T21:06:29.158Z",
         isMarried:false
  	}
   })
```

{% endtab %}

{% tab title="PHP" %}

```php
$playerAttributes = new \Gameball\Models\PlayerAttributes();
$playerAttributes->displayName = "Tyrion Lannister";
$playerAttributes->firstName = 'Tyrion';
$playerAttributes->lastName = 'Lannister';
$playerAttributes->gender = 'M';
$playerAttributes->email = 'tyrion@example.com';
$playerAttributes->dateOfBirth = '1978-01-11T00:00:00.000Z';
$playerAttributes->joinDate = '2021-09-19T21:06:29.158Z';
$playerAttributes->addCustomAttribute('isMarried' , true);
$playerAttributes->addCustomAttribute('location' , 'Miami');
$playerAttributes->addCustomAttribute('graduationDate' , '2018-07-04T21:06:29.158Z');

$playerRequest = \Gameball\Models\PlayerRequest::factory(
        "player456",
        null, // Mobile (not null according to your channel merging config)
        null, // Email (not null according to your channel merging config)
        $playerAttributes,
        "CODE11" // ReferrerCode
);

$playerResponse = $gameball->player->initializePlayer($playerRequest);
```

{% endtab %}

{% tab title="Python" %}

```python
# Initialize Player
player_request = gameball.playerObject("player123", 
    player_attributes = gameball.playerAttributes(
        "Jon Snow",
        "Jon",
        "Snow",
        "+1234567",
        "jon.snow@example.com",
        "M",
        "1980-09-19T00:00:00.000Z",
        "2019-09-19T21:06:29.158Z",
        tags="VIP,Platinum",
        custom={
            'location':"Miami",
            'graduationDate':"2018-07-04T21:06:29.158Z",
            'isMarried':False
        }    
    ),
    referrer_code="CODE11"
)
player_response = gameball.initialize_player(player_request)
```

{% endtab %}

{% tab title=".NET" %}

```
var request = new PlayerRequest()
	{
		PlayerUniqueId = "player123",
		PlayerAttributes = new PlayerAttributes()
		{
			DisplayName = "Jon Snow",
			FirstName = "Jon",
			LastName = "Snow",
			Email = "jon.snow@example.com",
			Gender = "M",
			Mobile = "+1234567",
			DateOfBirth = new DateTime(1980, 9, 19),
			JoinDate = new DateTime(2019, 9, 19, 21, 6, 29, 158)
		},
		ReferrerCode = "CODE11"
	};
var response = Gameball.InitializePlayer(request);
```

{% endtab %}
{% endtabs %}

**Note***:* All attributes inside the **`playerAttributes`** object are optional, if the values of any attributes shown below are unavailable, remove the attribute from the **`playerAttributes`** object.

## GET - Retrieve User

This API call is used to retrieve user's information.

```http
https://api.gameball.co/api/v3.0/integrations/player/{playerUnqiueId}
```

### Request

#### Header

| Attribute | Type       | Required | Description                                                                                                                                                                                                                                                                              |
| --------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `APIKey`  | **string** | Yes      | Client APIKey                                                                                                                                                                                                                                                                            |
| `Lang`    | **string** | No       | <p>Language to get the user's info with. If not provided, the response would be in default language.</p><p><strong>Note:</strong> The language provided should be as per configured languages in your account.</p><p><strong>Example:</strong> <code>"en"</code>, <code>"fr"</code>.</p> |

#### Path Parameters

<table data-header-hidden><thead><tr><th width="218">Parameter</th><th width="150">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td>Yes</td><td>Unique identifier for the user at <strong>Referd.</strong></td></tr></tbody></table>

### Response

<table data-header-hidden><thead><tr><th width="242.33333333333331">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td>Unique identifier for the user at <strong>Referd.</strong></td></tr><tr><td><code>playerAttributes</code></td><td><strong>object</strong></td><td>An <a href="#playerattributes-object"><strong>object</strong></a> with set of user properties defined previously at the user's creation.</td></tr><tr><td><code>referralLink</code></td><td><strong>string</strong></td><td>Referral URL.</td></tr></tbody></table>

#### Sample Response

```javascript
{
   "playerUniqueId":"player456",
   "playerAttributes":{
      "displayName":"Jon Snow",
      "email":"jon.snow@example.com",
      "mobileNumber":"0123456789",
      "gender":"M",
      "joinDate":"09/19/2019 21:06:29",
      "tags":[
         "VIP",
         "Elite"
      ],
      "custom":{
         "location":"Miami",
         "graduationDate":"2018-07-04T21:06:29.158Z",
         "isMarried":false
      }
   },
   "referralCode":"CODE12",
   "referralLink":"https://gameofthrones.myshopify.com/account/register?ReferralCode=CODE12",
   "dynamicReferralLink":"https://gameofthrones.myshopify.com/account/register?ReferralCode=CODE12"
}
```

### Usage Example

The example shown is a request sent to **Referd** to get a user info with **`playerUniqueId`“player456”.**

{% tabs %}
{% tab title="cURL" %}

```javascript
curl -X GET -H 'apiKey: 807b041b7d35425988e354e1f6bce186'
 -v -i 'https://api.gameball.co/api/v3.0/integrations/player/player456'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Player.get_player_info("player456")
```

{% endtab %}

{% tab title="PHP" %}

```php
$playerResponse = $gameball->player->getPlayerInfo("player456");
```

{% endtab %}

{% tab title="Python" %}

```python
player_response = gameball.get_player_info("player456")
```

{% endtab %}

{% tab title=".NET" %}

```aspnet
var response = Gameball.GetPlayerInfo(“player456”);
```

{% endtab %}
{% endtabs %}

## DELETE - Delete User

This API is used to delete a user along with his attributes, rewards and actions.

```html
https://api.gameball.co/api/v3.0/integrations/player/{playerUnqiueId}
```

### Request

#### Header

<table data-header-hidden><thead><tr><th>Attribute</th><th width="186">Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>APIKey</code></td><td><strong>string</strong></td><td>Yes</td><td>Client API key</td></tr><tr><td><code>secretKey</code></td><td><strong>string</strong></td><td>Yes</td><td>Client Secret Key</td></tr></tbody></table>

#### Path Parameters

<table data-header-hidden><thead><tr><th width="237">Attribute</th><th width="122">Type</th><th width="130">Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td>Yes</td><td>Unique identifier for the user at <strong>Referd</strong>.</td></tr></tbody></table>

### Usage Example

{% tabs %}
{% tab title="cURL" %}

```javascript
curl -X DELETE -H 'apiKey: 807b041b7d35425988e354e1f6bce186' \
       -H 'secretKey: klmb041b7d354259l3u4ft35e1q2r3703' -d 
-v -i 'https://api.gameball.co/api/v3.0/integrations/player/player456'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Player.delete("player456")
```

{% endtab %}

{% tab title="PHP" %}

```php
$playerResponse = $gameball->player->delete("player456");
```

{% endtab %}

{% tab title="Python" %}

```python
player_response = gameball.deletePlayer("player456")
```

{% endtab %}

{% tab title=".NET" %}

```aspnet
var response = Gameball.DeletePlayer(“player456”);
```

{% endtab %}
{% endtabs %}

## GET - User's Coupons

This endpoint is used to get the Coupons of a specific user.

```http
https://api.gameball.co/api/v3.0/integrations/transactions/{playerUniqueId}/coupon
```

### Request

#### Header

<table data-header-hidden><thead><tr><th width="192">Attribute</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>APIKey</code></td><td><strong>string</strong></td><td>Yes</td><td>Client API key</td></tr><tr><td><code>secretKey</code></td><td><strong>string</strong></td><td>Yes</td><td>Client Secret Key</td></tr></tbody></table>

#### Path Parameters

<table data-header-hidden><thead><tr><th width="220">Attribute</th><th width="117">Type</th><th width="123">Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td>Yes</td><td>Unique identifier for the user at <strong>Referd</strong>.</td></tr></tbody></table>

### Response

<table data-header-hidden><thead><tr><th width="232">Attribute</th><th width="126.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Description</td></tr><tr><td><code>coupons</code></td><td><strong>array</strong></td><td>An array of <strong>Coupon</strong> <a href="#coupon-object"><strong>objects</strong></a>.</td></tr></tbody></table>

#### `coupon` Object

<table><thead><tr><th width="247">Parameter</th><th width="143">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>code</code></td><td><strong>string</strong></td><td>Coupon Code.</td></tr><tr><td><code>isUsed</code></td><td><strong>boolean</strong></td><td>A <strong>boolean</strong> indicating if the coupon was used by the specified user.</td></tr><tr><td><code>value</code></td><td><strong>double</strong></td><td>Value of coupon. ( in the case of percentage discount this would be the value in percentage of the coupon)</td></tr><tr><td><code>currency</code></td><td><strong>string</strong></td><td>Currency of the coupon.</td></tr><tr><td><code>creationDate</code></td><td><strong>DateTime</strong></td><td>The date that the coupon was created on.</td></tr><tr><td><code>couponType</code></td><td><strong>string</strong></td><td><p>Indicates the type of the coupon, the value of the string can be one of the following:</p><ul><li><strong><code>free_shipping</code></strong></li><li><strong><code>percentage_discount</code></strong></li><li><strong><code>fixed_discount</code></strong></li><li><strong><code>free_product</code></strong></li><li><strong><code>fixed_rate_discount</code></strong></li><li><strong><code>custom</code></strong></li></ul></td></tr><tr><td><code>product</code></td><td><strong>object</strong></td><td>In the case of <strong><code>free_product</code></strong> coupon, a <code>product</code> <a href="#product-object"><strong>object</strong> </a>indicates the details of the free product.</td></tr><tr><td><code>startAt</code></td><td><strong>DateTime</strong></td><td>Date that the coupon starts at and can be applied.</td></tr><tr><td><code>endAt</code></td><td><strong>DateTime</strong></td><td>Date that the coupon expires at.</td></tr><tr><td><code>isExpired</code></td><td><strong>boolean</strong></td><td>Boolean indicating if the coupon is expired.</td></tr><tr><td><code>collections</code></td><td><strong>array</strong></td><td>An array of <strong>Collection</strong> Objects specifying the collections that the coupon can be applied on.</td></tr><tr><td><code>group</code></td><td><strong>object</strong></td><td>An <a href="#group-object"><strong>object</strong> </a>describing the coupon group which the coupon belongs to.</td></tr><tr><td><code>options</code></td><td><strong>object</strong></td><td>An <a href="#optionsobject"><strong>object</strong> </a>describing the coupon's options.</td></tr></tbody></table>

#### **`product` Object**

<table><thead><tr><th width="257">Parameter</th><th width="106">Type</th><th>Description</th><th data-hidden>Parameter</th></tr></thead><tbody><tr><td><code>productId</code></td><td><strong>integer</strong></td><td>Unique identifier of the product.</td><td><code>productId</code></td></tr><tr><td><code>productName</code></td><td><strong>string</strong></td><td>Name of the product.</td><td><code>productName</code></td></tr><tr><td><code>productDisplayName</code></td><td><strong>array</strong></td><td>An array of display names for the product.</td><td><code>productDisplayNames</code></td></tr><tr><td><code>variantId</code></td><td><strong>integer</strong></td><td>In case the product has variants this is the id of the variant.</td><td><code>variantId</code></td></tr><tr><td><code>variantName</code></td><td><strong>string</strong></td><td>In case the product has variants this is the name of the variant.</td><td><code>variantName</code></td></tr></tbody></table>

**`collection` Object**

<table><thead><tr><th width="257">Type</th><th width="106"></th><th>Description</th><th data-hidden>Parameter</th></tr></thead><tbody><tr><td><code>collectionId</code></td><td><strong>integer</strong></td><td>Unique identifier of the collection.</td><td><code>productId</code></td></tr><tr><td><code>collectionName</code></td><td><strong>string</strong></td><td>Name of the collection.</td><td><code>productName</code></td></tr></tbody></table>

#### **`group` Object**

<table><thead><tr><th width="257">Parameter</th><th width="113">Type</th><th>Description</th><th data-hidden>Parameter</th></tr></thead><tbody><tr><td><code>handle</code></td><td><strong>string</strong></td><td>A unique identifier for the coupon group.</td><td><code>productId</code></td></tr><tr><td><code>title</code></td><td><strong>string</strong></td><td>Title of the coupon group.</td><td><code>productName</code></td></tr><tr><td><code>url</code></td><td><strong>string</strong></td><td>URL of the coupon group.</td><td></td></tr><tr><td><code>iconPath</code></td><td><strong>string</strong></td><td>Icon path of the coupon group.</td><td></td></tr><tr><td><code>description</code></td><td><strong>string</strong></td><td>Description of the coupon group.</td><td></td></tr><tr><td><code>maxPerPlayer</code></td><td><strong>integer</strong></td><td>Maximum number of times a user can achieve coupons from this group.</td><td></td></tr><tr><td><code>startDate</code></td><td><strong>DateTime</strong></td><td>Date at which coupons can start to be redeemed from this group.</td><td></td></tr><tr><td><code>expiryDate</code></td><td><strong>DateTime</strong></td><td>Date at which you can no longer redeem coupons from this group.</td><td></td></tr><tr><td><code>isAvailable</code></td><td><strong>boolean</strong></td><td>A <strong>boolean</strong> flag indicating if there are coupon available to be redeemed from this group.</td><td></td></tr><tr><td><code>isValid</code></td><td><strong>boolean</strong></td><td>Flag indicating if the group is valid (Current Date is between start and expiry dates).</td><td></td></tr><tr><td><code>isActive</code></td><td><strong>boolean</strong></td><td>Flag indicating if the group is active or not (Client marked the group as active or not and group’s dates are valid).</td><td></td></tr></tbody></table>

#### `options`Object

<table><thead><tr><th>Parameter</th><th width="136.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>ExpiryAfter</code></td><td><strong>integer</strong></td><td>Number of days until the coupon expires.</td></tr><tr><td><code>UsageLimit</code></td><td><strong>integer</strong></td><td>Maximum number of times a coupon or offer can be used.</td></tr><tr><td><code>Capping</code></td><td><strong>double</strong></td><td>Maximum limit on the total amount of discount that can be applied to an order.</td></tr><tr><td><code>MinOrderValue</code></td><td><strong>double</strong></td><td>The minimum amount a user must spend on an order to qualify for the coupon.</td></tr><tr><td><code>CombinesWith</code></td><td><strong>object</strong></td><td><p>An <strong>object</strong> that that determines whether specific types of discounts can be combined and consists of three <strong>boolean</strong> values:</p><ul><li><code>ShippingDiscounts</code></li><li><code>ProductDiscounts</code></li><li><code>OrderDiscounts</code></li></ul></td></tr><tr><td><code>ProductId</code></td><td><strong>string</strong></td><td>Unique identifier of the product.</td></tr><tr><td><code>ProductName</code></td><td><strong>string</strong></td><td>Name of the product.</td></tr><tr><td><code>VariantId</code></td><td><strong>string</strong></td><td>In case the product has variants this is the id of the variant.</td></tr><tr><td><code>VariantName</code></td><td><strong>string</strong></td><td>In case the product has variants this is the name of the variant.</td></tr><tr><td><code>ProductDisplayName</code></td><td><strong>string</strong></td><td>Display name for the product.</td></tr><tr><td><code>HasCollections</code></td><td><strong>boolean</strong></td><td>Indicates if it has collections.</td></tr><tr><td><code>Platforms</code></td><td><strong>array</strong></td><td>List of platforms.</td></tr></tbody></table>

#### Sample Response

```json
[
    {
        "code": "R7KVWwoT4c",
        "isUsed": false,
        "value": 30.0,
        "currency": "EGP",
        "creationDate": "2022-09-21T11:08:42.298758",
        "couponType": "custom",
        "product": {
            "productId": null,
            "productName": null,
            "productDisplayName": null,
            "variantId": null,
            "variantName": null
        },
        "startAt": "2021-09-21T11:08:42.298758",
        "endAt": "2023-09-21T11:08:42.298758",
        "isExpired": false,
        "collections": [],
        "group": {
            "handle": "free_macdo",
            "title": "Free MACDO",
            "url": "https://www.mcdonalds.eg/eat/menu/Item/Chicken-MACDO-",
            "iconPath": "https://www.mcdonalds.eg/Cms_Data/Contents/En/Media/images/Menu/large-Image/Chicken-MACDO.png",
            "description": "Coupons in this group give a free macdo and can be rdeemed in all Mcdonalds branches"
        }
    },
    {
        "code": "zFHYySXdiy",
        "isUsed": false,
        "value": 50.0,
        "currency": "EGP",
        "creationDate": "2022-09-21T11:07:22.718595",
        "couponType": "percentage_discount",
        "product": {
            "productId": null,
            "productName": null,
            "productDisplayName": null,
            "variantId": null,
            "variantName": null
        },
        "startAt": null,
        "endAt": null,
        "isExpired": false,
        "collections": [],
        "group": null
    },
    
]
```

### Usage Example

{% tabs %}
{% tab title="cURL" %}

```javascript
curl -X GET -H 'apiKey: 807b041b7d35425988e354e1f6bce186' \
       -H 'secretKey: klmb041b7d354259l3u4ft35e1q2r3703' -d 
-v -i 'https://api.gameball.co/api/v3.0/integrations/player/player456/coupon'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Player.get_player_coupon("player456")
```

{% endtab %}

{% tab title="PHP" %}

```php
$playerResponse = $gameball->player->getPlayerCoupon("player456");
```

{% endtab %}

{% tab title="Python" %}

```python
player_response = gameball.get_player_coupon("player456")
```

{% endtab %}

{% tab title=".NET" %}

```aspnet
var response = Gameball.GetPlayerCoupon(“player456”);
```

{% endtab %}
{% endtabs %}

## GET - User's Referrals

```http
https://api.gameball.co/api/v3.0/integrations/players/{playerUniqueId}/referrals
```

This endpoint is used to get the Referrals of a specific user with the status of the referral for each referred user, whether the referral has been completed (**`active`**) or pending the needed referral action (**`pending`**) as per your referral configurations.

### Request

#### Header

<table data-header-hidden><thead><tr><th width="192">Attribute</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>APIKey</code></td><td><strong>string</strong></td><td>Yes</td><td>Client API key</td></tr></tbody></table>

#### Path Parameters

<table data-header-hidden><thead><tr><th width="220">Attribute</th><th width="117">Type</th><th width="123">Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td>Yes</td><td>Unique identifier for the user at <strong>Referd</strong>.</td></tr></tbody></table>

#### Query Parameters

<table data-header-hidden><thead><tr><th width="220">Attribute</th><th width="117">Type</th><th width="123">Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>page</code></td><td><strong>integer</strong></td><td>No</td><td>Index of required page. (e.g. 1, 2, ..)<br><strong>Default:</strong> 1</td></tr><tr><td><code>limit</code></td><td><strong>integer</strong></td><td>No</td><td>limit of results per page. (e.g. 10, 20, ..)<br><strong>Default:</strong> 50<br><strong>Max:</strong> 200</td></tr></tbody></table>

### Response

<table data-header-hidden><thead><tr><th width="232">Attribute</th><th width="126.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Description</td></tr><tr><td><code>referredFriends</code></td><td><strong>array</strong></td><td>An array of <strong>referredFriend</strong> <a href="#referredfriend-object"><strong>objects</strong></a>.</td></tr><tr><td><code>count</code></td><td><strong>integer</strong></td><td>Count of users in the in current page.</td></tr><tr><td><code>total</code></td><td><strong>integer</strong></td><td>Total number of users referred by the given user.</td></tr><tr><td><code>totalPending</code></td><td><strong>integer</strong></td><td>Total <strong><code>"pending"</code></strong> number of users referred by the given user but haven't completed the required referral action (e.g. Placed an order).</td></tr><tr><td><code>totalActive</code></td><td><strong>integer</strong></td><td>Total <strong><code>"active"</code></strong> number of users successfully referred by the given user and have completed the required referral action (e.g. Placed an order).</td></tr></tbody></table>

#### **referredFriend** Object

<table><thead><tr><th width="247">Parameter</th><th width="143">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td>Unique identifier for the user at <strong>Referd</strong>.</td></tr><tr><td><code>displayName</code></td><td><strong>string</strong></td><td>User's display name.</td></tr><tr><td><code>email</code></td><td><strong>string</strong></td><td>User's email.</td></tr><tr><td><code>mobileNumber</code></td><td><strong>string</strong></td><td>User's mobile number.</td></tr><tr><td><code>joinDate</code></td><td><strong>DateTime</strong></td><td>The date at which the user joined the store.</td></tr><tr><td><code>status</code></td><td><strong>string</strong></td><td><p>Indicates the status of the referred user, the value of the string can be one of the following:</p><ul><li><strong><code>active</code></strong></li><li><strong><code>pending</code></strong></li></ul></td></tr></tbody></table>

#### **Sample Response**

```json
{
   "referredFriends":[
      {
         "displayName":"Jon Snow",
         "email":"jon.snow@example.com",
         "mobileNumber":"0123456789",
         "joinDate":"09/19/2019 21:06:29",
         "status":"Pending",
         "playerUniqueId":"123"
      },
      {
         "displayName":"Arya Stark",
         "email":"arya.stark@example.com",
         "mobileNumber":"0111111119",
         "joinDate":"09/19/2018 22:16:25",
         "status":"Active",
         "playerUniqueId":"123"
      }
   ],
   "total":2,
   "count":2,
   "totalPending":1,
   "totalActive":1
}
```

### Usage Example

{% tabs %}
{% tab title="cURL" %}

```javascript
curl -X GET -H 'apiKey: 807b041b7d35425988e354e1f6bce186'
 -v -i 'https://api.gameball.co/api/v3.0/integrations/players/player456/referrals'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Player.get_player_referrals("player456")
```

{% endtab %}

{% tab title="PHP" %}

```php
$playerResponse = $gameball->players->getPlayerReferrals("player456");
```

{% endtab %}

{% tab title="Python" %}

```python
player_response = gameball.get_player_referrals("player456")
```

{% endtab %}

{% tab title=".NET" %}

```aspnet
var response = Gameball.GetPlayerReferrals(“player456”);
```

{% endtab %}
{% endtabs %}


# Event

This API endpoint allows you to track and send your users' events on your platform to Referd.

## Available Endpoints

| Type     | Description                          | Endpoint            |
| -------- | ------------------------------------ | ------------------- |
| **POST** | [**Track Event**](#post-track-event) | /integrations/event |

The event APIs help you record any actions your user performs, along with any properties or metadata that describe the action. For further elaboration on events, check this [article](https://help.gameball.co/en/articles/3468399-understand-your-players-events) in our Help Center.

Each action is known as an event. Each event has a name, like place\_order, and metadata, for example a `place_order` event might have properties like `amount` or `source`. Calling `events` is one of the first steps to getting started with **Referd**.

The event API call accepts a collection of event to help tracking multiple user actions. Event object is described [below](#event-object).

## POST - Track Event

This API call is used to send an event to **Referd** where the received event will be evaluated.

```http
https://api.gameball.co/api/v3.0/integrations/event
```

### Request

#### Header

| Attribute | Type       | Required | Description    |
| --------- | ---------- | -------- | -------------- |
| `APIKey`  | **string** | Yes      | Client API key |

#### Body

| Attribute        | Type       | Required | Description                                                                                                 |
| ---------------- | ---------- | -------- | ----------------------------------------------------------------------------------------------------------- |
| `playerUniqueId` | **string** | Yes      | Unique identifier for the user at **Referd**                                                                |
| `events`         | **object** | Yes      | Collection of user [**events**](broken://pages/9GPfdFoiZqbOOfaoiWWI#event-object) to be sent to **Referd**. |

{% hint style="info" %}
In case the user doesn't exist on **Referd** before sending the **Event** API call, the user will be created automatically on **Referd**.
{% endhint %}

#### `event` Object

The **Event** object is how you record any actions your users perform, along with any metadata that describes the action. For further elaboration on events check [Understand your users' events](https://help.tryreferd.com/en/articles/8668415-create-and-send-events-to-referd).

Metadata are extra pieces of information you can tie to events you track. They can be none or anything that will be useful while analyzing the events later. We recommend sending properties whenever possible because they give you a more complete picture of what your users are doing. Every Metadata can be a number, a string or an array of values.

#### Event and Metadata example:

| Event Name | Key                | Example Value           |
| ---------- | ------------------ | ----------------------- |
| `buy`      | `product_id`       | "a123456"               |
|            | `price`            | 30                      |
|            | `product_category` | "fashion"               |
|            | `product_tags`     | "men & new\_collection" |

#### Sample Event Object

```typescript
"buy": {
  "product_id": "a123456",
  "price": 30,
  "product_category": "fashion"
  "product_tags": ["men", "new_collection"]
}
```

#### Sample Request Body

```javascript
{
  "events": {
    "place_order": {    // Events with metadata
      "total_amount": "100",
      "category": [
          "electronics",
          "cosmetics"
      ]
    },
    "review": { } // For events with no metadata
  },
  "playerUniqueId": "player123"
}
```

### Usage Examples

#### **Example One**

The below represents events done by a user with `playerUniqueId` “player123” on two events:

1. Event “place\_order”: (An event that has 2 metadata keys)
   1. `total_amount`: Total money paid by the player
   2. `category`: Type of products being bought by player
2. Event `review`: (An event with no metadata)

{% tabs %}
{% tab title="cURL" %}

```typescript
curl --location --request POST 'https://api.gameball.co/api/v3.0/integrations/event' \
--header 'apiKey: 807b041b7d35425988e354e1f6bce186' \
--header 'Content-Type: application/json' \
--data-raw '{
  "events": {
    "place_order": {    // Events with metadata
      "total_amount": "100",
      "category": [
          "electronics",
          "cosmetics"
      ]
    },
    "review": { } // For events with no metadata
  },
  "playerUniqueId": "player123"
  }'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Event.send_event({
	events:{
		place_order:{
			total_amount:"100",
			category:[
				"electronics",
				"cosmetics"
			]
		},
		review:{}
	},
	playerUniqueId:"player123"
})
```

{% endtab %}

{% tab title="PHP" %}

```php
$eventRequest = \Gameball\Models\EventRequest::factory("player123");
$eventRequest->addEvent('place_order');
$eventRequest->addMetaData('place_order','total_amount','100');
$eventRequest->addMetaData('place_order','category',array("electronics","cosmetics"));
$eventRequest->addEvent('review');
$response = $gameball->event->sendEvent($eventRequest);
```

{% endtab %}

{% tab title="Python" %}

```python
event = gameball.eventObject("player123")
event.add_event(
     'place_order',
      {
         "total_amount":"100",
         "category":["electronics","cosmetics"]
      })
event_request = gameball.send_event(event)
```

{% endtab %}

{% tab title=".NET" %}

```
var placeOrderEvent = new Event(){
	Name="place_order"
};

placeOrderEvent.AddMetadata("total_amount", 100);
placeOrderEvent.AddMetadata("category", new string[]{"electronics","cosmetics"});

var reviewEvent = new Event(){
	Name="review"
};
var eventRequest = new EventRequest(){
	PlayerUniqueId="player123"	
};

eventRequest.AddEvent(placeOrderEvent);
eventRequest.AddEvent(reviewEvent);

var response = Gameball.SendEvent(eventRequest);
```

{% endtab %}
{% endtabs %}

#### **Example Two**

The below example shows how the event endpoint could be used to trigger an event to reserve 2 rooms:

1. Event `reserve`: An event with one metadata key
   1. `rooms`: Types of rooms booked by player, 1 for standard and 2 for deluxe rooms

{% tabs %}
{% tab title="cURL" %}

```typescript
curl -X POST -H 'apiKey: 807b041b7d35425988e354e1f6bce186' -d '{
    "events": 
        {
            "reserve": {
                "rooms": 2
            }
        },
    "playerUniqueId": "player123"
}' -v -i 'https://api.gameball.co/api/v3.0/integrations/event'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Event.send_event({
	events:{
		reserve:{
			rooms:2
		}
	},
	playerUniqueId:" player123"
	
})
```

{% endtab %}

{% tab title="PHP" %}

```php
$eventRequest = \Gameball\Models\EventRequest::factory("player123");
$eventRequest->addEvent('reserve');
$eventRequest->addMetaData('reserve','rooms','2');
$response = $gameball->event->sendEvent($eventRequest);
```

{% endtab %}

{% tab title="Python" %}

```python
event = gameball.eventObject("player123")
event.add_event(
     'reserve',
      {
         "rooms":2
      })
event_request = gameball.send_event(event)
```

{% endtab %}

{% tab title=".NET" %}

```
var reserveEvent = new Event(){
	Name="reserve"
};

reserveEvent.AddMetadata("rooms", 2);

var eventRequest = new EventRequest(){
	PlayerUniqueId="player123"	
};

eventRequest.AddEvent(reserveEvent);

var response = Gameball.SendEvent(eventRequest);
```

{% endtab %}
{% endtabs %}

### Remarks

* API consumer can provide any number of events given that each event name is not replicated
* API consumer can provide from 0 to all event metadata keys, however the keys must not be replicated. If the consumer has multiple values for a single metadata key it should be provide as an array of strings as follows “key”: \[“value1”, “value2”, “value3”, …]


# Notifications

The Notifications API can be used to list the user's notifications and also to update its status once read.

## Available Endpoints

| Type    | Description                                                          | Endpoint                                     |
| ------- | -------------------------------------------------------------------- | -------------------------------------------- |
| **GET** | [**User Notifications**](#get-player-notifications)                  | /integrations/notifications/{playerUnqiueId} |
| **PUT** | [**Mark Notification(s) as Read**](#put-mark-notification-s-as-read) | /integrations/notifications                  |

## GET - User Notifications

```http
https://api.gameball.co/api/v3.0/integrations/notifications/{playerUnqiueId}/
```

This API is used to to retrieve a specific user's list of notifications in **Referd**.

### Request

#### Header

| Attribute | Type       | Required | Description    |
| --------- | ---------- | -------- | -------------- |
| `APIKey`  | **string** | Yes      | Client API key |

#### Path Parameters

<table data-header-hidden><thead><tr><th>Attribute</th><th width="150">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td>Attribute</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>playerUniqueId</code></td><td><strong>string</strong></td><td>Yes</td><td>Unique identifier for the user at <strong>Referd</strong></td></tr></tbody></table>

#### Query Parameters

| Attribute | Type        | Required | Description                                                                                                                                                                                                                                                                            |
| --------- | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isRead`  | **boolean** | No       | Read status filter. This could be used in case you need to filter notifications based on their read status.                                                                                                                                                                            |
| `lang`    | **string**  | No       | <p>Language filter. This could be used to specify the language needed to display the notification in.<br><strong>Note:</strong> The language provided should be as per configured languages in your account.</p><p><strong>Example:</strong> <code>"en"</code>, <code>"fr"</code>.</p> |
| `page`    | **integer** | No       | Result page number. Starts from 1. **Default** is 1                                                                                                                                                                                                                                    |
| `limit`   | **integer** | No       | Result page size. **Default** is 50 notifications and **Max** is 200                                                                                                                                                                                                                   |

### Response

Returns an array of notification **objects** described as follows:

| Attribute       | Type        | Description                                                                                                                                                                                 |
| --------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `notifications` | **array**   | List of returned notification [**objects**](#notification-object).                                                                                                                          |
| `count`         | **integer** | Currently displayed **notifications** list count                                                                                                                                            |
| `total`         | **integer** | <p>Total number of <strong>notifications</strong> available matching the applied filters</p><p><strong>Example:</strong></p><p><code>"count": 50</code></p><p><code>"total": 200</code></p> |

#### `notification` Object

| Attribute        | Type        | Description                                                                                                                                                                                                                                                                                                                                         |
| ---------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `notificationId` | **string**  | Unique Identifier for a notification                                                                                                                                                                                                                                                                                                                |
| `title`          | **string**  | Notification Title                                                                                                                                                                                                                                                                                                                                  |
| `body`           | **string**  | Notification Body                                                                                                                                                                                                                                                                                                                                   |
| `isRead`         | **boolean** | Indicates whether the notification is read or not.                                                                                                                                                                                                                                                                                                  |
| `createdAt`      | **string**  | <p>Notification's creation date, as an ISO8601 timestamp.</p><p><strong>Example:</strong> <code>"2019-09-21T16:53:28.190Z"</code></p>                                                                                                                                                                                                               |
| `lang`           | **string**  | <p>The language in which the notification is displayed.<br>In case the <code>lang</code> is not provided in the request, default <code>lang</code> is returned.</p><p><strong>Note:</strong> The language provided should be as per configured languages in your account.</p><p><strong>Example:</strong> <code>"en"</code>, <code>"fr"</code>.</p> |
| `icon`           | **string**  | Notification's icon URL.                                                                                                                                                                                                                                                                                                                            |

#### Sample Response

```javascript
{
    "notifications": [
        {
            "notificationId" : "123",
            "title": "New level!",
            "body": "Keep it up! You are now on Bronze ",
            "isRead": true,
            "createdAt": "2021-05-12T00:08:09.646174",
            "lang": "en",
            "icon": "https://cdn.gameball.co/uploads/client776/ad8b2587-959f-48fd-ab58-a643323652begb-icon-level-13.png"
        },
        {
            "notificationId" : "124",
            "title": "Congratulations! ",
            "body": "Welcome earned. Enjoy your rewards and keep earning more!",
            "isRead": true,
            "createdAt": "2021-05-12T00:08:09.623367",
            "lang": "en",
            "icon": "https://cdn.gameball.co/uploads/client776/bcc5d9be-3861-415f-bdf9-34b4064a1320Group 2144.png"
        }
    ],
   "count": 50,
   "total": 200
}
```

### Usage Example

{% tabs %}
{% tab title="cURL" %}

```typescript
curl -X GET -H 'apiKey: 807b041b7d35425988e354e1f6bce186' -v -i 
 'https://api.gameball.co/api/v3.0/integrations/notifications/player123?lang=en'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
# Example 1
Gameball::Notifications.get_notifications("player123")

# Example 2
Gameball::Notifications.get_notifications("player123",{
	page: 2,
	limit: 10
})
```

{% endtab %}

{% tab title="PHP" %}

```php
$response = $gameball->notification
    ->getPlayerNotifications("player123",false, null, 2, 10);
```

{% endtab %}

{% tab title="Python" %}

```python
notifications = gameball.get_notifications("player123")
```

{% endtab %}

{% tab title=".NET" %}

```aspnet
var response = Gameball.GetPlayerNotifications("player123");
```

{% endtab %}
{% endtabs %}

## PUT - Mark Notification(s) as Read

```http
https://api.gameball.co/api/v3.0/integrations/notifications
```

The API call is used to mark the user's notification(s) as read in **Referd**.

### Request

#### Header

| Attribute | Type       | Required | Description    |
| --------- | ---------- | -------- | -------------- |
| `APIKey`  | **string** | Yes      | Client API key |

#### Body

| Attribute         | Type      | Required | Description                                                                                                                                 |
| ----------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `notificationIds` | **array** | Yes      | <p>An array of IDs of the notifications to be marked as read.</p><p><strong>Example:</strong> <code>\["12334", "14533", "55343"]</code></p> |

#### Sample Body

```javascript
{
    "notificationIds" : ["123", "3441", "3245"]
}
```

### Usage Example

{% tabs %}
{% tab title="cURL" %}

```typescript
curl -X PUT -H 'apiKey: 807b041b7d35425988e354e1f6bce186' -d '{
        "notificationIds" : ["123", "3441", "3245"]
  }' -v -i 'https://api.gameball.co/api/v3.0/integrations/notifications'
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
Gameball::Notifications.mark_notifications({notificationIds: ["123", "3441", "3245"]})
```

{% endtab %}

{% tab title="PHP" %}

```php
$response = $gameball->notification
    ->markPlayerNotificationsAsRead(["123", "3441", "3245"]);
```

{% endtab %}

{% tab title="Python" %}

```python
notifications = gameball.mark_notifications(["123", "3441", "3245"])
```

{% endtab %}

{% tab title=".NET" %}

```aspnet
var response = Gameball.MarkNotifications(new string[]{"123", "3441", "3245"});
```

{% endtab %}
{% endtabs %}


# API Endpoint Testing

Explore and test our API seamlessly with the dedicated Postman collection

**Importing the Collection in Postman**

Follow these steps to import the collection into your Postman environment:

1. **Open Postman**: Launch the Postman application on your system.
2. **Navigate to the Import Tab**: Click on the "Import" button located in the top-left corner of the Postman window.
3. **Select the Link Option**: Choose the "Link" tab within the Import dialog.
4. **Paste the Collection Link**: Copy the provided [collection link](https://bit.ly/referd-postman) and paste it into the designated field.
5. **Initiate the Import**: Click the "Import" button to initiate the import process.

![Import Postman Collection](https://chat.openai.com/c/path_to_screenshot/import_postman_collection.png)

<figure><img src="https://983627972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1bAQ4IvAKNqrQlsRN5b4%2Fuploads%2FApGZD78EMp2DfOwTZE1u%2Fimage%20(5).png?alt=media&amp;token=f8852750-f7e8-43ca-8693-ba6bb3e0d6d3" alt=""><figcaption></figcaption></figure>

By following these steps, you will seamlessly integrate the API endpoint collection into your Postman workspace, enabling you to effortlessly test and interact with our API.


# Errors

This section shows all Referd common error codes and how to resolve them.

## HTTP Status Codes

**Referd** uses [HTTP response status codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) to indicate the success or failure of your API requests. If your request fails, **Referd** returns an error using the appropriate status code.

* `2XX` codes indicate success and that the request worked as intended
* `4XX` codes indicate errors due to some mistakes in the request.
* `5XX` codes indicate an error with **Referd's** servers.

## Error Object

When an error occurs and the response code is `4XX`, **Referd's** servers send an **Error Object** that has two parameters, `code`and `message`.

### Example

```javascript
{
    "code": 14,
    "message": "Name Already Exists"
}
```

## Error Codes

**Referd** sends an error code in the body of the response, each code has a corresponding error message that is descriptive of what went wrong, below are the codes along with their description.

| Code | Message                    | Description                                                     |
| ---- | -------------------------- | --------------------------------------------------------------- |
| 4    | Missing Arguments          | Missing parameter in the argument                               |
| 5    | Null Arguments             | The format is invalid or not compatible                         |
| 7    | Invalid Value              | Value is in the wrong format.                                   |
| 12   | Name Length Invalid        | The provided name does not meet the required character limit    |
| 13   | Something Wrong            | An unexpected error occurred while processing your request.     |
| 14   | Name Already Exists        | The name provided is already registered in our system           |
| 15   | Email Already Exists       | The email address provided is already registered in our system. |
| 16   | Inactive                   | Inactive element like a user or program that are inactive       |
| 50   | Referd Is Disabled         | **Referd** is disabled                                          |
| 101  | User External ID Not Found | User does not exist                                             |
| 102  | User Already Exists        | The user you are trying to create already exists                |
| 351  | Event Not Found            | This event is not configured in the dashboard                   |


