Integrating custom Twitch subscription verification with HybridAuth

I created a custom method to verify if a user has an active Twitch subscription. Originally I built this using my own auth system, but now I want to integrate it with HybridAuth framework. I can retrieve the access token using Hybrid_Provider_Adapter::getAccessToken() but I’m not sure about the best place to call my verification method.

My function returns HTTP 200 for subscribed users and other status codes for non-subscribers. I already added the user_subscribe scope and it works fine. Where should I place this function call in the HybridAuth workflow to check the HTTP response code?

public function verifySubscription($token){
    $user = $this->getAuthenticatedUser($token);
    $apiUrl = "https://api.twitch.tv/kraken/users/" . $user . "/subscriptions/" . $channelId;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/vnd.twitchtv.v3+json', 'Authorization: OAuth ' . $token));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_URL, $apiUrl);
    curl_setopt($curl, CURLOPT_POST, 0);
    
    $response = curl_exec($curl);
    $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    return $statusCode;
}

Skip modifying HybridAuth’s internals - build a middleware layer instead. After getUserProfile() succeeds, run your subscription check as a separate step before letting users into protected areas. Keeps things clean and way easier to debug.

I built something like this for a content platform. Created a custom auth service that handles HybridAuth first, then immediately hits your verification method with the fresh token. If the subscription check fails, just redirect or block access without breaking OAuth.

One thing that bit me - handle API failures properly. Your verification needs to tell the difference between “user isn’t subscribed” and “API is down.” When Twitch’s API went offline, it locked out all my subscribers. Now I always build in fallback logic or grace periods so users don’t get screwed when APIs have outages.

I ran into the same thing with HybridAuth and external API verification. Best way I found was hooking into the auth callback instead of messing with the core workflow. Once OAuth finishes, I set up a custom event handler that fires your verification method. Keeps the auth process clean while adding your subscription check after authentication. You can do this by extending the HybridAuth adapter or wrapping it in a service. Heads up - that Kraken API endpoint is deprecated. Switch to the new Helix API at https://api.twitch.tv/helix/subscriptions/user with proper headers including Client-ID. Also cache the subscription status since these API calls have rate limits. I built mine as a service layer that runs right after getUserProfile() succeeds. That way you handle user data and subscription verification together without breaking HybridAuth’s structure. Store the verification result in your session or user object for later requests.

just toss it in a separate function that runs after hybridauth finishes. don’t overthink it - grab the token, run your verification immediately, then redirect. wrap it in try/catch though since twitch’s api gets flaky and you don’t want users stuck in auth loops when their servers crap out.

The Problem:

You’re struggling to integrate a custom Twitch subscription verification method into your HybridAuth workflow. You’re successfully retrieving the access token, but you’re unsure where to optimally place the subscription verification function call within the HybridAuth process to efficiently check the HTTP response code and manage potential API errors and updates. The current approach involves direct API calls and lacks robust error handling and adaptability to potential changes in Twitch’s API or HybridAuth. This makes your solution fragile and prone to breaking.

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

Directly embedding subscription verification logic within the core authentication flow tightly couples your system, making it highly susceptible to breakage when either Twitch’s API or HybridAuth undergoes updates. This approach also lacks essential features like robust error handling (e.g., handling Twitch API outages) and efficient mechanisms to deal with API rate limits. A more scalable solution decouples these concerns, improving maintainability and reliability.

:gear: Step-by-Step Guide:

  1. Create a Dedicated Middleware Layer: Instead of modifying HybridAuth’s core functionality, create a separate middleware layer or service to handle the subscription verification. This layer will act as an intermediary between HybridAuth and your application’s logic. This approach promotes clean separation of concerns and simplifies debugging.

  2. Hook into the HybridAuth Callback: After successful authentication with HybridAuth (e.g., using the getUserProfile() callback), trigger your middleware layer. This ensures that the access token is readily available for your verification process. Consider using events or custom callbacks provided by HybridAuth for this step.

  3. Implement the Verification Service: This service will contain your verifySubscription function (modified for Helix API if necessary). Here’s an example showing improvements for error handling and API resilience:

<?php
public function verifySubscription($token){
    // Use the Helix API -  Kraken is deprecated
    $user = $this->getAuthenticatedUser($token);
    $apiUrl = "https://api.twitch.tv/helix/subscriptions/user"; // Helix endpoint
    $headers = array(
        'Client-ID: YOUR_CLIENT_ID', // Remember to replace with your actual Client ID
        'Authorization: Bearer ' . $token,
        'Accept: application/json'
    );

    $ch = curl_init($apiUrl);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        // Log the error - essential for debugging
        error_log("Twitch subscription verification failed: HTTP code $httpCode, Response: $response");
        return false; // Or throw an exception depending on your error handling strategy
    }

    $data = json_decode($response, true);
    //Process the response to determine subscription status - adapt this to your needs
    return isset($data['data']) && count($data['data']) > 0;
}
  1. Handle the Response: After the verifySubscription function executes, check the returned value (true for subscribed, false otherwise). Based on this result, grant or deny access to the protected features of your application.

  2. Implement Rate Limiting and Retries: Add rate limiting to your API calls to avoid exceeding Twitch API limits. Consider implementing retry mechanisms with exponential backoff to handle temporary API failures.

:mag: Common Pitfalls & What to Check Next:

  • API Key and Client ID: Ensure that you’ve correctly set your Twitch Client ID and access token.
  • Helix API Endpoint: Verify that you are using the correct Helix API endpoint (/helix/subscriptions/user) for subscription checks.
  • Error Handling: Implement comprehensive error handling in your verification service. Log all errors and implement fallback mechanisms to prevent unexpected disruptions in user experience during API outages.
  • Caching: Cache the subscription status for a short duration to reduce API calls and improve performance. If your application is frequently calling this API, caching is essential.

: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!

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