Skip to content

OfferWall SDK Quick Integration Guide

1. Add the Loader Script

Safe Loading Method

Add this code to ensure script loading doesn't block your application and handles CDN availability issues gracefully:

javascript
document.addEventListener('DOMContentLoaded', function() {
  if (!window.loadOfferWallSDK) {
    const script = document.createElement('script');
    script.src = 'https://cdn.giga.pub/script/offer/loader/loader.js';
    script.async = true;
    document.head.appendChild(script);
  }
});

Simpliest Loading Method

Or simply add this to your HTML:

html
<script src="https://cdn.giga.pub/script/offer/loader/loader.js"></script>

2. Initialize the SDK

Handling Asynchronous SDK Loading

The pattern (window.loadGigaSDKCallbacks || (window.loadGigaSDKCallbacks = [])).push(() => {...}) registers a function to be executed after the SDK is fully loaded, even if the script loads asynchronously. This ensures your initialization code runs only when the SDK is available, preventing errors due to missing dependencies.

js
// Initialize SDK
(window.loadGigaSDKCallbacks || (window.loadGigaSDKCallbacks = [])).push(
    () => {
        window.loadOfferWallSDK({
            projectId: 'YOUR_PROJECT_ID' // Replace with your project ID
        })
        .then(sdk => {
            // Save SDK reference
            window.gigaOfferWallSDK = sdk;
            
            // Listen for reward claims
            sdk.on('rewardClaim', async (data) => {
              console.log('Reward claim received:', data);
              
              // Process reward with your backend and get confirmation hash
              const confirmationHash = await verifyWithYourBackend(data);
              
              // Confirm the reward
              if (confirmationHash) {
                sdk.confirmReward(data.rewardId, confirmationHash);
              }
            });
        })
        .catch(error => {
            console.error('Error loading SDK:', error);
        });
    }
);
ts
// Reward claim interface
interface RewardClaim {
  rewardId: string | number;
  userId: string;
  projectId: string | number;
  hash: string;
  amount: number;
  description?: string;
}

// Initialize SDK
(window.loadGigaSDKCallbacks || (window.loadGigaSDKCallbacks = [])).push(
    () => {
      (window as any).loadOfferWallSDK({ 
        projectId: 'YOUR_PROJECT_ID' // Replace with your project ID
      })
      .then((sdk: any) => {
        // Save SDK reference
        (window as any).gigaOfferWallSDK = sdk;
        
        // Listen for reward claims
        sdk.on('rewardClaim', async (data: RewardClaim) => {
          console.log('Reward claim received:', data);
          
          // Process reward with your backend and get confirmation hash
          const confirmationHash = await verifyWithYourBackend(data);
          
          // Confirm the reward
          if (confirmationHash) {
            sdk.confirmReward(data.rewardId, confirmationHash);
          }
        });
      })
      .catch((error: Error) => {
        console.error('Error loading SDK:', error);
      });
});
jsx
import { useEffect, useState } from 'react';

function App() {
  const [offerWallSDK, setOfferWallSDK] = useState(null);
  
  useEffect(() => {
    // Initialize the SDK when component mounts
      (window.loadGigaSDKCallbacks || (window.loadGigaSDKCallbacks = [])).push(
          () => {
              window.loadOfferWallSDK({
                projectId: 'YOUR_PROJECT_ID'
              })
              .then(sdk => {
                // Save SDK reference
                window.gigaOfferWallSDK = sdk;
                setOfferWallSDK(sdk);
                
                // Listen for reward claims
                sdk.on('rewardClaim', async (data) => {
                  console.log('Reward claim received:', data);
                  
                  // Process reward with your backend
                  const confirmationHash = await verifyWithYourBackend(data);
                  
                  // Confirm the reward
                  if (confirmationHash) {
                    sdk.confirmReward(data.rewardId, confirmationHash);
                  }
                });
              })
              .catch(error => {
                console.error('Error loading SDK:', error);
              });
    });
    
    // Clean up event listeners when component unmounts
    return () => {
      if (window.gigaOfferWallSDK) {
        // Optional: clean up event listeners
      }
    };
  }, []); // Empty dependency array means this runs once on mount
  
  // Rest of your component...
}
tsx
import { useEffect, useState } from 'react';

