You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Appylar API一段时间后突发401未授权错误的原因求助

Appylar API一段时间后突发401未授权错误的原因求助

It sounds like a classic session lifecycle issue with the Appylar API—let’s break down the most likely reasons for this 401 error and how to fix them, based on your code and typical ad platform behavior:

1. Your Session Token Has Expired (Server-Side Invalidation)

The most probable culprit is that Appylar’s session tokens have an implicit expiration period that’s not immediately visible in your initial session creation response. Even though you’re holding onto the same token value, the server will invalidate it after a set amount of time (often hours, or based on inactivity).

Looking at your code, you only fetch a sessionToken once during the init() call, with no logic to detect when it’s expired or refresh it. Once the token is invalidated on Appylar’s end, every subsequent request using it will throw a 401.

Fix:

Add 401 error handling to your core request method (the one used for both session creation and ad fetching) that automatically refreshes the session when a 401 is encountered:

// Modify your base request function to handle 401s
async request<T>(url: string, data: any, isSessionCreation = false) {
  try {
    // Don't include session token for the initial session creation request
    const requestData = isSessionCreation 
      ? data 
      : { ...data, session_token: this.sessionToken };

    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(requestData)
    });

    if (response.status === 401) {
      // Token expired—refresh session and retry the request
      await this.refreshSession();
      // Retry the original request with the new token
      return await this.request<T>(url, data);
    }

    if (!response.ok) {
      throw new Error(`API request failed with status: ${response.status}`);
    }

    return (await response.json()) as T;
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}

// Add a method to refresh the session without re-fetching DOM values repeatedly
async refreshSession() {
  try {
    const size = this.renderer.getScreenSize();
    const sessionData = await this.request<CreateSessionResponse>(
      API_URL_CREATE_SESSION,
      {
        app_key: this.appKey,
        orientations: this.orientations,
        width: size.width,
        height: size.height,
        density: parseFloat($('#id_density').val() ?? '1'),
        app_id: $('#id_app_id').val(),
        language: $('#id_language').val(),
        country: $('#id_country').val(),
        test_mode: $('#id_test_mode').val() === '1',
      } as CreateSessionRequestData,
      true // Mark this as a session creation request (no token needed)
    );

    // Update session values with fresh data
    this.sessionToken = sessionData.session_token;
    this.bufferMinLimit = sessionData.buffer_limits.min;
    this.rotationInterval = sessionData.rotation_interval;
    this.triggerEvent({ name: 'sessionRefreshed' });
  } catch (error) {
    console.error('Failed to refresh session:', error);
    this.triggerEvent({ name: 'error', error });
  }
}

2. Session Invalidation Due to Platform Policies

Appylar might also invalidate sessions for other reasons, like:

  • Extended inactivity (if your app goes idle for too long between ad requests)
  • Security-related token rotation (some ad platforms rotate tokens periodically to reduce risk)
  • Unexpected changes to session-bound parameters (e.g., if your app’s test_mode flag changes after initialization, though this is less likely to trigger a 401)

Fix:

The same session refresh logic above will handle these cases too. For proactive prevention, check if Appylar’s documentation mentions any explicit session expiration details (like an expires_in field in the initial session response) that you could use to refresh the token before it expires, instead of waiting for a 401.

3. Edge Case: Accidental Token Corruption

While less likely, double-check that your sessionToken isn’t being modified accidentally somewhere else in your code (e.g., a typo in a variable assignment, or a race condition with your AdBuffer logic). You mentioned the token remains unchanged, but it’s worth a quick audit to rule this out.

Final Note

Testing this: You can simulate the 401 scenario by manually invalidating your session token (e.g., changing one character in the token string) and verifying that your refresh logic triggers correctly.

Hope this resolves your issue—let me know if you need help refining the refresh logic for your specific code structure!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 12:09:30