protected void processLicense(VerifyEntitlementTokenResponse verifiedLicense) { SPAppLicenseType licenseType = SPAppLicenseHelper.GetLicenseTypeFromLicense(verifiedLicense); switch (licenseType) { case SPAppLicenseType.Trial: //Do something for a valid trial besides presenting a message on the UI if (SPAppLicenseHelper.GetRemainingDays(verifiedLicense) > 0) { //Valid trial //The UI string retrieved above will already contain the appropiate info //In real app code you could take additional steps (we encourage trials to be fully featured) //Helper code will return int.MaxValue for an unlimited trial } else { //Expired trial //The UI string retrieved above will already contain the appropiate info //In real app code you could take additional steps (e.g. provide reduced functionality) } break; case SPAppLicenseType.Paid: //Do something for a paid app break; case SPAppLicenseType.Free: //Do something for a free app break; default: throw new Exception("Unknown License Type"); } }
public static string GetStorefrontUrl(VerifyEntitlementTokenResponse verifiedLicense, string hostWebUrl, string currentPageUrl, string appName) { String storeTemplateString = "{0}_layouts/15/storefront.aspx?source={1}&sname={2}&#vw=AppDetailsView,app={3},clg=0,cm=en-US"; //Note: If you are using the hardcoded token provided in the sample this URL will always point to the Cheezburgers app. return(String.Format(storeTemplateString, hostWebUrl, currentPageUrl, appName, verifiedLicense.AssetId)); }
public static string GetStorefrontUrl(VerifyEntitlementTokenResponse verifiedLicense, string hostWebUrl, string currentPageUrl, string appName) { String storeTemplateString = "{0}_layouts/15/storefront.aspx?source={1}&sname={2}&#vw=AppDetailsView,app={3},clg=0,cm=en-US"; //Note: If you are using the hardcoded token provided in the sample this URL will always point to the Cheezburgers app. return String.Format(storeTemplateString, hostWebUrl, currentPageUrl, appName, verifiedLicense.AssetId); }
protected void Page_Load(object sender, EventArgs e) { //ProductId must match the one on the AppManifest.xml of the SharePoint App that is retrieving its license //An app can only retrieve its own licenses for security reasons (e.g. you cannot retrieve other Apps licenses) //The one hardcoded here matches this test app Guid ProductId = new Guid("7c617a53-6f45-4d23-ada0-28eabb744acb"); string uiWarningMessage = null; //Get Context token to call SP; standard oAuth string contextToken = Session["contexToken"].ToString(); TokenHelper.TrustAllCertificates(); ClientContext ctx = TokenHelper.GetClientContextWithContextToken(Session["SPHostUrl"].ToString(), Session["contexToken"].ToString(), Request.Url.Authority); //Use helper method to retrieve a processed license object //It is recommended to CACHE the VerifyEntitlementTokenResponse result until the storeLicense.tokenExpirationDate VerifyEntitlementTokenResponse verifiedLicense = SPAppLicenseHelper.GetAndVerifyLicense(ProductId, ctx); //Get UI warning. //Note that the name of the app is being hardcoded to Cheezburgers because is an app that already exists on the marketplace //You should use your exact app display name instead (make sure name matches with the metadata you submit to seller dashboard uiWarningMessage = SPAppLicenseHelper.GetUIStringText(verifiedLicense, Session["SPHostUrl"].ToString(), Request.Url.ToString(), "Cheezburgers", "Features X, Y, Z"); if (verifiedLicense == null) { //No license found or the license was malformed //The UI string retrieved above will already contain the appropiate info //In real app code you could take additional steps (e.g. provide reduced functionality) } else { //There is a well-formed license; must look at properties to determine validity if (verifiedLicense.IsValid) { //Valid production license //For app sample purposes display 'Production License' + the corresponding warning text; replace this with your own logic. uiWarningMessage = "Production License: " + uiWarningMessage; processLicense(verifiedLicense); } else if (verifiedLicense.IsTest && _testMode == true) { //Test mode with valid test token //For debug we just display 'Test License' plus the corresponding UI warning text; in a real world production scenario _testMode should be set to false and the test license should be rejected. uiWarningMessage = "Test License: " + uiWarningMessage; processLicense(verifiedLicense); } else { //Beep, production mode with invalid license //Warn the user about missing/invalid license uiWarningMessage = "Invalid License!!! " + uiWarningMessage; } } //Sets the text of the alert lblWarning.Text = uiWarningMessage; }
protected void Page_Load(object sender, EventArgs e) { try { var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request); var hostWeb = Page.Request["SPHostUrl"]; var appWeb = Page.Request["SPAppWebUrl"]; using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority)) { // Retrieve any app licenses stored within SharePoint, most RELEVANT first. ClientResult <AppLicenseCollection> licenses = Microsoft.SharePoint.Client.Utilities.Utility.GetAppLicenseInformation(clientContext, _productID); clientContext.ExecuteQuery(); if (licenses.Value.Count == 0) { throw new InvalidOperationException("No license"); } string licenseString = licenses.Value[0].RawXMLLicenseToken; // Validate the license against the Office Store license service. VerificationServiceClient service = new VerificationServiceClient(); VerifyEntitlementTokenRequest request = new VerifyEntitlementTokenRequest(); request.EntitlementToken = licenseString; VerifyEntitlementTokenResponse storeLicense = service.VerifyEntitlementToken(request); // Perform licensing checks. // // Use this version of the check in production: // if (!storeLicense.IsValid || storeLicense.IsExpired) // // Use this version of the check in test/debugging: if ((!storeLicense.IsValid && !storeLicense.IsTest) || storeLicense.IsExpired) { throw new InvalidOperationException("Invalid license"); } // At this point, we have a valid license. We can retrieve the details // of the license (type of license, acquisition date, etc.) from the // license provided by the Office Store and take appropriate actions. // <--TBD--> Response.Write("Licensing Succeeded: " + storeLicense.EntitlementType.ToString()); } } catch (Exception ex) { Response.Write("Licensing failed: " + ex.Message); } }
/// <summary> /// Takes a token from SP and verifies it with the Store using the verification web service. /// </summary> /// <param name="rawLicenseToken">XML string containing a well-formed license token</param> private static VerifyEntitlementTokenResponse GetValidatedLicenseFromStore(string rawLicenseToken) { VerificationServiceClient service = null; VerifyEntitlementTokenResponse result = null; VerifyEntitlementTokenRequest request = new VerifyEntitlementTokenRequest(); request.EntitlementToken = rawLicenseToken; service = new VerificationServiceClient(); result = service.VerifyEntitlementToken(request); return(result); }
/// <summary> /// Returns a ready to display UI string for a given license. Includes a link to the storefront if necessary /// </summary> /// <param name="verifiedLicense">A license object that has already been verified by the Store web service</param> /// <param name="hostWebUrl">The URL of the web where the app is installed. Get this from SP tokens</param> /// <param name="currentPageUrl">The URL of the current page (so users can return to it from the storefront); must be same domain as hostWeb</param> /// <param name="appDisplayName">The title of the breadcrum that storefront will display on the back link</param> /// <returns></returns> public static string GetUIStringText(VerifyEntitlementTokenResponse verifiedLicense, string hostWebUrl, string currentPageUrl, string appDisplayName, string additionalFeaturesFullVersion) { string uiWarning = String.Empty; if (verifiedLicense == null) { uiWarning = String.Format(GetLicenseStringFromResource(_noLicenseStringKey), appDisplayName, "<a href='" + GetStoreSearchUrl(appDisplayName, hostWebUrl, currentPageUrl) + "'>", "</a>", additionalFeaturesFullVersion); } else { string storeFrontUrl = SPAppLicenseHelper.GetStorefrontUrl(verifiedLicense, hostWebUrl, currentPageUrl, appDisplayName); SPAppLicenseType licenseType = GetLicenseTypeFromLicense(verifiedLicense); switch (licenseType) { case SPAppLicenseType.Free: uiWarning = String.Format(GetLicenseStringFromResource(_freeStringKey), appDisplayName, "<a href='" + storeFrontUrl + "'>", "</a>"); break; case SPAppLicenseType.Paid: uiWarning = String.Format(GetLicenseStringFromResource(_paidStringKey), appDisplayName, "<a href='" + storeFrontUrl + "'>", "</a>"); break; case SPAppLicenseType.Trial: int remainingDays = GetRemainingDays(verifiedLicense); if (remainingDays == int.MaxValue) { //Unlimited time trial uiWarning = String.Format(GetLicenseStringFromResource(_trialUnlimitedStringKey), appDisplayName, "<a href='" + storeFrontUrl + "'>", "</a>", additionalFeaturesFullVersion); } else { //Time limited trial if (remainingDays > 0) { uiWarning = String.Format(GetLicenseStringFromResource(_trialStringKey), appDisplayName, remainingDays, "<a href='" + storeFrontUrl + "'>", "</a>", additionalFeaturesFullVersion); } else { //Expired trial uiWarning = String.Format(GetLicenseStringFromResource(_trialExpiredStringKey), "<a href='" + storeFrontUrl + "'>", "</a>"); } } break; } } return(uiWarning); }
public static VerifyEntitlementTokenResponse GetAndVerifyLicense(Guid productId, ClientContext ctx) { //Retrieve license from SharePoint string rawLicense = GetLicenseTokenFromSharePoint(productId, ctx); if (String.IsNullOrEmpty(rawLicense)) { return(null);// No license } //Validate license with the store VerifyEntitlementTokenResponse storeLicense = GetValidatedLicenseFromStore(rawLicense); return(storeLicense); }
/// <summary> /// Returns the number of days this license is valid (can return negative if expired). /// If you want an extra level of granularity you shouldn't use days but instead look at the Time. /// </summary> /// <param name="verifiedLicense"></param> public static int GetRemainingDays(VerifyEntitlementTokenResponse verifiedLicense) { DateTime licenseExpirationDate = (DateTime)verifiedLicense.EntitlementExpiryDate; if (licenseExpirationDate == DateTime.MaxValue) { //Unlimited trial, return max int return(int.MaxValue); } else { int remainingDays = licenseExpirationDate.Subtract(DateTime.UtcNow).Days; return(remainingDays); } }
/// <summary> /// Returns the corresponding license type given a verified license. Note that verified != valid /// </summary> /// <param name="verifiedLicense">A license object that has already been verified by the Store web service</param> public static SPAppLicenseType GetLicenseTypeFromLicense(VerifyEntitlementTokenResponse verifiedLicense) { string entitlementType = verifiedLicense.EntitlementType.ToLower(); return(GetLicenseTypeFromString(entitlementType)); }