# Welcome to Giftoin

Giftoin is your all-in-one platform for creating engaging player experiences through digital collections, rewards, and marketplaces. Whether you're running a Roblox game or a Discord community, our platform helps you boost player retention and create exciting economies.

### Why Giftoin? ✨

* 🔄 **Boost Retention** - Keep players coming back with engaging collection mechanics
* 💸 **Increase Revenue** - Create new monetization opportunities through digital collectibles
* 🛠️ **Easy Integration** - Simple API and SDKs that work with your existing infrastructure

### Get Started in 3 Steps 🚀

1. **Sign Up & Get API Key** - Create your account and access your API credentials
2. **Create Your First Collection** - Set up a themed set of digital collectibles
3. **Integrate & Launch** - Connect Giftoin to your game or platform

#### What Can You Do With Giftoin?

**🎴 Collections & Cards**

Create engaging digital card collections for your players to collect, complete, and earn rewards.

**🎁 Rewards**

Set up automated reward systems that encourage collection completion and player engagement.

**💰 Point System**

Establish your own economy with customizable point systems for transactions and rewards.

**🏪 Marketplace**

Create player-driven marketplaces where items can be traded using points.

#### Quick Navigation

* 📝 [**Overview** ](/introduction/overview)- Learn what Giftoin is and how it can benefit your game
* 🚀 [**Quick Start**](/introduction/quick-start) - Get up and running in minutes
* 🧩 [**API Reference**](/api-reference/standards-and-conventions) - Detailed API documentation for integration
* 💡 [**Use Cases**](/resources/use-cases) - Explore real-world implementation examples


# Overview

## What is Giftoin?

Giftoin is a comprehensive loyalty and marketplace platform designed specifically for gaming communities. We provide the infrastructure to create, manage, and distribute digital collectibles, set up reward systems, and establish in-game marketplaces with point-based economies.

## How Giftoin Stands Out 🌟

Traditional loyalty programs offer basic points and rewards. Giftoin transforms engagement through collectible-driven experiences:

| Traditional Loyalty | Giftoin Approach                   |
| ------------------- | ---------------------------------- |
| Basic points system | Rich collectible ecosystem         |
| Generic rewards     | Themed collections and marketplace |
| Limited engagement  | Gamified collection mechanics      |
| Single platform     | Cross-platform integration         |

### Core Features

### **🎴 Collection System**

* Create themed card collections
* Set collection durations and availability
* Define card rarities and quantities
* Track collection progress

### **🎁 Reward Management**

* Design flexible reward structures
* Set up automatic reward distribution
* Create tiered reward systems
* Configure reward claiming conditions

### **💰 Point System**

* Multiple point type support
* Configurable point economics
* Point earning mechanisms
* Balance management

### **🏪 Marketplace**

* Set up in-game marketplaces
* Configure item pricing
* Manage point-based transactions
* Control marketplace availability

### **🔗 Platform Integration**

* Easy-to-use REST API
* Multi-platform support (Roblox, Discord)
* Real-time updates
* Secure authentication

### Benefits

* 📈 Increase player retention through collecting mechanics
* 💵 Generate revenue through marketplace transactions
* 🤝 Build engagement with reward systems
* 🌐 Create sustainable in-game economies
* 📊 Track and analyze player behavior

### How It Works

1. Set up your collections and marketplace
2. Configure point systems and rewards
3. Integrate Giftoin into your game
4. Players collect, trade, and earn rewards
5. Monetize and optimize


# Quick Start

## Acquiring an API Key

Your API requests are authenticated using API keys. Any request that doesn't include an API key will return an error.

You can can access your API key directly from your management dashboard:

1. Login to the management dashboard with your account
2. Using the left side navigation panel click on Settings -> Account
3. Here you can reveal your API key or easily copy it.

{% hint style="info" %}
**Important to know:** Currently you can have only one API key. Make sure to save it in a secure location and do not share it. Also make sure to use it only on secured environments like your backend and absolutely not your front end.
{% endhint %}

## Using Your API Key

You may use any server-side programming language that can make HTTPS requests to target the Giftoin API. All requests should target the URL: `https://api.giftoin.org/api/v1`&#x20;

You need to supply your API Key in REST API calls in the header with a custom header:\
`x-gft_api_key`

## Make your first request

To make your first request, send an authenticated request to the campaigns endpoint. This will return you an array of existing campaigns, if you have none it will return an empty array.

{% hint style="info" %}
**Don't forget:** You must include your API key with every API call, otherwise you will receive an error.
{% endhint %}

