Flip a coin — embed and API integration example

Embed & API: Integrate Coin Flips Into Apps & Giveaways

By FlipACoinFree Team11 min read

Embed & API: Integrate Coin Flips Into Apps & Giveaways

Want to add coin flip functionality to your website, app, or live stream? Whether you're running online giveaways, building a decision-making tool, or need randomization for your application, integrating a coin flip is easier than you think.

In this comprehensive guide, we'll show you how to embed coin flips on your site, use our API for programmatic access, run bulk flips for contests, and ensure fair, auditable results for any use case.

Why Embed a Coin Flip on Your Site or Stream?

Live Streaming and Content Creation

Streamers and content creators use embedded coin flips for:

  • Viewer interaction: Let chat decide game choices
  • Giveaway selection: Fair, transparent winner selection
  • Challenge triggers: Random events based on coin flips
  • Betting games: Viewers predict outcomes for points
  • Content variety: Add unpredictability to streams

Contest and Giveaway Pages

Businesses and influencers embed flips for:

  • Fair winner selection: Transparent, unbiased results
  • Tie-breakers: Quick resolution for tied entries
  • Random drawings: Select from multiple participants
  • Instant results: No waiting, immediate outcomes
  • Proof of fairness: Shareable, verifiable results

Educational Websites

Teachers and educational platforms use embeds for:

  • Interactive lessons: Students flip coins in real-time
  • Probability experiments: Collect data from multiple flips
  • Homework tools: Practice problems with built-in randomization
  • Classroom games: Embedded directly in learning management systems

Sports and Gaming Sites

Sports sites and gaming platforms integrate flips for:

  • Match coin toss: Official pre-game coin flip
  • Tournament brackets: Random seeding or matchups
  • Fantasy sports: Draft order determination
  • Betting simulations: Practice with virtual coin flips

Decision-Making Tools

Apps and websites use coin flips for:

  • Yes/no decisions: Quick binary choices
  • Option selection: Choose between two alternatives
  • Random selection: Pick from a list of items
  • Tie-breaking: Resolve deadlocks in voting or selection

Quick Embed — Copy-Paste Iframe & JS SDK

Method 1: Simple Iframe Embed

The easiest way to embed coin flip widget is with an iframe. Just copy and paste this code:

<iframe 
  src="https://flipacoinfree.com/embed" 
  width="360" 
  height="420" 
  title="Flip a coin"
  frameborder="0"
  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>

Customization Options:

Add URL parameters to customize the embed:

<iframe 
  src="https://flipacoinfree.com/embed?theme=dark&sound=1&autoflip=0" 
  width="360" 
  height="420" 
  title="Flip a coin">
</iframe>

Available Parameters:

| Parameter | Values | Description | |-----------|--------|-------------| | theme | light, dark | Color scheme | | sound | 0, 1 | Enable/disable sound | | autoflip | 0, 1 | Auto-flip on load | | preset | preset ID | Load custom coin design | | hidehistory | 0, 1 | Hide flip history | | hidecontrols | 0, 1 | Hide control buttons |

Example with Multiple Parameters:

<iframe 
  src="https://flipacoinfree.com/embed?theme=dark&sound=1&hidehistory=1" 
  width="360" 
  height="420" 
  title="Flip a coin - dark theme with sound">
</iframe>

Method 2: JavaScript SDK

For more control and integration with your site's functionality, use our JavaScript SDK:

<!-- Include the SDK -->
<script src="https://flipacoinfree.com/sdk.js"></script>

<!-- Create a container -->
<div id="coin-flip-container"></div>

<!-- Initialize the coin flip -->
<script>
  FlipACoinFree.init({
    container: '#coin-flip-container',
    theme: 'dark',
    sound: true,
    onFlip: function(result) {
      console.log('Coin landed on:', result);
      // Your custom logic here
    }
  });
</script>

SDK Configuration Options:

FlipACoinFree.init({
  container: '#coin-flip-container',  // CSS selector for container
  theme: 'light',                      // 'light' or 'dark'
  sound: true,                         // Enable sound effects
  autoFlip: false,                     // Auto-flip on load
  preset: null,                        // Custom coin preset ID
  showHistory: true,                   // Show flip history
  showControls: true,                  // Show control buttons
  onFlip: function(result) {           // Callback when flip completes
    // result is 'heads' or 'tails'
  },
  onReady: function() {                // Callback when widget loads
    // Widget is ready
  }
});

Programmatic Control:

// Trigger a flip programmatically
FlipACoinFree.flip();

// Get flip history
const history = FlipACoinFree.getHistory();

// Clear history
FlipACoinFree.clearHistory();

// Change theme dynamically
FlipACoinFree.setTheme('dark');

// Enable/disable sound
FlipACoinFree.setSound(true);

Method 3: WordPress Plugin

For WordPress users, we offer a dedicated plugin:

  1. Install "Flip A Coin Free" plugin from WordPress directory
  2. Add shortcode to any page or post: [flipacoin]
  3. Customize with shortcode attributes:
[flipacoin theme="dark" sound="true" width="360"]

