> ## Documentation Index
> Fetch the complete documentation index at: https://docs.snagsolutions.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Connect social accounts

> Learn how to integrate social media platforms with your users using Snag's OAuth flow or by passing social handles directly

<head>
  <script type="application/ld+json">
    {JSON.stringify({
            "@context": "https://schema.org",
            "@graph": [
              {
                "@type": "HowTo",
                "name": "Connect social accounts",
                "description": "Learn how to integrate social media platforms with your users using Snag's OAuth flow or by passing social handles directly",
                "step": [
                  {"@type": "HowToStep", "name": "Choose an integration method", "text": "Decide between using Snag's built-in OAuth flow or passing social handles directly via the metadata endpoint."},
                  {"@type": "HowToStep", "name": "Generate OAuth URL", "text": "Call Snag's API to get an authentication URL for the social platform you want to connect."},
                  {"@type": "HowToStep", "name": "Redirect user to authorize", "text": "Send the user to the OAuth URL where they authorize the connection on the social platform."},
                  {"@type": "HowToStep", "name": "Handle the callback", "text": "Snag redirects back to your application. Verify the connection was successful by checking the user metadata."},
                  {"@type": "HowToStep", "name": "Use connected accounts in loyalty rules", "text": "Once connected, use social accounts in loyalty rules for follow verification, role checks, and engagement tracking."}
                ]
              },
              {
                "@type": "BreadcrumbList",
                "itemListElement": [
                  {"@type": "ListItem", "position": 1, "name": "Home", "item": "https://docs.snagsolutions.io/welcome"},
                  {"@type": "ListItem", "position": 2, "name": "Loyalty", "item": "https://docs.snagsolutions.io/loyalty/loyalty-overview"},
                  {"@type": "ListItem", "position": 3, "name": "Development", "item": "https://docs.snagsolutions.io/loyalty/development/getting-started"},
                  {"@type": "ListItem", "position": 4, "name": "Connect social accounts"}
                ]
              }
            ]
          })}
  </script>
</head>

After creating users and managing user groups, the next step is to connect social media accounts. Snag provides two methods for integrating social accounts: using Snag's OAuth flow or passing social handles directly.

## Overview

Social account integration enables enhanced loyalty features like:

* Social media verification rules
* Cross-platform engagement tracking
* Enhanced user profiles
* Automated social media tasks

## Supported Social Platforms

Snag supports connecting the following social platforms:

* **Twitter/X** - Follow accounts, post tweets, verify bio content
* **Discord** - Join servers, verify roles, track messages
* **Telegram** - Join channels, verify messages
* **Epic Games** - Verify game ownership and achievements
* **Steam** - Verify game library and wishlist
* **Google** - Verify email address
* **TikTok** - Verify TikTok account
* **Email** - Verify email address

## Method 1: Snag OAuth Flow

This method lets Snag handle the entire OAuth process, providing a seamless user experience.

### How It Works

1. **Generate OAuth URL**: Call Snag's API to get an authentication URL
2. **Redirect User**: Send the user to the OAuth URL
3. **User Authorization**: User authorizes the connection on the social platform
4. **Callback Handling**: Snag redirects back to your application
5. **Verification**: Confirm the connection was successful

### Implementation

#### Step 1: Generate OAuth URL

<RequestExample>
  ```bash cURL theme={null}
  curl -X GET 'https://admin.snagsolutions.io/api/twitter/auth?userId=user-id&redirectUri=https://yourapp.com/callback' \
    -H 'x-api-key: your-api-key-here'
  ```
</RequestExample>

<ResponseExample>
  ```json Success theme={null}
  {
    "url": "https://auth-provider.com/oauth/authorize?client_id=xxx&redirect_uri=xxx&state=xxx"
  }
  ```
</ResponseExample>

#### Step 2: Redirect User

```javascript theme={null}
// Server-side code to initiate the flow
app.get('/connect-twitter', async (req, res) => {
  try {
    const userId = req.query.userId
    const redirectUri = 'https://yourapp.com/callback'

    const response = await fetch(
      `https://admin.snagsolutions.io/api/twitter/auth?userId=${userId}&redirectUri=${redirectUri}`,
      {
        headers: {
          'x-api-key': process.env.SNAG_API_KEY,
        },
      }
    )

    const data = await response.json()

    // Redirect user to the OAuth URL
    res.redirect(data.url)
  } catch (error) {
    console.error('Error connecting Twitter account:', error)
    res.status(500).send('Error connecting Twitter account')
  }
})
```

#### Step 3: Handle Callback

```javascript theme={null}
// Handle the callback from Snag
app.get('/callback', async (req, res) => {
  const { code, state, userId } = req.query

  try {
    // Verify the connection was successful
    const user = await client.users.getMetadata(userId)

    if (user.twitterUser) {
      res.send('Twitter account connected successfully!')
    } else {
      res.send('Failed to connect Twitter account')
    }
  } catch (error) {
    console.error('Error verifying connection:', error)
    res.status(500).send('Error verifying connection')
  }
})
```

### Client-Side Integration

```javascript theme={null}
// Client-side code to initiate the flow
function connectTwitterAccount(userId) {
  // Redirect to your server endpoint
  window.location.href = `/connect-twitter?userId=${userId}`
}

