youtube api 使用 oauth 令牌获取 .NET 中的用户信息

youtube api use oauth token to get info on user in .NET

我有一个应用程序 (ios),您可以使用 google 登录,我要求用户授予访问他的 YouTube 数据的权限,

func doOAuthGoogle(){
    let oauthswift = OAuth2Swift(
        consumerKey:    GoogleYoutube["consumerKey"]!,
        consumerSecret: GoogleYoutube["consumerSecret"]!,
        authorizeUrl:   "https://accounts.google.com/o/oauth2/auth",
        accessTokenUrl: "https://accounts.google.com/o/oauth2/token",
        responseType:   "code"
    )
    oauthswift.authorizeWithCallbackURL( NSURL(string: "W2GCW24QXG.com.xxx.xxx:/oauth-swift")!, scope: "https://www.googleapis.com/auth/youtube", state: "", success: {
        credential, response, parameters in
        print("oauth_token:\(credential.oauth_token)")
        let parameters =  Dictionary<String, AnyObject>()

        //TODO: send oauth to server
        Alamofire.request(.GET, "http://xxx.azurewebsites.net:80/api/Login/Google/", parameters: ["access_token" : credential.oauth_token]).responseJSON { response in
             print(response)
             let resultDic : NSDictionary =  (response.result.value as? NSDictionary)!

             defaults.setObject(resultDic.valueForKey("userId"), forKey: "UserId")
             let vc = self.storyboard?.instantiateViewControllerWithIdentifier("vcGroupsViewController") as? GroupsController
             self.navigationController?.pushViewController(vc!, animated: true)
                    }

        }, failure: {(error:NSError!) -> Void in
            print("ERROR: \(error.localizedDescription)")
    })
}

之后我得到 credential.oauth_token 并将其发送到 .NET 服务器。

在服务器上我有库

using Google.Apis.Services;
using Google.Apis.YouTube.v3;

现在我想获取用户音乐播放列表,但找不到相关的示例代码,例如在具有 facebookclient

的 facebook 中
 var accessToken = access_token;
    var client = new FacebookClient(accessToken);
    // 1 : hit graph\me?fields=
    dynamic me = client.Get("me", new { fields = new[] { "id", "name", "first_name", "last_name", "picture.type(large)", "email", "updated_time" } });
    dynamic meMusic = client.Get("me/music");

好的,我找到了我自己问题的答案, 将访问令牌发送到服务器,然后使用 Web 客户端使用适当的 headers 调用 youtube 数据 api v3,结果将是 youtube 播放列表 ID,从那里获取 watchHistory 节点和将其保存到本地var,并在webclient2中使用它来调用列表项。

希望对其他人有所帮助。

internal User SaveGoogleYoutubeLogin(string access_token)
{
    var accessToken = access_token;
    string watchHistoryList = "";
    using (WebClient webclient = new WebClient())
    {
        webclient.Headers.Add(HttpRequestHeader.Authorization,"Bearer " + accessToken);
        webclient.Headers.Add("X-JavaScript-User-Agent", "Google APIs Explorer");
        var respone2 = webclient.DownloadString("https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true&key={your_api_key}");
        Debug.Print(respone2);
        JObject jResponse = JObject.Parse(respone2);
        watchHistoryList = (string)jResponse["items"][0]["contentDetails"]["relatedPlaylists"]["watchHistory"].ToString();

    }
    using (WebClient webclient2 = new WebClient())
    {
        webclient2.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + accessToken);
        webclient2.Headers.Add("X-JavaScript-User-Agent", "Google APIs Explorer");
        var respone2 = webclient2.DownloadString("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId="+ watchHistoryList + "&key={your_api_key}");
        Debug.Print(respone2);
        JObject jResponse = JObject.Parse(respone2);
        foreach (var item in jResponse["items"])
        {
            Debug.Print(item.ToString());
        }

        }