Coin Flip API — Sample Requests & Use Cases

For developers building applications, our coin flip API provides programmatic access to coin flip functionality.

API Endpoint

POST https://flipacoinfree.com/api/flip

Authentication

Include your API key in the request header:

Authorization: Bearer YOUR_API_KEY

Get your free API key by signing up at flipacoinfree.com/api-docs.

Basic Request (JavaScript)

fetch('https://flipacoinfree.com/api/flip', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    count: 1,
    weighted: false
  })
})
.then(response => response.json())
.then(data => {
  console.log('Result:', data.result);  // 'heads' or 'tails'
  console.log('Timestamp:', data.timestamp);
})
.catch(error => console.error('Error:', error));

Basic Request (Python)

import requests
url = 'https://flipacoinfree.com/api/flip'
headers = {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
}
data = {
    'count': 1,
    'weighted': False
}

response = requests.post(url, headers=headers, json=data)
result = response.json()

print(f"Result: {result['result']}")
print(f"Timestamp: {result['timestamp']}")

Request Parameters

| Parameter | Type | Required | Description | |-----------|------|----------|-------------| | count | integer | No | Number of flips (1-1000), default: 1 | | weighted | boolean | No | Use weighted flip, default: false | | probability | float | No | Heads probability (0.0-1.0), default: 0.5 | | preset | string | No | Custom coin preset ID | | metadata | object | No | Custom data to attach to flip |

Response Format

{
  "success": true,
  "result": "heads",
  "timestamp": "2025-10-10T14:30:00Z",
  "flipId": "abc123xyz",
  "metadata": {
    "count": 1,
    "weighted": false,
    "probability": 0.5
  }
}

Multiple Flips Request

fetch('https://flipacoinfree.com/api/flip', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    count: 10
  })
})
.then(response => response.json())
.then(data => {
  console.log('Results:', data.results);  // Array of 10 results
  console.log('Summary:', data.summary);  // { heads: 6, tails: 4 }
});

Weighted Flip Request

fetch('https://flipacoinfree.com/api/flip', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    count: 1,
    weighted: true,
    probability: 0.7  // 70% chance of heads
  })
})
.then(response => response.json())
.then(data => {
  console.log('Result:', data.result);
});

Rate Limits

  • Free tier: 100 requests per hour
  • Basic tier: 1,000 requests per hour
  • Pro tier: 10,000 requests per hour
  • Enterprise: Custom limits available Exceeded rate limits return HTTP 429 with retry-after header.

Error Handling

fetch('https://flipacoinfree.com/api/flip', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ count: 1 })
})
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return response.json();
})
.then(data => {
  console.log('Success:', data);
})
.catch(error => {
  console.error('Error:', error);
  // Handle error appropriately
});

Bulk Flips, Giveaways & Sports Integration

Bulk Flip Endpoint

For running large numbers of flips (contests, simulations, data collection):

POST https://flipacoinfree.com/api/batchflip

Request:

fetch('https://flipacoinfree.com/api/batchflip', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    count: 1000,
    exportFormat: 'csv'
  })
})
.then(response => response.json())
.then(data => {
  console.log('Batch ID:', data.batchId);
  console.log('Download URL:', data.downloadUrl);
});

Response:

{
  "success": true,
  "batchId": "batch_abc123",
  "count": 1000,
  "summary": {
    "heads": 503,
    "tails": 497
  },
  "downloadUrl": "https://flipacoinfree.com/api/download/batch_abc123.csv",
  "expiresAt": "2025-10-11T14:30:00Z"
}

Giveaway Integration Example

Here's a complete example for running a fair giveaway:

// Step 1: Get list of participants
const participants = [
  'user1@example.com',
  'user2@example.com',
  'user3@example.com',
  // ... more participants
];

// Step 2: Assign each participant to heads or tails
const headsGroup = participants.filter((_, i) => i % 2 === 0);
const tailsGroup = participants.filter((_, i) => i % 2 === 1);

// Step 3: Flip the coin
fetch('https://flipacoinfree.com/api/flip', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    count: 1,
    metadata: {
      giveaway: 'Summer Contest 2025',
      participants: participants.length
    }
  })
})
.then(response => response.json())
.then(data => {
  // Step 4: Determine winners
  const winners = data.result === 'heads' ? headsGroup : tailsGroup;
  
  // Step 5: Select random winner from winning group
  const finalWinner = winners[Math.floor(Math.random() * winners.length)];
  
  console.log('Winning side:', data.result);
  console.log('Winner:', finalWinner);
  console.log('Flip ID for verification:', data.flipId);
  
  // Step 6: Log for audit trail
  logGiveawayResult({
    flipId: data.flipId,
    winner: finalWinner,
    timestamp: data.timestamp
  });
});

Sports Coin Toss Integration

For sports websites implementing official coin tosses:

