Show Your First Ad

Learn how to display rewarded video ads and handle user rewards. This guide covers the complete ad flow from button click to reward distribution.

The Ad Flow

Understanding the rewarded ad flow is crucial for a smooth user experience:

1
User clicks button → "Watch Ad for 100 Coins"
2
SDK requests ad → From BZZE Ads server
3
Video player opens → Fullscreen overlay
4
User watches video → Must watch 80% minimum
5
Reward granted → Your onReward callback fires

Basic Implementation

Here's the simplest way to show an ad:

JavaScript - Minimal Example
// Initialize SDK (do this once on page load)
RewardedAd.init({
    appId: "YOUR_APP_ID",
    apiKey: "YOUR_API_KEY",
    userId: "user_12345",
    
    onReward: function(reward) {
        // THIS IS WHERE YOU GRANT THE REWARD
        alert('You earned 100 coins!');
        addCoinsToUserBalance(100);
    }
});

// Show ad when user clicks button
function showRewardedAd() {
    RewardedAd.showAd({
        rewardPreview: "100 coins"
    });
}

Complete Working Example

Here's a full HTML file you can test immediately:

HTML - Copy & Test
<!DOCTYPE html>
<html>
<head>
    <title>My Game</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 2rem;
        }
        #coinBalance {
            font-size: 2rem;
            color: #f59e0b;
            margin: 2rem 0;
        }
        button {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 1rem 2rem;
            font-size: 1.1rem;
            border-radius: 8px;
            cursor: pointer;
        }
        button:hover {
            transform: scale(1.05);
        }
    </style>
</head>
<body>
    <h1>🎮 My Awesome Game</h1>
    <div id="coinBalance">💰 Coins: 0</div>
    <button onclick="watchAdForCoins()">Watch Ad for 100 Coins</button>

    <script src="https://ads.bzze.com/sdk/rewarded.min.js"></script>
    <script>
        let coins = 0;

        // Initialize SDK
        RewardedAd.init({
            appId: "APP_1760726660483_6ohdjjgqm",
            apiKey: "bzze_fgpwe6uofk9",
            userId: "user_" + Math.random().toString(36).substr(2, 9),
            
            onReward: function(reward) {
                // Grant reward
                coins += 100;
                document.getElementById('coinBalance').textContent = '💰 Coins: ' + coins;
                alert('🎉 You earned 100 coins!');
            },
            
            onNoFill: function() {
                alert('😔 No ads available right now. Try again later!');
            },
            
            onError: function(error) {
                alert('❌ Error: ' + error.message);
            }
        });

        function watchAdForCoins() {
            RewardedAd.showAd({
                rewardPreview: "100 coins"
            });
        }
    </script>
</body>
</html>
✅ Try it now! Save this code as test.html and open it in your browser. Click the button to see a real ad!

Handling All Scenarios

Real-world apps need to handle multiple scenarios. Here's a production-ready implementation:

JavaScript - Production Ready
RewardedAd.init({
    appId: "YOUR_APP_ID",
    apiKey: "YOUR_API_KEY",
    userId: getCurrentUserId(),
    
    // User completed ad and earned reward
    onReward: function(reward) {
        console.log('Reward earned!', reward);
        grantUserReward(100, 'coins');
        showSuccessMessage('You earned 100 coins!');
    },
    
    // No ads available (low fill rate)
    onNoFill: function() {
        console.log('No ads available');
        showErrorMessage('No ads available right now. Try again in a few minutes!');
    },
    
    // User closed ad before completion
    onClose: function() {
        console.log('User closed ad');
        showInfoMessage('Watch the full ad to earn your reward!');
    },
    
    // Ad was shown successfully
    onAdShown: function() {
        console.log('Ad is now playing');
        pauseGameAudio(); // Pause game sounds
    },
    
    // User clicked on ad (rare, but trackable)
    onAdClicked: function() {
        console.log('User clicked ad');
        // Track engagement if needed
    },
    
    // Error occurred
    onError: function(error) {
        console.error('Ad error:', error);
        
        if (error.code === 'RATE_LIMIT_EXCEEDED') {
            showErrorMessage('You\'ve watched too many ads. Wait ' + error.remainingSeconds + ' seconds.');
        } else if (error.code === 'INVALID_CREDENTIALS') {
            showErrorMessage('Configuration error. Please contact support.');
        } else {
            showErrorMessage('Something went wrong. Try again later!');
        }
    }
});

Controlling the Button

Dynamically enable/disable your button based on ad availability:

JavaScript - Smart Button Control
// Check if ad is ready
function updateAdButton() {
    const button = document.getElementById('watchAdBtn');
    
    if (RewardedAd.isAdAvailable()) {
        button.disabled = false;
        button.textContent = '▶️ Watch Ad for 100 Coins';
        button.style.opacity = '1';
    } else {
        button.disabled = true;
        button.textContent = '⏳ Loading ad...';
        button.style.opacity = '0.5';
    }
}

// Check every 2 seconds
setInterval(updateAdButton, 2000);

// Also check after each ad shown
RewardedAd.init({
    // ... your config ...
    
    onReward: function(reward) {
        grantReward(100);
        updateAdButton(); // Update button state
    },
    
    onClose: function() {
        updateAdButton(); // Update button state
    }
});

Preloading Ads (Recommended)

For the best user experience, preload ads in advance:

JavaScript - With Preloading
RewardedAd.init({
    appId: "YOUR_APP_ID",
    apiKey: "YOUR_API_KEY",
    userId: "user_12345",
    
    // Enable automatic preloading
    autoPreload: true,        // Auto-preload ads
    preloadCount: 2,          // Keep 2 ads ready
    
    // Called when ad is preloaded
    onAdLoaded: function(count) {
        console.log('Ads ready:', count);
        updateAdButton(); // Enable button
    },
    
    onReward: function(reward) {
        grantReward(100);
    }
});

// Now showAd() will be instant!
function watchAd() {
    RewardedAd.showAd({
        rewardPreview: "100 coins"
    });
}
💡 Pro Tip: Preloading reduces wait time from 2-3 seconds to instant. Always use it for better UX!

Common Patterns

Pattern 1: Extra Lives

JavaScript
// Show when player dies
function onPlayerDeath() {
    showContinueModal({
        title: "Game Over!",
        message: "Watch an ad to continue?",
        onYes: function() {
            RewardedAd.showAd({
                rewardPreview: "1 extra life"
            });
        },
        onNo: function() {
            returnToMainMenu();
        }
    });
}

// Grant extra life on reward
RewardedAd.init({
    // ...
    onReward: function() {
        playerLives++;
        resumeGame();
    }
});

Pattern 2: Daily Bonus

JavaScript
// Double daily reward with ad
function claimDailyBonus() {
    const baseReward = 500;
    
    showModal({
        title: "Daily Bonus: 500 Coins",
        message: "Watch an ad to DOUBLE it to 1000 coins?",
        buttons: [
            {
                text: "Watch Ad (1000 coins)",
                onClick: function() {
                    RewardedAd.showAd({
                        rewardPreview: "1000 coins"
                    });
                }
            },
            {
                text: "Claim 500 coins",
                onClick: function() {
                    grantCoins(baseReward);
                }
            }
        ]
    });
}

RewardedAd.init({
    // ...
    onReward: function() {
        grantCoins(1000); // Doubled!
    }
});

Pattern 3: Shop Purchase Discount

JavaScript
// Get discount by watching ad
function unlockDiscount(item) {
    showModal({
        title: "Get 50% OFF!",
        message: "Watch an ad to unlock 50% discount on this item",
        onConfirm: function() {
            RewardedAd.showAd({
                rewardPreview: "50% discount"
            });
        }
    });
}

RewardedAd.init({
    // ...
    onReward: function() {
        applyDiscount(0.5); // 50% off
        showPurchaseModal();
    }
});

Best Practices

  • ✅ Always show reward value: "100 coins", "1 extra life", etc.
  • ✅ Make it optional: Never force ads
  • ✅ Use clear CTAs: "Watch Ad for Reward"
  • ✅ Handle all callbacks: Especially onNoFill and onError
  • ✅ Preload ads: For instant playback
  • ✅ Pause game audio: During ad playback
  • ❌ Don't spam: Respect frequency caps
  • ❌ Don't hide close button: Users must be able to exit
  • ❌ Don't fake rewards: Only grant on onReward

Testing Your Integration

Before going live, test all scenarios:

  1. Enable debug mode: RewardedAd.enableDebug()
  2. Test successful ad: Watch full ad → verify reward granted
  3. Test early close: Close ad early → verify no reward
  4. Test no fill: Trigger onNoFill scenario
  5. Test rate limits: Watch 10+ ads quickly → verify cooldown
  6. Test on mobile: Verify fullscreen and touch controls work

For a complete testing guide, see Testing Checklist.

Next Steps

showAd() API Reference
Complete method documentation
All Callbacks
Complete callback reference
Debug Mode
Test and troubleshoot