How to retrieve Twitch follower data with PHP using the Twitch API

I’m working on building a follower notification system for Twitch using PHP. I’ve managed to locate the API endpoint that provides follower information, but I’m stuck on the next steps. I need help with parsing the JSON response from the API call and extracting the username data to store it in a PHP variable. The API endpoint I’m using returns the most recent follower information. Can someone guide me through the process of making the API request, decoding the returned data, and properly extracting the follower’s username? Any code examples would be really helpful since I’m still learning how to work with APIs in PHP.

hey! yeah, u gotta use curl to call the API and then json_decode() for decoding the response. don’t forget to include your client-id and bearer token in the headers or it won’t work. after getting the json, u can access the username with $data[‘data’][0][‘from_name’].

Curl works but you’ll hit rate limits fast and deal with token headaches. Been there.

Skip the PHP curl mess. Set up a webhook that fires when you get new followers, then auto-format and store the data wherever you want.

You get real-time notifications without hammering the API. Easy to pipe into databases, Discord, whatever.

I’ve built tons of Twitch integrations this way - way more reliable than manual API calls. Webhooks scale better and handle auth automatically.

Latenode does this well - native Twitch triggers, handles the whole workflow without coding: https://latenode.com

The Problem:

You’re attempting to build a follower notification system for Twitch using PHP, and you’re encountering difficulties with the new Twitch API’s follower endpoint and how to process its JSON response to extract follower usernames. The old follows endpoint has been deprecated, making it challenging to receive real-time follower updates.

:thinking: Understanding the “Why” (The Root Cause):

Twitch has transitioned away from a simple polling approach for follower notifications. The previous follows endpoint is no longer supported. Continuous polling of the API is inefficient, prone to rate limiting, and doesn’t provide real-time updates. The solution lies in using Twitch’s EventSub system, a more efficient and scalable method for receiving real-time notifications.

:gear: Step-by-Step Guide:

  1. Set up EventSub for Channel Follows: This is the core solution to replace the deprecated follows endpoint. EventSub allows Twitch to push notifications to your application whenever a user follows your channel. You’ll need to create a webhook subscription for the channel.follow event type. This involves several key steps:

    • Register your application: Go to the Twitch Developer Console and register your application. You’ll need a Client ID and Secret.
    • Create a Webhook Subscription: Use the Twitch API to subscribe to the channel.follow event. This requires setting up a webhook URL, which is the endpoint your application will listen to receive the notifications. The request body should include the following:
      {
        "type": "webhook_subscription",
        "version": "1",
        "condition": {
          "broadcaster_user_id": "YOUR_BROADCASTER_USER_ID"
        },
        "transport": {
          "method": "webhook",
          "callback": "YOUR_WEBHOOK_URL"
        },
        "event": {
          "type": "channel.follow"
        }
      }
      
      Remember to replace "YOUR_BROADCASTER_USER_ID" with your Twitch user ID and "YOUR_WEBHOOK_URL" with the URL of the endpoint you’ve set up to receive these notifications.
    • Handle the Subscription Confirmation: Twitch will send a confirmation request to your webhook URL. Your application must validate the request and respond with the challenge presented in the body of the confirmation request to successfully complete the subscription process.
    • Handle the channel.follow Event: When a user follows your channel, Twitch will send a notification to your webhook URL. The notification will contain a JSON payload with the user_name of the follower. Your PHP application should be able to parse this JSON data to get the username. An example of a successful channel.follow notification:
      {
        "subscription": {
          "id": "YOUR_SUBSCRIPTION_ID",
          "type": "webhook_subscription",
          "version": "1",
          "status": "enabled",
          "cost": 1,
          "condition": {
            "broadcaster_user_id": "YOUR_BROADCASTER_USER_ID"
          },
          "transport": {
            "method": "webhook",
            "callback": "YOUR_WEBHOOK_URL"
          },
          "event": {
            "type": "channel.follow"
          }
        },
        "event": {
          "user_id": "FOLLOWING_USER_ID",
          "user_login": "FOLLOWING_USERNAME",
          "user_name": "Following User Name",
          "broadcaster_user_id": "YOUR_BROADCASTER_USER_ID",
          "broadcaster_user_login": "YOUR_BROADCASTER_USERNAME",
          "broadcaster_user_name": "Your Broadcaster Name"
        }
      }
      
  2. Process the JSON Response: Your PHP script will receive the JSON payload at your webhook URL. Use json_decode() to parse the data:

    <?php
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (isset($data['event']['user_name'])) {
        $followerUsername = $data['event']['user_name'];
        // Store $followerUsername in your database or wherever you need it
        echo "Success"; //Important to send a 200 OK response.
    } else {
        // Handle errors appropriately
        http_response_code(500);
        echo "Error";
    }
    ?>
    
  3. Store Follower Data: Once you’ve extracted the user_name, store it in your database or use it however your application requires.

:mag: Common Pitfalls & What to Check Next:

  • OAuth 2.0: Ensure you’ve correctly set up the OAuth 2.0 flow to obtain the necessary access token for your application.
  • Webhook URL Validation: Always validate the webhook’s response from Twitch to confirm the subscription is set up correctly.
  • Error Handling: Implement robust error handling to catch issues like network problems and API errors. Pay close attention to HTTP status codes and Twitch’s API documentation for potential errors.
  • Rate Limits: While EventSub significantly reduces the risk of hitting rate limits, be mindful of potential limitations if you are performing other API calls alongside EventSub notifications.
  • Scope Permissions: Make sure you have requested the necessary scope permissions (user:read:email might be needed in some use cases) during the OAuth flow.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Had the same headaches building my first Twitch integration. The main thing is getting Twitch’s auth flow right. Register your app in the Developer Console first - you’ll need the client ID and secret. Then set up OAuth to grab an access token. For requests, use cURL with the right headers - Authorization Bearer token and Client-ID. When you get the JSON back, json_decode it into an associative array. The follower data structure changes depending on which endpoint you’re using, so double-check the docs. I screwed up by assuming the format without actually verifying it. Watch out for scope requirements on some endpoints. And definitely add error handling for expired tokens since you’ll need to refresh them regularly.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.