async function conductSportsCoinToss(team1, team2) {
  // Step 1: Display teams
  console.log(`Coin toss between ${team1} and ${team2}`);
  
  // Step 2: Conduct flip
  const response = await fetch('https://flipacoinfree.com/api/flip', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      count: 1,
      metadata: {
        team1: team1,
        team2: team2,
        event: 'Pre-game coin toss'
      }
    })
  });
  
  const data = await response.json();
  
  // Step 3: Determine winner
  const winner = data.result === 'heads' ? team1 : team2;
  const loser = data.result === 'heads' ? team2 : team1;
  
  // Step 4: Return results
  return {
    result: data.result,
    winner: winner,
    loser: loser,
    flipId: data.flipId,
    timestamp: data.timestamp
  };
}

// Usage
conductSportsCoinToss('Team A', 'Team B')
  .then(result => {
    console.log(`${result.winner} wins the toss!`);
    console.log(`Flip ID: ${result.flipId}`);
  });

Tournament Bracket Generation

Use bulk flips to generate random tournament brackets:

async function generateTournamentBracket(teams) {
  // Flip for each matchup
  const matchups = [];
  
  for (let i = 0; i < teams.length; i += 2) {
    const response = await fetch('https://flipacoinfree.com/api/flip', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        count: 1,
        metadata: {
          matchup: `${teams[i]} vs ${teams[i+1]}`
        }
      })
    });
    
    const data = await response.json();
    const winner = data.result === 'heads' ? teams[i] : teams[i+1];
    
    matchups.push({
      team1: teams[i],
      team2: teams[i+1],
      winner: winner,
      flipId: data.flipId
    });
  }
  
  return matchups;
}

Security, Logging & Audit Trails

Ensuring Fair Results

For contests and giveaways, transparency is crucial:

1. Use Verifiable Flip IDs

Every API flip returns a unique flipId that can be verified:

// Store the flip ID
const flipId = data.flipId;

// Later, verify the flip
fetch(`https://flipacoinfree.com/api/verify/${flipId}`)
  .then(response => response.json())
  .then(verification => {
    console.log('Verified result:', verification.result);
    console.log('Timestamp:', verification.timestamp);
    console.log('Metadata:', verification.metadata);
  });

2. Enable Public Verification

Generate a public verification link for participants:

const verificationUrl = `https://flipacoinfree.com/verify/${flipId}`;
console.log('Verify this flip at:', verificationUrl);

3. Export Complete Audit Logs

Download CSV of all flips for your account:

fetch('https://flipacoinfree.com/api/export', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY'
  }
})
.then(response => response.blob())
.then(blob => {
  // Download CSV file
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'flip-audit-log.csv';
  a.click();
});

Privacy and Data Handling

We take privacy seriously:

  • No personal data required: Flips don't require user accounts
  • Optional metadata: You control what data is attached to flips
  • Automatic deletion: Flip data deleted after 90 days (or sooner on request)
  • GDPR compliant: Full data export and deletion available
  • No tracking: We don't track users across sites

Preventing Fraud in Giveaways

Best practices for fair giveaways:

1. Announce Method in Advance

  • Tell participants you'll use a coin flip
  • Share the verification URL format
  • Explain how winners will be selected

2. Conduct Flips Publicly

  • Live stream the flip if possible
  • Share flip ID immediately after
  • Allow real-time verification

3. Use Metadata for Transparency

  • Include giveaway name in metadata
  • Record participant count
  • Timestamp the flip

4. Provide Audit Trail

  • Export flip history
  • Share CSV with participants
  • Keep records for disputes

API Security Best Practices

Protect your API key:

Don't:

  • ❌ Expose API key in client-side code
  • ❌ Commit API key to public repositories
  • ❌ Share API key publicly

Do:

  • ✅ Store API key in environment variables
  • ✅ Use server-side API calls only
  • ✅ Rotate keys regularly
  • ✅ Use separate keys for development and production

Example (Node.js):

// Store in .env file
// FLIPACOIN_API_KEY=your_key_here

// Access in code
const apiKey = process.env.FLIPACOIN_API_KEY;

// Never expose in client code
fetch('https://flipacoinfree.com/api/flip', {
  headers: {
    'Authorization': `Bearer ${apiKey}`  // This runs on server only
  }
});

Final Thoughts & Next Steps

Integrating coin flip functionality into your website, app, or workflow is straightforward with our embed options and API. Whether you need a simple iframe for your blog or a full API integration for a complex application, we've got you covered.

The combination of easy embedding, powerful API access, bulk flip capabilities, and transparent audit trails makes FlipACoinFree the perfect choice for any project requiring fair, verifiable randomization.

Ready to get started?

  1. Try the embed demo: Visit embed coin flip widget to test different embed options
  2. Get your API key: Sign up at coin flip API for free API access
  3. Read the full docs: Comprehensive documentation with more examples and use cases
  4. Request custom branding: Contact us for white-label embed options

Need help? Our developer community and support team are here to assist. Join our Discord or email support@flipacoinfree.com.

Key Takeaways:

  • Embed with simple iframe or advanced JavaScript SDK
  • API provides programmatic access with flexible options
  • Bulk flips perfect for giveaways, contests, and data collection
  • Verification and audit trails ensure transparency
  • Rate limits and security features protect your integration
  • Free tier available for testing and small projects

Start integrating today and bring fair, transparent randomization to your users!