Unity 中的 YouTube 数据 v3 API - OAuth 不工作?我的访问令牌有效,但错误显示未经验证

YouTube Data v3 API in Unity - OAuth not working? My access tokens are valid, but error says UNAUTHENTICATED

我有一个 Unity 项目可以 API 调用 Patreon 和其他视频流网站等网站没有问题,但是当我使用相同的方法使用 YouTube 数据 API v3 时,它没有似乎无法识别我传递给端点的访问令牌。

// MyYouTubeAPI.cs

[Serializable]
struct formData
{
    public string part;
    public string broadcastType;
    public string mine;
    public string key;
}

void Start()
{
    StartCoroutine(GetLatestLiveChatID());
}

IEnumerator GetLatestLiveChatID()
{
    // create instance of our class with our values

    formData data = new formData
    {
        part = "snippet%2CcontentDetails%2Cstatus",
        broadcastType = "all",
        mine = "true",
        key = apiKey
    };
    
    // convert our class to json
    string JsonData = JsonUtility.ToJson(data);

    // instance of unity web request
    UnityWebRequest www = UnityWebRequest.Post("https://youtube.googleapis.com/youtube/v3/liveBroadcasts", "GET");

    // setup upload/download headers (this is what sets the json body)
    byte[] bodyRaw = Encoding.UTF8.GetBytes(JsonData);
    www.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
    www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

    // set your headers
    www.SetRequestHeader("Authorization", "Bearer " + accessToken); // MY ACCESS TOKEN ACTUALLY IS VALID THOUGH
    www.SetRequestHeader("Content-Type", "application/json");
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
        Debug.Log(www.downloadHandler.text);  // I GET THESE ERRORS IN UNITY CONSOLE
    }
    else
    {
        // Debug.Log(www.downloadHandler.text);
        jsonString = www.downloadHandler.text;
        Debug.Log(jsonString);
    }


}

但是我在 Unity 控制台中收到以下错误:

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Invalid Credentials",
        "domain": "global",
        "reason": "authError",
        "location": "Authorization",
        "locationType": "header"
      }
    ],
    "status": "UNAUTHENTICATED"
  }
}

我的访问令牌完全有效,因为我在检查其状态时得到以下信息:

{
  "issued_to": [MY CLIENT ID],
  "audience": [MY CLIENT ID],
  "scope": "https://www.googleapis.com/auth/youtube.force-ssl",
  "expires_in": 3586,
  "access_type": "offline"
}

抱歉我的格式,我在这里 post 不多。有人知道为什么我 运行 会遇到这个问题吗?我一辈子都弄不明白为什么我的访问令牌没有被看到、识别或通过。但我束手无策。非常感谢大家的帮助!

如果您可以访问 bash 提示符(或 Windows 命令提示符),请尝试以下命令:

curl "https://youtube.googleapis.com/youtube/v3/liveBroadcasts?part=snippet,contentDetails,status&broadcastType=all&mine=true&access_token=YOUR_ACCESS_TOKEN".

也尝试将访问令牌添加到您的 URL:将 access_token: accessToken 添加到您的 formData data 并删除对 www.SetRequestHeader 的调用。

我怀疑你的变量 accessTokennull 或空的。