interface RewardClaim {
  rewardId: string | number;
  userId: string;
  projectId: string | number;
  hash: string;
  amount: number;
  description?: string;
}

interface OfferWallSDK {
  open: () => void;
  close: () => void;
  confirmReward: (rewardId: string | number, hash: string) => Promise<boolean>;
  on: (event: string, handler: (data: any) => void) => void;
  off: (event: string, handler: (data: any) => void) => void;
}

function App() {
  const [offerWallSDK, setOfferWallSDK] = useState<OfferWallSDK | null>(null);
  
  useEffect(() => {
    // Initialize the SDK when component mounts
      ((window as any).loadGigaSDKCallbacks || ((window as any).loadGigaSDKCallbacks = [])).push(
          () => {
              (window as any).loadOfferWallSDK({
                  projectId: 'YOUR_PROJECT_ID'
              })
                  .then((sdk: OfferWallSDK) => {
                      // Save SDK reference
                      (window as any).gigaOfferWallSDK = sdk;
                      setOfferWallSDK(sdk);

                      // Listen for reward claims
                      sdk.on('rewardClaim', async (data: RewardClaim) => {
                          console.log('Reward claim received:', data);

                          // Process reward with your backend
                          const confirmationHash = await verifyWithYourBackend(data);

                          // Confirm the reward
                          if (confirmationHash) {
                              sdk.confirmReward(data.rewardId, confirmationHash);
                          }
                      });
                  })
                  .catch((error: Error) => {
                      console.error('Error loading SDK:', error);
                  });
              
          });
    
    // Clean up event listeners when component unmounts
    return () => {
      if ((window as any).gigaOfferWallSDK) {
        // Optional: clean up event listeners
      }
    };
  }, []); // Empty dependency array means this runs once on mount
  
  // Rest of your component...
}

3. Show the OfferWall

Add a button to open the OfferWall:

js
function openOfferWall() {
  if (window.gigaOfferWallSDK) {
    window.gigaOfferWallSDK.open();
  }
}

// Example: Opening on button click
document.getElementById('rewards-button').addEventListener('click', openOfferWall);
ts
function openOfferWall(): void {
  if ((window as any).gigaOfferWallSDK) {
    (window as any).gigaOfferWallSDK.open();
  }
}

// Example: Opening on button click
document.getElementById('rewards-button')?.addEventListener('click', openOfferWall);
jsx
function RewardsButton() {
  const openOfferWall = () => {
    if (window.gigaOfferWallSDK) {
      window.gigaOfferWallSDK.open();
    }
  };
  
  return (
    <button onClick={openOfferWall}>
      Open Rewards
    </button>
  );
}
tsx
const RewardsButton: React.FC = () => {
  const openOfferWall = (): void => {
    if ((window as any).gigaOfferWallSDK) {
      (window as any).gigaOfferWallSDK.open();
    }
  };
  
  return (
    <button onClick={openOfferWall}>
      Open Rewards
    </button>
  );
};

4. Verify Rewards on Backend

Create an endpoint on your backend to verify rewards:

js
// Example backend endpoint (Node.js/Express)
app.post('/verify-reward', (req, res) => {
  const { rewardId, userId, projectId, amount, hash } = req.body;
    const secretKey = process.env.REWARD_SECRET_KEY;
  
  // 1. Verify the hash and check eligibility
  const expectedHash = crypto
        .createHash('sha1')
        .update(`${userId}:${projectId}:${rewardId}:${amount}:${secretKey}`)
        .digest('hex');

  // Verify that the hash matches what we expect
  if (hash !== expectedHash) {
    return res.status(403).json({
        success: false,
        error: 'Invalid hash'
    });
  }

  // Perform additional eligibility checks here
  // - Check if user exists in your system
  // - Check if reward hasn't already been claimed
  // - Apply any business rules for rewards
    
  // 2. Generate confirmation hash
  const confirmationHash = require('crypto')
    .createHash('sha1')
    .update(`${rewardId}:${userId}:${projectId}:${amount}:confirm:${secretKey}`)
    .digest('hex');
  
  // 3. Update user balance in your system
  
  // 4. Return confirmation hash
  res.json({ 
    success: true, 
    confirmationHash 
  });
});
ts
import { Request, Response } from 'express';
import crypto from 'crypto';