{% openapi src="/files/t4I5L0nOvIDZ44vbu5Sn" path="/v1/gcm/reseller/campaign" method="get" %}
[reseller-1.1.1.yaml](https://content.gitbook.com/content/EhIwc268Kkd8bsiYY2hw/blobs/CPmtKes8SM3wpBcCZFGE/reseller-1.1.1.yaml)
{% endopenapi %}


# FAQs

### General Questions 🌐

#### What exactly is Giftoin?

Giftoin is a B2B2C platform that allows game developers to create digital collection systems, reward mechanics, and marketplaces to boost player engagement and retention.

#### Which platforms does Giftoin support?

Currently, we support Roblox and Discord with more platforms coming soon.

### Technical Questions 🔧

#### How do I get started with Giftoin?

Sign up for an account, get your API key, and follow our Quick Start guide to make your first integration.

#### Is Giftoin suitable for small indie games?

Absolutely! Giftoin is designed to scale from indie games to large productions.

#### Can I customize the look and feel of collections?

Yes, you have full control over the visual aspects of your collections, cards, and marketplace.

### Business Questions 💼

#### How does Giftoin help with player retention?

By implementing collectible mechanics, rewards for completion, and marketplace functionality, players have more reasons to return to your game regularly.

#### Can I monetize with Giftoin?

Yes, there are multiple monetization opportunities including premium collections, point packages, and marketplace transactions.

#### How does pricing work?

We offer flexible monthly plans for individuals, small teams, and enterprise options for larger organizations.

For current rates and detailed plan comparisons, please visit [giftoin.com/pricing](https://giftoin.com/pricing)


# Key Features

### Collection Management 🎴

* &#x20;Create unlimited themed collections
* Set collection timeframes (limited-time or permanent)
* Define custom reward structures
* Control card rarity and distribution

### Player Engagement 🎮

* Real-time collection progress tracking
* Automatic reward distribution
* Multiple point types support
* Cross-platform user management
* Player to player trading

### Developer Tools 🛠️

* Comprehensive REST API
* Detailed documentation
* Code examples for major platforms
* Testing environment

### Analytics and Insights 📊

* Track collection completion rates
* Monitor player engagement
* Measure campaign effectiveness
* View reward distribution stats

### Platform Support 🌐

* Roblox integration
* Discord integration
* More platforms coming soon

### Security 🔒

* Secure API authentication
* Rate limiting protection
* Data encryption
* Regular backups

### Marketplace Functionality 🏪

* Configure item pricing in points
* Enable player-to-player trading
* Create special marketplace-only items
* Set up limited-time offers

### Point System 💸

* Create multiple point types for different uses
* Reward points for in-game actions
* &#x20;Configure point exchange rates
* Set up point economy balancing


# Account Setup


# Authentication


# Making Your First API Call


# Standards and Conventions

Each request must contain the header `Accept: application/json`.\
You should also send an `Accept-Encoding: deflate, gzip` header to receive data fast and efficiently (will be supported in the future).<br>

All endpoints return data in JSON format with the results of your query under `data` if the call is successful.

## Endpoint Response Payload Format

All endpoints return data in JSON format with the results of your query under data if the call is successful.

A Status object is always included for both successful calls and failures when possible.\
The Status object always includes the current time on the server when the call was executed as a timestamp.

<br>

```json
{
    "data" : {
    ...
    },
    "status": {
        "timestamp": "1688555980233",
        "errorCode": 400,
        "errorMessage": "Invalid value for \"id\"",
   }
}

```


# Orders API


# Tokens/Points

{% openapi src="/files/kh1Lg73UZwyiSjgKTRkK" path="/gcm/reseller/campaign/{campaignPointsId}/order" method="post" %}
[giftoin-openapi-spec-updated-8.yaml](https://2038247114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEhIwc268Kkd8bsiYY2hw%2Fuploads%2F03ZVsMb8zfc5ndMhVHbW%2Fgiftoin-openapi-spec-updated-8.yaml?alt=media\&token=746e7872-6891-4710-b158-41d4a017e1ee)
{% endopenapi %}

**API Reference Notice**

We are currently experiencing a technical issue with the API reference display in GitBook. For the most accurate and complete API documentation, please refer to our [official API reference on Postman](https://www.postman.com/giftoin/giftoin-api).

We apologize for any inconvenience and are working to resolve this issue. Thank you for your understanding.


# Collectibles/Cards

{% openapi src="/files/kh1Lg73UZwyiSjgKTRkK" path="/gcm/reseller/campaign/{campaignCollectiblesId}/order" method="post" %}
[giftoin-openapi-spec-updated-8.yaml](https://2038247114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEhIwc268Kkd8bsiYY2hw%2Fuploads%2F03ZVsMb8zfc5ndMhVHbW%2Fgiftoin-openapi-spec-updated-8.yaml?alt=media\&token=746e7872-6891-4710-b158-41d4a017e1ee)
{% endopenapi %}

**API Reference Notice**

We are currently experiencing a technical issue with the API reference display in GitBook. For the most accurate and complete API documentation, please refer to our [official API reference on Postman](https://www.postman.com/giftoin/giftoin-api).

We apologize for any inconvenience and are working to resolve this issue. Thank you for your understanding.


# Collectibles/Random Cards

{% openapi src="/files/kh1Lg73UZwyiSjgKTRkK" path="/gcm/reseller/campaign/{campaignRandomId}/order" method="post" %}
[giftoin-openapi-spec-updated-8.yaml](https://2038247114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEhIwc268Kkd8bsiYY2hw%2Fuploads%2F03ZVsMb8zfc5ndMhVHbW%2Fgiftoin-openapi-spec-updated-8.yaml?alt=media\&token=746e7872-6891-4710-b158-41d4a017e1ee)
{% endopenapi %}

**API Reference Notice**

We are currently experiencing a technical issue with the API reference display in GitBook. For the most accurate and complete API documentation, please refer to our [official API reference on Postman](https://www.postman.com/giftoin/giftoin-api).

We apologize for any inconvenience and are working to resolve this issue. Thank you for your understanding.


# Users API

Users API allows developers to access key user-related data, focusing on inventories, collections, and progression stats. \
This API segment efficiently handles fundamental tasks associated with user data management.

### Features

* **Inventories**: Fetch and manage items in a user's inventory to keep real-time updates and modifications aligned with user interactions.
* **Collections**: Access and update user collections easily, enabling users to view and organize their collections seamlessly.
* **Progression**: Retrieve user progression details such as levels and achievements to track and display advancement metrics efficiently.

{% content-ref url="/pages/fQb1LefviyZed1DjdUka" %}
[Inventory](/api-reference/users-api/inventory)
{% endcontent-ref %}

{% content-ref url="/pages/ObShC5FgejBeULCseacI" %}
[Progress](/api-reference/users-api/progress)
{% endcontent-ref %}


# Inventory

{% openapi src="/files/Lyd84ZzdJWangiDYjetJ" path="/users/{platform}/{platformUserId}/inventory" method="get" %}
[giftoin-openapi-spec-updated-8 (1).yaml](https://2038247114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEhIwc268Kkd8bsiYY2hw%2Fuploads%2FkAoPrEQW2NAfT0nyKoRt%2Fgiftoin-openapi-spec-updated-8%20\(1\).yaml?alt=media\&token=239d658e-c9c3-43fb-b459-b4eec782024f)
{% endopenapi %}


# Progress

Get progress of user in collection-challenges

{% openapi src="/files/Lyd84ZzdJWangiDYjetJ" path="/users/{platform}/{platformUserId}/progress/collection-challenges" method="get" %}
[giftoin-openapi-spec-updated-8 (1).yaml](https://2038247114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEhIwc268Kkd8bsiYY2hw%2Fuploads%2FkAoPrEQW2NAfT0nyKoRt%2Fgiftoin-openapi-spec-updated-8%20\(1\).yaml?alt=media\&token=239d658e-c9c3-43fb-b459-b4eec782024f)
{% endopenapi %}

{% openapi src="/files/Lyd84ZzdJWangiDYjetJ" path="/users/{platform}/{platformUserId}/progress/collection-challenges/{programId}" method="get" %}
[giftoin-openapi-spec-updated-8 (1).yaml](https://2038247114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEhIwc268Kkd8bsiYY2hw%2Fuploads%2FkAoPrEQW2NAfT0nyKoRt%2Fgiftoin-openapi-spec-updated-8%20\(1\).yaml?alt=media\&token=239d658e-c9c3-43fb-b459-b4eec782024f)
{% endopenapi %}


# Error Handling

The API uses standard HTTP status The Giftoin API uses standard HTTP status codes to indicate the success or failure of an API call. Understanding these error codes will help you troubleshoot issues and handle errors gracefully in your application.

* `200 (OK)` - The request was successful
* `400 (Bad Request)` - The server could not process the request, most likely because of an invalid argument
* `401 (Unauthorized)` - Your request lacks valid authentication credentials, your API key is missing in the request headers
* `402 (Payment Required)` - Your API request was rejected due to it being a paid subscription plan with an overdue balance
* `403 (Forbidden)` - Your request was rejected due to a permission issue, likely a restriction on the API Key's associated service plan
* `404 (Not Found)` - The requested resource was not found
* `429 (Too Many Requests)` - The API Key's rate limit was exceeded
* `500 (Internal Server Error)` - An unexpected server issue was encountered

<br>

### Error Response Codes

When an error occurs, the API returns a JSON response with a status object containing:

* `timestamp` - The time when the error occurred
* `errorCode` - A numeric code specific to the error
* `errorMessage` - A human-readable description of the error

```json
{
    "status": {
        "timestamp": "1708777200000",
        "errorCode": 5250,
        "errorMessage": "Campaign not found"
    }
}
```

### Error Code Reference

Here's a reference of specific error codes you might encounter:

<table><thead><tr><th width="144.33333333333331">HTTP Status</th><th width="352">Error Code</th><th>Error Message</th></tr></thead><tbody><tr><td>400</td><td>1001 [API_KEY_INVALID]</td><td>This API Key is invalid.</td></tr><tr><td>401</td><td>1002 [API_KEY_MISSING]</td><td>API key missing.</td></tr><tr><td>404</td><td>5250[CAMPAIGN_NOT_FOUND]</td><td>Campaign not found</td></tr><tr><td>404</td><td>5252[CAMPAIGN_ORDER_NOT_FOUND]</td><td>Order not found</td></tr></tbody></table>

### Handling Errors in Your Code

Here are some best practices for handling API errors:

1. **Check for HTTP status codes first** - Handle different categories of errors differently (e.g., client errors vs. server errors)
2. **Parse the error message and code** - Extract specific information about what went wrong
3. **Implement retry logic for certain errors** - For example, retrying after a brief delay for rate limit errors (429)
4. **Log detailed error information** - Store the complete error response for debugging
5. **Provide user-friendly error messages** - Translate API errors into helpful information for your users

Example error handling in JavaScript:

```javascript
fetch('https://api.giftoin.org/api/v1/gcm/reseller/campaign/invalid_id')
  .then(response => {
    if (!response.ok) {
      return response.json().then(errorData => {
        throw {
          status: response.status,
          errorCode: errorData.status.errorCode,
          message: errorData.status.errorMessage
        };
      });
    }
    return response.json();
  })
  .then(data => {
    // Handle successful response
    console.log('Success:', data);
  })
  .catch(error => {
    // Handle error
    console.error('Error:', error);
    
    // User-friendly error messages
    if (error.errorCode === 5250) {
      displayUserMessage("We couldn't find that campaign. Please check the ID and try again.");
    } else if (error.errorCode === 5255) {
      displayUserMessage("This campaign is out of stock. Please contact support to increase the limit.");
    } else if (error.status === 429) {
      displayUserMessage("You've made too many requests. Please wait a moment and try again.");
    } else {
      displayUserMessage("Something went wrong. Please try again later or contact support.");
    }
  });
```


# Roblox

Giftoin Module is an easy way to integrate the powerful Giftoin platform solutions and tools into your Roblox games. Our module provides seamless access to a wide range of features, including:

* Gaming card collections
* Point system and shop
* Discord integration
* Quest system
* And much more!

With Giftoin Module, developers can enhance their games with robust economy systems, engaging collectibles, and cross-platform connectivity, all while simplifying the integration process.<br>


# Why use Giftoin?

## Why Choose Giftoin for Your Roblox Projects?

As a Roblox developer, you're constantly looking for ways to **enhance your games and provide more value** to your clients. \
The Giftoin Module offers a **powerful solution** that can set your projects apart and **create new revenue streams**.&#x20;

Here's why you should consider integrating Giftoin into your development toolkit:

### Unlock New Revenue Potential

By implementing Giftoin's loyalty and rewards system, you can help your clients monetize their games more effectively. Our platform enables:

* In-game economies with virtual currencies and points
* Collectible card systems that drive engagement
* Customizable shops for virtual goods

### Boost Player Engagement and Retention

Giftoin's gamification features are designed to keep players coming back:

* Reward progression with levels and points[1](https://giftoin.com/)
* Create engaging loyalty programs
* Implement automated tournaments and giveaways

### Seamless Integration

We've designed the Giftoin Module with developers like you in mind:

* Easy-to-implement, turnkey solutions[1](https://giftoin.com/)
* Comprehensive documentation and support
* Minimal coding required for advanced features

### Cross-Platform Connectivity

Expand your game's reach beyond Roblox:

* Discord integration for community building
* Future-proof your games with blockchain technology
* (Optional) Web3 assets and integrations

### Stand Out to Clients

Offer cutting-edge features that will impress your clients:

* Advanced loyalty programs that are simple to implement
* Custom rewards systems that increase player retention
* Data-driven insights to help optimize game performance

### Grow Your Business

By mastering the Giftoin Module, you'll be able to:

* Offer additional services to existing clients
* Attract new clients with innovative game features
* Position yourself as a forward-thinking developer in the Roblox ecosystem

\ <br>


# Basic Usage

Welcome to the Gitoin API documentation! This page provides a comprehensive guide to integrating our API with your Roblox applications, enabling you to leverage our platform's features seamlessly.

### Steps to Implement

1. **Set Up HTTP Requests**\
   Enable HTTP requests in your game settings:
   * Go to Game Settings > Security
   * Enable "Allow HTTP Requests"
   * Roblox [docs reference](https://create.roblox.com/docs/reference/engine/classes/HttpService#HttpEnabled)
2. **Create a Server Script**
   * In Roblox Studio, create a new Script in ServerScriptService
   * Copy the provided code into this script
3. **Customize API Details**\
   Replace the placeholder values in the script:
   * `<CAMPAIGN_ID>`: Insert your specific campaign ID
   * `<API KEY>`: Insert your provided API key
4. **Error Handling**\
   The script includes basic error handling. You can expand on this by logging errors or implementing retry logic.
5. **Testing**\
   Test the API call in a controlled environment before full implementation.

#### Send Giftoin Function (Lua)

```lua
local HttpService = game:GetService("HttpService")

local function sendGiftoin(apiUrl, apiKey, dataTable)
    local jsonData = HttpService:JSONEncode(dataTable)
    
    local headers = {
        ["Content-Type"] = "application/json",
        ["x-gft-api-key"] = apiKey
    }
    
    local requestDetails = {
        Url = apiUrl,
        Method = "POST",
        Headers = headers,
        Body = jsonData
    }
    
    local success, response = pcall(function()
        return HttpService:RequestAsync(requestDetails)
    end)
    
    if success then
        if response.Success then
            print("Data sent successfully! Response:", response.Body)
            -- Process response data here if needed
            return true, response.Body
        else
            warn("API request failed. Status code:", response.StatusCode)
            return false, response.StatusCode
        end
    else
        warn("Failed to send data: " .. tostring(response))
        return false, response
    end
end

local apiUrl = "https://api.giftoin.org/v1/api-reseller/api/v1/gcm/reseller/campaign/YOUR_CAMPAIGN_ID/order"
local apiKey = "YOUR_API_KEY"

```

### Player Join Event

#### **Triggers when user joins the game**

This API implementation uses Roblox's `HttpService` to send player data to an external endpoint when a a player joins the game. Here's a breakdown of how it works:

1. The script uses the `Players.PlayerAdded` event to detect when a new player joins the game.
2. When a player joins, it creates a data table containing the player's Roblox user ID.
3. The `sendGiftoin` function is called with this data, along with the API URL and API key.
4. The function converts the data to JSON format and sends a POST request to the specified API endpoint.
5. The request includes necessary headers like Content-Type and the API key for authentication.
6. Error handling is implemented using pcall to catch any issues during the HTTP request.
7. The script prints success or failure messages based on the API response.

```lua
game.Players.PlayerAdded:Connect(function(player)
    local dataTable = {
        ["thirdPartyUserIds"] = {
            {["type"] = "roblox",
            ["id"] = tostring(player.UserId)}
        }
    }
    
    local success, result = sendGiftoin(apiUrl, apiKey, dataTable)
    if success then
        print("API call successful for player:", player.Name)
    else
        warn("API call failed for player:", player.Name, "Error:", result)
    end
end)
```


# Developer Access

### Sign Up for Developer Access

To begin using the Giftoin Module, you first need to sign up for developer access. Follow these steps:

1. **Visit Our Website**: Apply for developer access on our [official website](https://giftoin.com/).
2. **Receive Account Details**: Check your email for your account credentials and getting started information.
3. **Choose the Roblox Template**: Select the "Roblox" template in your dashboard for a quick setup.
4. **Explore Documentation**: Continue to our "Getting Started" page for detailed integration guides.

### Accessing Your API Key

Once logged in, navigate to your account dashboard to generate your API key:

* Click on "Settings" -> "Account" in the sidebar.
* Copy your API key and keep it secure; you’ll need it for authentication in your scripts.


# Installation

To add the Giftoin Module to your Roblox game you need to simply download the module and import it to your game accordingly to the detailed guide below:

{% file src="/files/f7Dbfmk6rVwbTZPXVwaI" %}
Giftoin Module File
{% endfile %}

1. **Download Giftoin Module file**:
   * Navigate to and select the downloaded `.rbxmx` file.
2. **Place in ServerScriptService:**
   * Right click `ServerScriptService` in your Explorer panel.
   * Select "Insert Object"
   * Select the GiftoinModule file you just downloaded
   * The GiftoinModule folder & config will be imported to your `ServerScriptService`
3. **Create Additional Objects (optional)** :\
   Create multiple `RemoteEvent` in `ReplicatedStorage` as needed and mentioned in further guides in this docs.

#### Verifying Installation

Regardless of the method you choose, ensure that the Giftoin Module is properly placed in `ServerScriptService`. This location is crucial for the module to function correctly and securely.

## File Structure

```
GiftoinModule (Folder)
├── init.lua
├── API.lua
├── Utils.lua
├── Events.lua
├── [Other module files]
GiftoinModuleConfig (File)

```

## Authenticating with Your API Key

To use the Giftoin API, you need to authenticate using your API key. We've simplified this process by using a config file within the GiftoinModule.

#### Steps to Set Up Authentication

1. **Locate the Config File**: In the `ServerScriptFolder` folder, you'll find a file named `GiftoinModuleConfig`. This file is outside of the GiftoinModule folder to enable you to upgrade to future versions easily without resetting your config each time.
2. **Enter Your API Key**: Look for the `API_KEY` variable and replace the placeholder value with your actual API key:

   ```lua
   return {
   	API = {
   		BASE_URL = "https://api.giftoin.org/v1/api-reseller/api/v1",
   		API_KEY = "123"
   	},
   }


   ```
3. **Save the File**: After entering your API key, save the file.

#### Using the API

With your API key set in the settings file, the Giftoin Module will automatically handle authentication for all API calls. You don't need to manually authenticate in your scripts.

To use the Giftoin API in your game scripts, simply require the module as usual:

```lua
local ServerScriptService = game:GetService("ServerScriptService")
local GiftoinModule = require(ServerScriptService:WaitForChild("GiftoinModule"):WaitForChild("init"))
local GiftoinEvents = GiftoinModule.Events




--local claimGiftoinEvent = game.ReplicatedStorage.GiftoinModule.ClaimGiftoinEvent
-- Create the ClaimGiftoinEvent if it doesn't exist
local claimGiftoinEvent = game.ReplicatedStorage:FindFirstChild("ClaimGiftoinEvent")
if not claimGiftoinEvent then
	claimGiftoinEvent = Instance.new("RemoteEvent")
	claimGiftoinEvent.Name = "ClaimGiftoinEvent"
	claimGiftoinEvent.Parent = game.ReplicatedStorage
end


claimGiftoinEvent.OnServerEvent:Connect(function(player)
	GiftoinEvents.claimDaily(player)
end)

```

#### Security Note

Remember to keep your `GiftoinModuleConfig` file secure and never share it publicly.\
If you're using version control, make sure to add this file to your `.gitignore` to prevent accidentally committing your API key.&#x20;


# Additional Example / Use-Cases


# Point Reward

Here's an example of how to use the Giftoin Module to send points to a player when they join the game.

#### Server Script Example

Place this script in `ServerScriptService`:

```lua
-- Require the necessary modules
local GiftoinApi = require(game.ReplicatedStorage.GiftoinModule.API)
local GiftoinUtils = require(game.ReplicatedStorage.GiftoinModule.Utils)
local GiftoinEvents = require(game.ReplicatedStorage.GiftoinModule.Events)

-- Configuration (replace with your actual values)
local CAMPAIGN_ID = "your_campaign_id_here"
local POINT_ID = "your_point_id_here"
local JOIN_REWARD_AMOUNT = 100

-- Function to send points when a player joins
local function onPlayerJoin(player)
    local robloxId = tostring(player.UserId)
    
    -- Send points to the player
    local success, result = GiftoinApi.sendPoint(robloxId, CAMPAIGN_ID, POINT_ID, JOIN_REWARD_AMOUNT)
    
    if success then
        print(player.Name .. " was awarded " .. JOIN_REWARD_AMOUNT .. " points for joining!")
    else
        warn("Failed to send points to " .. player.Name .. ". Error: " .. tostring(result))
    end
end

-- Connect the function to the PlayerAdded event
game.Players.PlayerAdded:Connect(onPlayerJoin)

-- Set up the ClaimGiftoin event handler
local claimGiftoinEvent = game.ReplicatedStorage.GiftoinModule.ClaimGiftoinEvent

claimGiftoinEvent.OnServerEvent:Connect(function(player)
    -- Example of using sendPoint for a different scenario
    local success, result = GiftoinApi.sendPoint(tostring(player.UserId), CAMPAIGN_ID, "daily_reward", 50)
    
    if success then
        print(player.Name .. " claimed their daily reward of 50 points!")
    else
        warn("Failed to send daily reward points to " .. player.Name .. ". Error: " .. tostring(result))
    end
end)
```

#### Explanation

1. We start by requiring the necessary modules from the GiftoinModule.
2. We define configuration variables for the campaign ID, point ID, and the amount of points to award when joining. You should replace these with your actual values (from you Giftoin Dashboard website).
3. The `onPlayerJoin` function is defined to send points to a player when they join. It uses `GiftoinApi.sendPoint()` with the following parameters:
   * `robloxId`: The player's Roblox User ID as a string
   * `campaignId`: The ID of your campaign
   * `pointId`: The ID of the point type you're awarding
   * `quantity`: The number of points to award
4. We connect the `onPlayerJoin` function to the `PlayerAdded` event, so it runs whenever a new player joins the game.
5. We also set up an event handler for the `ClaimGiftoinEvent`. This demonstrates how to use the `sendPoint` function in a different scenario, such as awarding daily rewards that will be explained in more detail in the [Broken mention](broken://pages/jPwkrlyKgyeiivCNxBud) section.

#### Important Notes

* Make sure to replace `"your_campaign_id_here"` and `"your_point_id_here"` with your actual campaign and point IDs.
* The `robloxId` is obtained from the player's `UserId` and converted to a string, as required by the `sendPoint` function.
* Error handling is implemented to log any issues with sending points.
* This example assumes that the `sendPoint` function returns a success boolean and a result. Adjust the error handling if the function behaves differently.


# Daily Reward

### Simplified Daily Reward System Guide

The Giftoin package includes a built-in daily reward system that handles all the logic on the server-side, including catching the event, processing the claim, and sending the result back to the client.

#### 1. Set Up the Client-Side Script

1. Create a new `LocalScript` in `StarterPlayerScripts` or attach it to the GUI element that will handle the claim button.
2. Create a new instance of `RemoteEvent` in `ReplicatedStorage` named `ClaimGiftoinEvent`
3. Use the following code:

```lua
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local claimButton = script.Parent
local claimGiftoinEvent = ReplicatedStorage.GiftoinModule.ClaimGiftoinEvent
local debounce = false

local function updateUI(success, message)
    if success then
        print("Reward claimed successfully: " .. message)
        -- Update UI to show success (e.g., show a success message, update reward counter)
    else
        print("Claim failed: " .. message)
        -- Update UI to show failure (e.g., show an error message)
    end
end

claimButton.MouseButton1Click:Connect(function()
    if debounce then return end
    debounce = true
    claimGiftoinEvent:FireServer()
    debounce = false
end)

claimGiftoinEvent.OnClientEvent:Connect(updateUI)
```

#### 2. Create the Claim Button

1. Design a GUI with a claim button for your daily reward.
2. Attach the LocalScript from step 1 to this button.

#### 3. Customize the Reward UI

* Implement the `updateUI` function to update your game's UI based on the claim result.
* You can show success messages, update reward counters, or display error messages as needed.

#### 4. Additional Considerations

* The GiftoinModule handles all the server-side logic for daily claims, including:
  * Catching the ClaimGiftoinEvent
  * Processing the claim (including checks for 24-hour intervals)
  * Sending the result back to the client
* You don't need to implement any server-side scripts for this functionality.
* The system will automatically ensure that players can only claim once every 24 hours.

#### 5. Potential Use Cases

* **Daily Login Reward**: Use this system as is for a daily login reward.
* **Quest Completion**: Trigger the claim when a player completes a daily quest.

By following this simplified guide, you'll have integrated the Giftoin daily reward system into your game. \
The system handles all server-side logic automatically, allowing you to focus on creating an engaging UI and integrating the reward system into your game's overall design.


# Advanced Point Distribution System

### Step-by-Step Setup Guide

#### 1. Import the Collectible Point Part

{% file src="/files/FsH8C84kNNACNVuOiK4Y" %}

The ready to use part contains:

1. Point part with mesh & texture
2. Sound to be played when user collide with the part (collect it)
3. Server-side script to handle the collision & sending of point to the player
4. Part's customer attributes to be used when sending the point on the Giftoin Platform the the player

#### 2. Set Up Custom Attributes

1. Select your "CandyPoint" part in the Explorer.
2. In the Properties window, scroll down to the Attributes section.
3. Set values for each attribute:
   * PointQuantity: Enter the number of points this collectible is worth (e.g., 10)
   * PointId: Enter a unique identifier for this type of point (e.g., "candy\_point")
   * CampaignId: Enter the campaign identifier (e.g., "halloween\_2024")

#### 3. Test and Replicate

1. Play test your game to ensure the point collection works as expected.
2. Once confirmed, you can duplicate the "CandyPoint" part and distribute it throughout your game.
3. Adjust the attributes for each instance as needed (e.g., different point values or IDs for different locations).

#### 4. Final Considerations

* Ensure the GiftoinModule is properly set up with the correct API endpoints and authentication.
* Consider creating a system to dynamically spawn these points in your game.
* Implement a user interface to display collected points to players.
* Set up proper error handling and logging for the API calls.


# Managed Codes & In-Game Rewards (Coming Soon)

Learn how to implement and use Giftoin's advanced code redemption and reward system in your Roblox game.

Welcome to Giftoin's Managed Codes & In-Game Rewards system! This powerful tool allows you to easily implement a secure and flexible code redemption system in your Roblox game.

Key features:

* Instant implementation with GiftoinModule
* Secure server-side processing
* Flexible reward types
* Customizable UI integration
* Centralized code management through Giftoin platform

By using our system, you can focus on creating unique gameplay experiences while we handle the complexities of code management and reward distribution.

### Register Reward Type

Our module is built in a modular way - allowing all kinds of rewards.&#x20;

You simply need to register each reward type - name and the function to run to grant the reward to the user.

```lua
-- For updating leaderboard stats

local ServerScriptService = game:GetService("ServerScriptService")
local GiftoinModule = require(ServerScriptService:WaitForChild("GiftoinModule"):WaitForChild("init"))
local GiftoinRedemptionSystem = GiftoinModule.Redemption

GiftoinRedemptionSystem.RegisterCallback("points", function(player, amount)
	print("points added")
	local leaderstats = player:FindFirstChild("leaderstats")
	if leaderstats then
		local points = leaderstats:FindFirstChild("Points")
		if points then
			points.Value = points.Value + amount
		end
	else
		print("Player leaderstats are missing")
	end
end)

```


# Registering Reward Types

Learn how to define custom reward types for your game.

The GiftoinModule allows you to register custom reward types that fit your game's economy. \
Here's how to register a reward type(place it in a server-side script in `ServerScriptService`):

```lua

GiftoinModule.RegisterRewardType("Currency", function(player, amount)
    -- Add currency to player's account
    local leaderstats = player:FindFirstChild("leaderstats")
    if leaderstats then
        local currency = leaderstats:FindFirstChild("Currency")
        if currency then
            currency.Value = currency.Value + amount
        end
    end
end)

```

You can register multiple reward types:

```lua
GiftoinModule.RegisterRewardType("Item", function(player, itemId)
    -- Give item to player
    -- Your item granting logic here
end)

GiftoinModule.RegisterRewardType("Experience", function(player, expAmount)
    -- Add experience to player
    -- Your experience granting logic here
end)
```


# Authenticating with Your API Key

To use the Giftoin API, you need to authenticate using your API key. We've simplified this process by using a settings file within the GiftoinModule.

#### Steps to Set Up Authentication

1. **Locate the Settings File**: In the GiftoinModule folder, you'll find a file named `Settings.lua`.
2. **Enter Your API Key**: Open `Settings.lua` and look for the `API_KEY` variable. Replace the placeholder value with your actual API key:

   ```lua
   -- GiftoinSettings.lua
   local Settings = {
       API_KEY = nil -- Replace with your actual API key
   }

   return Settings
   ```
3. **Save the File**: After entering your API key, save the `Settings.lua` file.

#### Using the API

With your API key set in the settings file, the Giftoin Module will automatically handle authentication for all API calls. You don't need to manually authenticate in your scripts.

To use the Giftoin API in your game scripts, simply require the module as usual:

```lua
local GiftoinApi = require(game.ReplicatedStorage.GiftoinModule.API)
local GiftoinUtils = require(game.ReplicatedStorage.GiftoinModule.Utils)
local GiftoinEvents = require(game.ReplicatedStorage.GiftoinModule.Events)


local claimGiftoinEvent = game.ReplicatedStorage.GiftoinModule.ClaimGiftoinEvent

claimGiftoinEvent.OnServerEvent:Connect(function(player)
-- Now you can use GiftoinAPI functions without additional authentication steps
	GiftoinApi.someFunction(player)
end)
```

#### Security Note

Remember to keep your `GiftoinSettings.lua` file secure and never share it publicly.\
If you're using version control, make sure to add this file to your `.gitignore` to prevent accidentally committing your API key.


# Tools and Scripts

In addition to our core API functions, we provide a collection of ready-to-use tools and scripts to enhance your game development experience. These scripts can be easily integrated into your projects

<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><strong>Rotating Script</strong></td><td></td><td></td><td><a href="/files/Q78tFsudqXBJj1pzU4qF">/files/Q78tFsudqXBJj1pzU4qF</a></td><td><a href="/pages/MaLRD6O0PJMwhvrfwptp">/pages/MaLRD6O0PJMwhvrfwptp</a></td></tr><tr><td></td><td></td><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td><td></td><td></td></tr></tbody></table>


# Rotating Script

This script allows you to easily create a rotating effect for objects in your game, such as coins, power-ups, or decorative elements.

<figure><img src="/files/Q78tFsudqXBJj1pzU4qF" alt=""><figcaption></figcaption></figure>

```lua
local coin = script.Parent

local function rotate ()
	while true do
		coin.Orientation = coin.Orientation + Vector3.new(0, 3, 0)
		wait()
	end
end

rotate()

```

### How to Use:

1. Create a new Script in Roblox Studio.
2. Copy and paste the above code into the script.
3. Place the script as a child of the object you want to rotate.
4. The object will now rotate continuously around its Y-axis.

### Customization:

* To change the rotation speed or axis, modify the Vector3 values:
  * `Vector3.new(X, Y, Z)`:
    * X controls rotation around the X-axis
    * Y controls rotation around the Y-axis
    * Z controls rotation around the Z-axis
* Increase the numbers for faster rotation, decrease for slower rotation.

### Example Use Cases:

* Rotating coins or collectibles
* Creating spinning power-ups
* Animating decorative elements in your game world

\ <br>


# Floating Script

Coming soon...


# Quest System (Coming Soon)

Easily create quests and reward your players using the Giftoin platform


# Discord

## Available In Closed Beta!

The Discord bot is currently only available to a limited selection of beta users. Contact us at <contact@giftoin.com> to join the beta.


# Introduction

The Giftoin Discord App integrates powerful loyalty and rewards functionality directly into your Discord server.

Key features include:

* Digital collectible card management
* Giveaway creation and management
* Card trading system
* Progress tracking for collections
* User inventory management
* Administrative statistics and controls

This guide will walk you through setting up the Giftoin Discord App and using all of its features effectively.


# Getting Started

##

{% stepper %}
{% step %}

### Install the Bot

* Visit [Discord official Giftoin installation link](https://discord.com/oauth2/authorize?client_id=1217845993513685085)
* Click "Add to Server"
* Select the server where you want to install Giftoin
* Review and approve the requested permissions
  {% endstep %}

{% step %}
**Request Setup Code**

* Join the official [Giftoin Discord](https://discord.gg/9CzbDYc9sV) server
* Open a support ticket in the designated channel
* Request a unique setup authorization code
* The Giftoin support team will provide you with a code specific to your server

{% endstep %}

{% step %}
**Run Setup Command**

* In your server, use the `/giftoin setup {setupCode}` command in any channel
* Enter the setup code when prompted
* The bot will verify permissions and begin the setup process
* Wait for confirmation that setup is complete

{% endstep %}

{% step %}
Private Mode Configuration

* After setup, all Giftoin elements will be created in private mode
* Only server administrators can view the newly created:
  * Giftoin category
  * Specialized channels
  * Role configurations
  * Pinned guide messages
* Review all created elements and make any desired customizations
  {% endstep %}

{% step %}
**Test Bot Functionality**

* Experiment with the available commands (see [Command Reference](/platform-guides/discord/command-reference))
* Test giveaway creation and management
* Check inventory and progress tracking
* Ensure all features work as expected before making public
  {% endstep %}

{% step %}
Publish the Bot

* When ready for users to access the bot, run the `/publish` command
* Specify which roles should have access to Giftoin features
* Confirm the publication settings
* The bot will then become visible and usable for members with the specified roles
  {% endstep %}
  {% endstepper %}

<details>

<summary>Server Structure</summary>

* **Admin Channel**: For bot announcements and admin-only communications
* **Guide Channel**: Contains helpful resources and links
* **Giveaways Channel**: Where giveaways are announced and managed
* **General Channel**: For community discussions about Giftoin
* **Trading Channel**: Where members can trade cards and view offers
* **Bingo Channel**: Reserved for future bingo functionality

Note: Administrators can rename these channels after setup without affecting functionality.

</details>


# Command Reference

### Command Reference

#### General Commands

| Command      | Description                                | Usage        | User Access |
| ------------ | ------------------------------------------ | ------------ | ----------- |
| `/daily`     | Collect your daily rewards                 | `/daily`     | All members |
| `/inventory` | View your collection of cards and points   | `/inventory` | All members |
| `/progress`  | Check your progression through collections | `/progress`  | All members |

#### Giveaway Commands

| Command            | Description                         | Usage                         | User Access   |
| ------------------ | ----------------------------------- | ----------------------------- | ------------- |
| `/giveaway view`   | View details of a specific giveaway | `/giveaway view {giveawayId}` | Admins & Mods |
| `/giveaway list`   | List active and scheduled giveaways | `/giveaway list`              | Admins & Mods |
| `/giveaway create` | Create a new giveaway               | `/giveaway create`            | Admins & Mods |
| `/giveaway cancel` | Cancel an existing giveaway         | `/giveaway cancel`            | Admins & Mods |

#### Trading Commands

| Command                | Description                            | Usage                            | User Access |
| ---------------------- | -------------------------------------- | -------------------------------- | ----------- |
| `/trade offers create` | Create a new trade offer               | `/trade offers create`           | All members |
| `/trade offers list`   | View all active trade offers           | `/trade offers list`             | All members |
| `/trade offers cancel` | Cancel one of your active trade offers | `/trade offers cancel {offerId}` | All members |

#### Administrator Commands

| Command        | Description                                 | Usage          | User Access |
| -------------- | ------------------------------------------- | -------------- | ----------- |
| `/admin stats` | Retrieve statistics about Giftoin usage     | `/admin stats` | Admins only |
| `/grant-role`  | Assign a Giftoin role to a user             | `/grant-role`  | Admins only |
| `/publish`     | Make the bot available to users after setup | `/publish`     | Admins only |


# Role System

The Giftoin Discord App creates a hierarchical role system

#### Giftoin Admin

* Full access to all Giftoin features
* Can configure bot settings
* Can create, edit, and cancel giveaways
* Can view admin statistics
* Can manage roles
* Access to admin channel

#### Giftoin Moderator

* Can create and edit giveaways
* Can moderate trading activities
* Cannot access admin-only features
* Cannot view administrative statistics

#### Giftoin Member

* Automatically assigned to users who interact with the bot
* Can participate in giveaways
* Can create and accept trade offers
* Can view their inventory and progress


# User Guides

<details>

<summary>How to Trade Cards</summary>

1. **Creating a Trade Offer**:
   * Use `/trade offers create`
   * Select up to 3 cards from your inventory to offer
   * Optionally add a point value
   * Confirm your offer
2. **Viewing Trade Offers**:
   * Use `/trade offers list` to see all active offers
   * Browse offers in the Trading channel
3. **Accepting a Trade**:
   * Click the "Accept Trade" button on any trade offer
   * Review the trade details carefully
   * Confirm to complete the trade
4. **Canceling Your Trade Offer**:
   * Use `/trade offers cancel {offerId}`
   * The offer will be removed from the list and channel

Note: Trade offers expire after 24 hours if not accepted.

</details>

<details>

<summary>Checking Your Inventory</summary>

* Use the `/inventory` command to see all your collected items
* Your inventory displays:
  * Cards organized by collection
  * Rarity information
  * Point balance
  * Direct link to your wallet login

</details>

<details>

<summary>Tracking Your Progress</summary>

1. Use the `/progress` command to check your collection status
2. The progress view shows:
   * Collection completion percentage
   * Owned vs. missing cards
   * Direct reward claims available
   * Quick access to your Giftoin App profile

</details>

<details>

<summary>Setting Up the Bot (Admin Guide)</summary>

1. **Initial Setup**:
   * Use `/setup` in any channel
   * Enter your authorization code when prompted
   * Wait for the setup process to complete
2. **Configuring Channels**:
   * After setup, all required channels will be created
   * You can rename channels without affecting functionality
   * Customize channel permissions as needed
3. **Role Assignment**:
   * Use `/grant-role` to assign Giftoin Admin or Moderator roles
   * Members role is assigned automatically through interaction
4. **Publishing the Bot**:
   * Use `/publish` when ready to make the bot available to all members
   * Ensure all mandatory channels exist before publishing
   * Configure audience access settings as needed

</details>

<details>

<summary>Managing Giveaways</summary>

* Use `/giveaway create`
* Set the prize, duration, and winner count
* Configure announcement settings:
  * Public announcements
  * Private DM notifications (at least one method required)
* Set duration using the "1m 1h 1d" format (e.g., "2h 30m" for 2 hours and 30 minutes)
* **Monitoring Active Giveaways**:
  * Use `/giveaway list` to view all active and scheduled giveaways
  * Filter by status (in-progress/scheduled)
* **Viewing Giveaway Details**:
  * Use `/giveaway view {giveawayId}` to see:
    * Configuration settings
    * Participation data
    * Winner information (if ended)
* **Canceling a Giveaway**:
  * Use `/giveaway cancel` and select the giveaway to cancel
  * Confirm cancellation when prompted

</details>

<details>

<summary>Viewing Statistics</summary>

1. Use `/admin stats` to access comprehensive metrics
2. Available statistics include:
   * Daily and weekly usage
   * Trading activity
   * User engagement
   * Giveaway participation
   * Collection completion rates

</details>


# Troubleshooting

## Common Issues and Solutions

**Bot Not Responding to Commands**

* Ensure the bot has proper permissions
* Check if the bot is online and operational
* Verify you're using the correct command syntax

**Giveaway Creation Failing**

* Ensure you have Admin or Moderator role
* Check that all required fields are completed
* Verify the prize description is not too long

**Trading Issues**

* Confirm both parties have the items in their inventory
* Check that you haven't reached the trade offer limit (default: 1 active offer)
* Verify the offer hasn't expired (24-hour limit)

**Missing Channels After Setup**

* Run the setup process again
* Check server permissions for the bot
* Contact Giftoin support if issues persist

## Getting Help

If you encounter issues not covered in this documentation:

1. Check the #guide channel for additional resources
2. Contact the server administrator
3. Submit a support ticket in the official Giftoin Discord server


# FAQs

### FAQ

**Q: How do I get a setup code for setup command?** \
A: Setup codes are available through Giftoin's Discord server by submitting a support ticket.

**Q: Can I rename the channels created by the bot?** \
A: Yes, you can rename channels without affecting functionality. The bot tracks channels by their unique IDs, not names.

**Q: How many active trade offers can a user have?** \
A: By default, users can have 1 active trade offer at a time. This limit can be configured depends on your subscription plan.

**Q: Do cards get locked when included in a trade offer?** \
A: No, cards are not locked during the offer period. Inventories are validated at the time of trade execution.

**Q: How long do trade offers last?** \
A: Trade offers expire after 24 hours if not accepted.

**Q: How do users claim daily rewards?** \
A: Users can claim daily rewards using the `/daily` command. Limited to one per 24 hours.&#x20;

**Q: Can users participate in multiple giveaways simultaneously?** \
A: Yes, users can participate in as many active giveaways as they wish.


# Wordpress

## Available In Closed Beta!

The Discord bot is currently only available to a limited selection of beta users. \
Contact us at <https://giftoin.com/contact> or directly via email <contact@giftoin.com> to join the beta.


# Use Cases

Discover how to implement Giftoin in different scenarios to maximize engagement and value for your users. These use cases provide practical examples and code samples to help you get started quickly.

{% content-ref url="/pages/UmXz5S77N0LOhHm691hV" %}
[Basic](/resources/use-cases/basic)
{% endcontent-ref %}

{% content-ref url="/pages/jmvDQfvir2UCXPH5kyxP" %}
[Games](/resources/use-cases/games)
{% endcontent-ref %}

{% content-ref url="/pages/rIqcON6bL9yHWuHXZbAl" %}
[eCommerce](/resources/use-cases/ecommerce)
{% endcontent-ref %}


# Basic

#### Loyalty Programs

Loyalty programs are a powerful way to increase customer retention and lifetime value. \
With Giftoin, you can create sophisticated loyalty programs that reward users for various actions.

**Basic Loyalty Program Setup**

1. Create a points-based campaign in your Giftoin dashboard
2. Set up point values for different user actions:
   * Account creation: 100 points
   * Purchases: 1 point per $1 spent
   * Referrals: 50 points per successful referral
3. Implement point tracking in your application:

```javascript
// Award points for a purchase
async function awardPurchasePoints(userId, orderAmount) {
  const pointsToAward = Math.floor(orderAmount);
  
  try {
    const response = await fetch(`https://api.giftoin.org/api/v1/gcm/reseller/campaign/${CAMPAIGN_ID}/point`, {
      method: 'POST',
      headers: {
        'x-gft_api_key': 'YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        userId: userId,
        points: pointsToAward,
        reason: `Purchase points for order ${orderAmount}`
      })
    });
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error awarding points:', error);
    throw error;
  }
}
```

4. Create redemption tiers with different rewards:
   * 500 points: 10% discount coupon
   * 1000 points: Free shipping coupon
   * 2500 points: Exclusive digital collectible

**Loyalty Program Best Practices**

* Make point earnings visible and easy to understand
* Provide a clear path to rewards
* Celebrate milestone achievements
* Create limited-time bonus point opportunities
* Send regular updates on point balances and available rewards
* Analyze redemption patterns to optimize your program


# eCommerce

Integrate Giftoin into your e-commerce platform to enhance customer experience and drive sales through strategic rewards.

**Post-Purchase Rewards**

Send a digital reward immediately after purchase completion:

```php
<?php
// After order confirmation
function sendPostPurchaseReward($customerEmail, $orderAmount, $orderNumber) {
  $curl = curl_init();
  
  $payload = [
    "contacts" => [$customerEmail],
    "title" => "Thank You for Your Purchase!",
    "description" => "Enjoy this special gift as a token of our appreciation.",
    "metadata" => [
      "orderNumber" => $orderNumber,
      "orderAmount" => $orderAmount
    ]
  ];
  
  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.giftoin.org/api/v1/gcm/reseller/campaign/YOUR_CAMPAIGN_ID/order',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_HTTPHEADER => array(
      'x-gft_api_key: YOUR_API_KEY',
      'Content-Type: application/json'
    ),
  ));
  
  $response = curl_exec($curl);
  curl_close($curl);
  return json_decode($response, true);
}
?>
```

**Abandoned Cart Recovery**

Send a special offer to customers who abandoned their shopping carts:

1. Track cart abandonment in your e-commerce system
2. After 24 hours, send a gift with a discount coupon:

```javascript
// Scheduled job to process abandoned carts
async function processAbandonedCarts() {
  // Get carts abandoned 24 hours ago
  const abandonedCarts = await getAbandonedCarts(24);
  
  for (const cart of abandonedCarts) {
    try {
      const response = await fetch(`https://api.giftoin.org/api/v1/gcm/reseller/campaign/ABANDONED_CART_CAMPAIGN_ID/order`, {
        method: 'POST',
        headers: {
          'x-gft_api_key': 'YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          contacts: [cart.customerEmail],
          title: "Don't Miss Out!",
          description: "We saved your cart. Complete your purchase with this special discount.",
          metadata: {
            cartId: cart.id,
            cartValue: cart.totalValue
          }
        })
      });
      
      // Mark cart as processed
      await markCartProcessed(cart.id);
      
    } catch (error) {
      console.error(`Error processing abandoned cart ${cart.id}:`, error);
    }
  }
}
```

**Seasonal Promotions**

Create limited-time campaigns for holidays and special events:

1. Design themed digital collectibles or coupons
2. Set campaign start and end dates
3. Create urgency with limited quantities
4. Promote across email, social media, and your website
5. Track redemption rates compared to normal promotions

**Integration Tips**

* Connect Giftoin with your CRM to personalize rewards
* Use order data to segment customers and tailor rewards
* A/B test different reward types to optimize conversion
* Implement reward progress indicators at checkout
* Create exclusive membership tiers with special rewards


# Games

#### Gaming Rewards & Achievements

Enhance player engagement and retention in your games with strategic rewards and achievements.

**Daily Login Rewards**

Reward players for logging in consecutively:

```lua
-- Roblox example for daily rewards
local GiftoinModule = require(ServerScriptService:WaitForChild("GiftoinModule"))
local GiftoinEvents = GiftoinModule.Events

-- Track player logins
local function onPlayerJoin(player)
    local userId = tostring(player.UserId)
    local lastLogin = getLastLoginTime(userId)
    local currentTime = os.time()
    
    -- Check if this is a new daily login
    if isNewDay(lastLogin, currentTime) then
        -- Increment streak counter
        local streak = incrementLoginStreak(userId)
        
        -- Award points based on streak length
        local pointsToAward = calculateStreakPoints(streak)
        GiftoinEvents.sendPoints(player, "daily_login", pointsToAward)
        
        -- On milestone days, send special gifts
        if streak == 7 then
            -- Weekly milestone reward
            GiftoinEvents.sendSpecialReward(player, "weekly_milestone")
        elseif streak == 30 then
            -- Monthly milestone reward
            GiftoinEvents.sendSpecialReward(player, "monthly_milestone")
        end
        
        -- Update last login time
        updateLastLoginTime(userId, currentTime)
    end
end

-- Connect to PlayerAdded event
game.Players.PlayerAdded:Connect(onPlayerJoin)
```

**Achievement Systems**

Create a comprehensive achievement system:

1. Define achievement categories:
   * Progression (completing levels, reaching milestones)
   * Collection (gathering items, completing sets)
   * Skill (mastering game mechanics, setting records)
   * Social (team play, community participation)
2. Design a reward structure:
   * Digital collectibles for visual achievements
   * In-game currency or items for functional rewards
   * Status badges for social recognition
   * Access to exclusive content or features
3. Implementation example:

```javascript
// Track achievement progress and award when completed
function updateAchievementProgress(userId, achievementId, progress) {
  // Get current progress
  const currentProgress = getUserAchievementProgress(userId, achievementId);
  const achievement = getAchievementDetails(achievementId);
  
  // Update progress
  const newProgress = currentProgress + progress;
  saveUserAchievementProgress(userId, achievementId, newProgress);
  
  // Check if achievement is completed
  if (newProgress >= achievement.targetValue && !isAchievementCompleted(userId, achievementId)) {
    // Mark as completed
    markAchievementCompleted(userId, achievementId);
    
    // Send Giftoin reward
    sendAchievementReward(userId, achievementId);
  }
}

// Send the reward through Giftoin
async function sendAchievementReward(userId, achievementId) {
  const achievement = getAchievementDetails(achievementId);
  const userEmail = getUserEmail(userId);
  
  try {
    const response = await fetch(`https://api.giftoin.org/api/v1/gcm/reseller/campaign/${achievement.campaignId}/order`, {
      method: 'POST',
      headers: {
        'x-gft_api_key': 'YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        contacts: [userEmail],
        title: `Achievement Unlocked: ${achievement.name}`,
        description: achievement.rewardDescription,
        metadata: {
          achievementId: achievementId,
          userId: userId
        }
      })
    });
    
    // Notify the user in-game
    notifyUserOfAchievement(userId, achievementId);
    
  } catch (error) {
    console.error(`Error sending achievement reward for ${achievementId}:`, error);
    // Handle error - queue for retry
  }
}
```

**Player Retention Strategies**

* Create progression systems with increasing rewards
* Implement surprise gifts for reaching milestones
* Design limited-time events with exclusive rewards
* Create collection mechanics that encourage completionism
* Implement leaderboards with periodic rewards
* Use rewards to guide players to underutilized game features

**Analytics and Optimization**

Track these metrics to optimize your gaming rewards:

* Redemption rates by reward type
* Player retention lift from reward programs
* Session frequency and duration changes
* Social sharing of achievements
* Conversion impact on in-game purchases


# Support

We're here to help you successfully integrate and use the Giftoin platform. \
Here's how to get assistance when you need it.

## Help Resources

Before contacting support, check these resources:

1. **Documentation** - You're looking at it! Most questions are answered here.
2. **API Reference** - Detailed information about each endpoint and parameter.
3. **Troubleshooting Guide** - Solutions to common issues.
4. **FAQ** - Answers to frequently asked questions.

### Contact Support

If you can't find a solution in our documentation, reach out to our support team:

### **Email Support**

Send detailed information about your issue to <support@giftoin.com>. Please include:

* Your account email
* Description of the issue
* Steps to reproduce
* Any error messages or codes
* Screenshots if applicable

We typically respond within 24 business hours.

### **Discord Support**

All customers have access to our Discord community support channels where issues can be submitted and tracked.

Advanced & Professional customers receive enhanced support through private dedicated Discord channels, providing direct access to our support team and quicker response time.

### Feature Requests

Have an idea to improve Giftoin? We'd love to hear it!

Submit feature requests through your dashboard:

1. Click on "Support" in the navigation menu
2. Select "Feature Request"
3. Describe your idea and how it would benefit your use case

Our product team reviews all requests and prioritizes based on customer demand and strategic alignment.

### Support Plans

| Feature                   | Basic    | Advanced | Professional  |
| ------------------------- | -------- | -------- | ------------- |
| Email Support             | ✓        | ✓        | ✓             |
| Discord Support           | ✓        | ✓        | ✓             |
| Response Time             | 48 hours | 24 hours | 4 hours       |
| Dedicated Discord Channel | ✗        | ✓        | ✓             |
| Dedicated Agent           | ✗        | ✗        | ✓             |
| Implementation Assistance | ✗        | Limited  | Comprehensive |

To upgrade your support plan, contact our sales team at <sales@giftoin.com>.

### Security Issues

If you discover a security vulnerability, please do NOT report it through the standard support channels. Instead, email <security@giftoin.com> with details of the issue.

We take security seriously and will respond promptly to all legitimate security concerns.

### Providing Feedback

Your feedback helps us improve! After resolving a support ticket, you'll receive a satisfaction survey. Please take a moment to let us know how we did and how we can serve you better in the future.

We also conduct quarterly customer experience surveys to gather more comprehensive feedback about our platform and support services.


# Supported Chains

| Network Name | Network Type |
| ------------ | ------------ |
| Polygon      | `Mainnet`    |
| Amoy         | `Testnet`    |
| Ethereum     | `Mainnet`    |
| Sepolia      | `Testnet`    |
| BNB          | `Mainnet`    |
| BNB Testnet  | `Testnet`    |


