[筆記]C# 取得Firebase中Dynamic Links的資料

C#  透過Google.Apis.FirebaseDynamicLinks.v1 取得Firebase中Dynamic Links的資料

 

Firebase中Dynamic Links的資料

https://console.cloud.google.com/home

https://console.cloud.google.com/apis/credentials

建立服務帳戶,填入資訊後點選"完成"

私密金鑰密碼 只會出現一次 要妥善保存

一定要加入這個角色 中文:​[Firebase拓展檢視者] 英文:[Firebase Grow Viewer]

不然取資料時會 會回傳 The caller does not have permission [403]

NuGet安裝項目

Google.Apis.Auth.OAuth2
Google.Apis.FirebaseDynamicLinks.v1
Google.Apis.Services

主要程式
static void Main(string[] args)
{
    try
    {
    	string dynamicLink = "要查詢的網址";

    	string durationDays = 7;

    	new Program().Run(dynamicLink, durationDays).Wait();

    }
    catch (AggregateException ex)
    {
    	foreach (var e in ex.InnerExceptions)
    	{
    		Console.WriteLine("ERROR: " + e.Message);
    	}
    }
    Console.WriteLine("\n Press any key to close...");
    Console.ReadKey();
}

private async Task Run(string dynamicLink, int durationDays)
{
	//取得Bin資料夾路徑(此範例的私密金鑰檔案(xxx.p12)放在Bin資料夾)
	string basePath = AppDomain.CurrentDomain.BaseDirectory;
	var fileName = Path.Combine(basePath, "私密金鑰檔名.p12");
	var certificate = new X509Certificate2(fileName, "notasecret", X509KeyStorageFlags.Exportable);
	
	//Google Cloud Platform > [API和服務] > [憑證] > [服務帳戶]中的電子郵件
	string serviceAccountEmail = "填入電子郵件";
	
	var credential = new ServiceAccountCredential(
	   new ServiceAccountCredential.Initializer(serviceAccountEmail)
	   {
		   Scopes = new[] { FirebaseDynamicLinksService.Scope.Firebase }
	   }.FromCertificate(certificate));

	var firebaseService = new FirebaseDynamicLinksService(new BaseClientService.Initializer { 
		HttpClientInitializer = credential,
		ApplicationName = "DynamicLink Sample",
	});


	var linkStatsRequest = firebaseService.V1.GetLinkStats(dynamicLink);
	linkStatsRequest.AccessToken = credential.GetAccessTokenForRequestAsync().Result;
	linkStatsRequest.DurationDays = durationDays;

	var linkStatsResult = linkStatsRequest.Execute();
	var resurtJsonTxt = JsonConvert.SerializeObject(linkStatsResult);
	Console.WriteLine(resurtJsonTxt);
}