interface RewardVerificationRequest {
  rewardId: string | number;
  userId: string;
  projectId: string | number;
  amount: number;
  hash: string;
}

// Example backend endpoint (Node.js/Express with TypeScript)
app.post('/verify-reward', (req: Request, res: Response) => {
  const { rewardId, userId, projectId, amount, hash } = req.body as RewardVerificationRequest;
  
  // 1. Verify the hash and check eligibility
  
  // 2. Generate confirmation hash
  const secretKey = process.env.REWARD_SECRET_KEY as string;
  const confirmationHash = crypto
    .createHash('sha1')
    .update(`${rewardId}:${userId}:${projectId}:${amount}:confirm:${secretKey}`)
    .digest('hex');
  
  // 3. Update user balance in your system
  
  // 4. Return confirmation hash
  res.json({ 
    success: true, 
    confirmationHash 
  });
});

5. Verifying Rewards with Your Backend

js
// Function to verify rewards with your backend
async function verifyWithYourBackend(reward) {
  try {
    const response = await fetch('https://your-api.example.com/verify-reward', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(reward)
    });
    
    const result = await response.json();
    return result.success ? result.confirmationHash : null;
  } catch (error) {
    console.error('Error verifying reward:', error);
    return null;
  }
}
ts
interface RewardClaim {
  rewardId: string | number;
  userId: string;
  projectId: string | number;
  hash: string;
  amount: number;
  description?: string;
}

interface VerificationResponse {
  success: boolean;
  confirmationHash?: string;
  error?: string;
}

// Function to verify rewards with your backend
async function verifyWithYourBackend(reward: RewardClaim): Promise<string | null> {
  try {
    const response = await fetch('https://your-api.example.com/verify-reward', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(reward)
    });
    
    const result: VerificationResponse = await response.json();
    return (result.success && result.confirmationHash) ? result.confirmationHash : null;
  } catch (error) {
    console.error('Error verifying reward:', error);
    return null;
  }
}
jsx
// In a React service or utility file
export async function verifyWithYourBackend(reward) {
  try {
    const response = await fetch('https://your-api.example.com/verify-reward', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(reward)
    });
    
    const result = await response.json();
    return result.success ? result.confirmationHash : null;
  } catch (error) {
    console.error('Error verifying reward:', error);
    return null;
  }
}

// Then in your React component that handles the SDK:
import { verifyWithYourBackend } from './services/rewardService';

// The SDK setup would use this function when handling reward claims
tsx
// In a React service or utility file
import { RewardClaim } from './types';

interface VerificationResponse {
    success: boolean;
    confirmationHash?: string;
    error?: string;
}

export async function verifyWithYourBackend(reward: RewardClaim): Promise<string | null> {
    try {
        const response = await fetch('https://your-api.example.com/verify-reward', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(reward)
        });

        const result: VerificationResponse = await response.json();
        return (result.success && result.confirmationHash) ? result.confirmationHash : null;
    } catch (error) {
        console.error('Error verifying reward:', error);
        return null;
    }
}

// Then in your React component that handles the SDK:
import { verifyWithYourBackend } from './services/rewardService';
import { RewardClaim } from './types';

// The SDK setup would use this function when handling reward claims

That's it!

The basics are:

  1. Add the loader
  2. Initialize with your project ID
  3. Show the OfferWall when needed
  4. Listen for reward claims and confirm them

For more advanced configurations, see the full documentation.