// Example button click handler
document.getElementById('connect-twitter-btn').addEventListener('click', () => {
  connectTwitterAccount('user-123')
})
```

## Method 2: Direct Social Handle Passing

If you control the OAuth flow in your application, you can pass social handles directly to Snag using the metadata endpoint.

### Implementation

```javascript theme={null}
import SnagSolutions from '@snagsolutions/sdk'

const client = new SnagSolutions({
  apiKey: 'your-api-key-here',
})

// After your OAuth flow completes, update user metadata
const updatedUser = await client.users.createMetadata({
  walletAddress: '0x1234567890abcdef1234567890abcdef12345678',
  twitterUser: 'user_twitter_handle',
  twitterUserId: 'user_twitter_id',
  discordUser: 'user_discord_username',
  discordUserId: 'user_discord_id',
  telegramUsername: 'user_telegram_username',
  telegramUserId: 'user_telegram_id',
})
```

### Example: Custom OAuth Implementation

```javascript theme={null}
// Your custom OAuth flow
async function handleTwitterOAuth(code) {
  // Your OAuth implementation
  const twitterData = await exchangeCodeForToken(code)
  const userInfo = await getTwitterUserInfo(twitterData.access_token)

  // Pass the Twitter handle to Snag
  await client.users.createMetadata({
    walletAddress: currentUser.walletAddress,
    twitterUser: userInfo.username,
  })

  console.log('Twitter handle updated in Snag')
}
```

## Platform-Specific Endpoints

### Twitter/X

```javascript theme={null}
// Generate Twitter OAuth URL
const twitterAuth = await client.social.twitter.auth({
  userId: 'user-id',
  redirectUri: 'https://yourapp.com/callback',
})
```

### Discord

```javascript theme={null}
// Generate Discord OAuth URL
const discordAuth = await client.social.discord.auth({
  userId: 'user-id',
  redirectUri: 'https://yourapp.com/callback',
})
```

### Telegram

```javascript theme={null}
// Generate Telegram OAuth URL
const telegramAuth = await client.social.telegram.auth({
  userId: 'user-id',
  redirectUri: 'https://yourapp.com/callback',
})
```

## Custom OAuth Applications

Snag allows you to use your own OAuth applications for **Twitter**, **Discord**, **Epic Games**, and **Steam** integrations. This enables you to maintain your brand identity throughout the authentication flow.

<Tip>
  Contact the Snag team for integration support if you want to use your own OAuth applications.
</Tip>

### Required Redirect URLs

Add these redirect URLs to your OAuth application:

* `https://snag-render.com/api/twitter/auth/callback`
* `https://snag-render.com/api/discord/auth/callback`
* `https://snag-render.com/api/epic/auth/callback`
* `https://snag-render.com/api/steam/auth/callback`

## Error Handling

### Common Issues

<AccordionGroup>
  <Accordion title="OAuth Flow Errors">
    * **Invalid redirect URI**: Ensure your redirect URI matches exactly
    * **Expired authorization**: OAuth codes expire quickly, handle them promptly
    * **User cancellation**: Handle cases where users cancel the authorization
  </Accordion>

  <Accordion title="Social Handle Conflicts">
    * **Duplicate handles**: Check if a social handle is already connected to another user
    * **Invalid handles**: Verify social handles are in the correct format
    * **Platform-specific errors**: Handle platform-specific error responses
  </Accordion>
</AccordionGroup>

### Error Handling Example

```javascript theme={null}
try {
  const response = await client.social.twitter.auth({
    userId: 'user-id',
    redirectUri: 'https://yourapp.com/callback',
  })

  // Redirect user to OAuth URL
  window.location.href = response.url
} catch (error) {
  if (error.status === 400) {
    console.error('Invalid parameters:', error.message)
  } else if (error.status === 403) {
    console.error('API key invalid or expired')
  } else {
    console.error('Unexpected error:', error)
  }
}
```

## Best Practices

<Tip>
  **User Experience**: Use Snag's OAuth flow for a seamless experience, or implement your own for complete control.
</Tip>

<Tip>
  **Error Handling**: Always handle OAuth errors gracefully and provide clear feedback to users.
</Tip>

<Tip>
  **Security**: Never expose API keys in client-side code. Always handle OAuth flows server-side.
</Tip>

<Warning>
  **Rate Limits**: Be mindful of API rate limits when processing multiple social connections.
</Warning>

## Integration with Loyalty Rules

Once social accounts are connected, they can be used in loyalty rules:

* **Twitter Follow**: Verify users follow specific accounts
* **Discord Role**: Check if users have specific server roles
* **Telegram Join**: Verify users joined specific channels
* **Social Verification**: Use social accounts as proof of identity

<Info>
  For detailed information on social account management, see our [Managing
  Social Accounts](/loyalty/managing-social-accounts) guide.
</Info>

## Next Steps

Now that you can connect social accounts, you're ready to:

<Card title="Create Loyalty Rules" icon="star" href="/loyalty/create-your-first-rule">
  Start building loyalty programs with social media integration.
</Card>
