客戶專用的 .NET 快速入門導覽課程

按照本快速入門指南中的步驟進行,在大約 10 分鐘內,您會有簡單的 .NET C# 控制台應用程式,可向零接觸註冊客戶客戶 API 提出要求。

必備條件

如要執行本快速入門導覽課程,您需要:

  • 您的 Google 帳戶是零接觸註冊機制客戶帳戶的成員。請參閱客戶帳戶
  • Visual Studio 2013 以上版本。
  • 連線至網際網路和網路瀏覽器。

步驟 1:啟用零接觸註冊 API

  1. 使用這個精靈在 Google Developers Console 中建立或選取專案,然後自動啟用 API。依序點選「繼續」和「前往憑證」
  2. 按一下「建立憑證」上的「取消」
  3. 選取頁面頂端的「OAuth 同意畫面」分頁標籤。選取「電子郵件地址」,輸入「產品名稱」 (如果尚未設定),然後按一下「儲存」按鈕。
  4. 選取「憑證」分頁標籤,按一下「建立憑證」按鈕,然後選取「OAuth 用戶端 ID」
  5. 選取應用程式類型「Other」,輸入「快速入門導覽課程」名稱,然後按一下「建立」按鈕。
  6. 按一下「OK」關閉「OAuth 用戶端」面板。
  7. 按一下 「Download JSON」(下載 JSON)
  8. 將檔案移至工作目錄,並重新命名為 client_secret.json

步驟 2:準備專案

  1. 在 Visual Studio 中建立新的 .NET Core C# Console 應用程式專案。
  2. 開啟套件管理員,選取套件來源 nuget.org,並新增下列套件:
    • Google.Apis.AndroidProvisioningPartner.v1
    • Google.Apis.Auth

如要瞭解詳情,請參閱 Microsoft 文件:安裝並使用套件

步驟 3:設定範例

  1. 將步驟 1 中的 client_secret.json 下載至 Visual Studio 解決方案總管。
  2. 選取 client_secret.json,然後前往「Properties」(屬性) 視窗,將「Copy to output Directory」欄位設為「Always copy」
  3. Program.cs 改成下列程式碼:
using Google.Apis.AndroidProvisioningPartner.v1;
using Google.Apis.AndroidProvisioningPartner.v1.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace ZeroTouchCustomerQuickstart
{
    class Program
    {
        // A single scope is used for the zero-touch enrollment customer API.
        static readonly string[] Scopes =
            { "https://www.googleapis.com/auth/androidworkzerotouchemm" };
        static string ApplicationName = "Zero-touch Enrollment .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            // Ask the user to authorize the request using their Google Account
            // in their browser.
            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/zero-touch.quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.FromStream(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create a zero-touch enrollment API service endpoint.
            var service = new AndroidProvisioningPartnerService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName
            });

            // Get the customer's account. Because a customer might have more
            // than one, limit the results to the first account found.
            CustomersResource.ListRequest accountRequest = service.Customers.List();
            accountRequest.PageSize = 1;
            CustomerListCustomersResponse accountResponse = accountRequest.Execute();
            if (accountResponse.Customers.Count == 0)
            {
                // No accounts found for the user. Confirm the Google Account
                // that authorizes the request can access the zero-touch portal.
                Console.WriteLine("No zero-touch enrollment account found.");
                Environment.Exit(-1);
            }
            Company customer = accountResponse.Customers[0];
            var customerAccount = String.Format("customers/{0}", customer.CompanyId);


            // Send an API request to list all the DPCs available.
            CustomersResource.DpcsResource.ListRequest request = service.Customers.Dpcs.
                List(customerAccount);
            CustomerListDpcsResponse response = request.Execute();

            // Print out the details of each DPC.
            IList<Dpc> dpcs = response.Dpcs;
            foreach (Dpc dpcApp in dpcs)
            {
                Console.WriteLine("Name:{0}  APK:{1}",
                                  dpcApp.DpcName,
                                  dpcApp.PackageName);
            }

        }
    }
}

步驟 4:執行範例

如要建構並執行範例,請按一下 Visual Studio 工具列中的「 Start」(啟動)

首次執行應用程式時,您必須授予存取權:

  1. 應用程式會嘗試在預設瀏覽器中開啟新分頁。如果失敗,請從控制台複製網址,並在瀏覽器中開啟。如果您尚未登入 Google 帳戶,系統會提示您登入。如果您登入多個 Google 帳戶,頁面會提示您選取要授權的帳戶。
  2. 然後點選 [Accept]
  3. 關閉瀏覽器分頁,應用程式會繼續執行。

Notes

  • Google API 用戶端程式庫會在檔案系統中儲存授權資料,因此後續啟動並不會啟動授權。
  • 如要重設應用程式的授權資料,請刪除 ~/.credentials/zero-touch.quickstart.json 檔案,然後再次執行應用程式。
  • 本快速入門導覽課程中的授權流程非常適合指令列應用程式。如要瞭解如何新增授權給網頁應用程式,請參閱 使用 OAuth 2.0 網頁應用程式 (ASP.NET MVC) 一文。

疑難排解

以下是一些需要檢查的常見事項。 透過快速入門導覽課程 告訴我們錯誤所在,我們會設法加以修正。

  • 請確認您用於授權 API 呼叫的 Google 帳戶與您零接觸註冊機制客戶帳戶的成員相同。請嘗試使用同一個 Google 帳戶登入零接觸註冊機制入口網站,藉此測試存取權。
  • 確認帳戶在入口網站中已接受最新的《服務條款》。請參閱「 客戶帳戶」。

瞭解詳情