快速入門:個人化應用程式 (HTML)
[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]
使用 JavaScript 的 Windows 執行階段應用程式可以使用 Live SDK 從使用者的 Microsoft 帳戶存取資訊。
當應用程式執行時,使用者必須使用其 Microsoft 帳戶登入,並同意您的應用程式存取其資料。使用者登入並同意之後,您的應用程式就可以存取使用者的個人檔案資料,來提供個人化體驗。
重要 本快速入門僅供說明與示範之用。若想要在要上傳到 Windows 市集並散佈給客戶的應用程式中使用這個功能,則除了登入功能之外,還需要包含登出功能與隱私權原則。完成本快速入門之後,請閱讀 Microsoft 帳戶登入的需求,以了解如何新增這些功能。
重要 本主題中的教學課程將示範 Windows 市集應用程式。您也可以將 Microsoft 服務新增到 Windows Phone 市集應用程式。
先決條件
使用 JavaScript 開發使用「Windows Live 服務」功能的 Windows 執行階段應用程式之前,您必須先在開發電腦上安裝必要的軟體。
如果尚未安裝開發 Windows 市集應用程式所需的工具與 SDK,請安裝。這些工具包括 Microsoft Visual Studio 與其他工具。
使用 JavaScript 的 Windows 市集應用程式。
注意 這個快速入門中顯示的程式碼會新增至 Visual Studio 中 JavaScript 專案的 [空白應用程式] 範本。
將使用者登入,並取得存取其資料的同意
新增可存取「Windows Live 服務」功能的程式碼。
應用程式執行時,可為使用 Microsoft 帳戶登入的使用者顯示 Windows 登入控制項。登入之後,如果使用者尚未同意此應用程式,會提示使用者同意應用程式存取他們的個人檔案資訊。
若要在您的應用程式執行時將使用者登入,請在專案中執行此動作:
設定 Live SDK 參考如下:
- 在 [方案總管]**** 中,以滑鼠右鍵按一下 [參考] > [加入參考]****。
- 移至 [Windows] > [擴充功能],然後核取 [Live SDK] 旁邊的方塊。如果在清單中沒看見 [Live SDK],請重新安裝 Live SDK,然後重試此程序。
- 按一下 [確定] 結束對話方塊。
將 Live SDK 檔案中的 wl.js 檔案參照新增至應用程式。在 JavaScript 專案的 [空白應用程式]**** 範本中,這會新增至 Default.html。
在應用程式主要程式碼檔的 <head> 標記以及 default.js 檔案的連結上方,像這樣新增 <script> 標記。
<script src="///LiveSDKHTML/js/wl.js"></script>
在 default.html 的 <body> 標記中,新增程式碼以讓使用者登入其 Microsoft 帳戶,並以使用者資訊更新顯示。
注意 如果使用者的電腦帳戶與其 Microsoft 帳戶關聯,這不會顯示 Microsoft 帳戶登入控制項。在此情況下,應用程式會自動登入。
在 <body> 標記中,新增下列程式碼。
<!--This is where the user's info will be written after the user has signed in.--> <label id="info"></label> <!--This is the script code that will sign the user in and display their name.--> <script> // Initialize the Live Connect features. // This should be called from each file that // uses Live Connect features. WL.init(); // Sign the user into their Microsoft account or connect // the app to the Microsoft account the user has associated // with their computer account. WL.login({ scope: ["wl.signin"] }).then( function (response) { onLoginComplete(); }, function (loginError) { document.getElementById("info").innerText = "Login Error: " + loginError.error + " - " + loginError.error_description; } ); // If the user is signed in, then get their profile info function onLoginComplete() { WL.api({ path: "me", method: "get" }).then( function (response) { // update the display to show the user's name document.getElementById("info").innerText = "Hello " + response.name + "!"; }, function (infoError) { document.getElementById("info").innerText = "Data Request Error: " + infoError.error.message; } ); } </script>
摘要與後續步驟
在這個主題中,您已了解如何開始在您的應用程式中使用「Windows Live 服務」,以存取使用者在 Microsoft 雲端服務 (例如 Outlook.com 與 Microsoft OneDrive) 中的資料。
若要繼續深入了解使用「Windows Live 服務」的詳細資訊,請參閱 Microsoft 帳戶登入的需求和如何將 Microsoft 服務新增到您的應用程式主題,您可以從中了解如何新增登入和登出功能及隱私權原則。