Thursday, February 28, 2013

SharePoint 2013 hosted App License check

How do you manage/enforce licensing on a fully SharePoint hosted app with JavaScript only?

You need a couple of things:

1. JavaScript that checks for the license.

2. Landing pages, telling you that your license has expired or is invalid.

3. An app that helps you creating test keys for testing your App with licensing.


Is the License code valid for the App store?

Yes, the code is valid, because it is implemented in Site Tree View app that has been approved for the App Store.

1. JavaScript

After searching the web for a solution, I found this http://social.msdn.microsoft.com/Forums/en-US/appsforsharepoint/thread/f022893c-3927-4471-8ae8-7dbcd0b8e5fe

However I needed a more clean solution and rewrote the script. Please note that the code depends on jQuery.Cookie.js, JQuery.xml2json.js plugin and the SP client side libraries.

window.SF = window.SF || {};
window.SF.LicenseConstructor = function($) {

    var licenseCollection;

    var response;

    var licenseSettings;

 

    this.Check = function (s) {

        licenseSettings = s;

        var token = $.cookie(licenseSettings.productId);

        if (token) checkToken(token);

        else {

            licenseCollection = SP.Utilities.Utility.getAppLicenseInformation(licenseSettings.context, licenseSettings.productId);

            licenseSettings.context.executeQueryAsync(onRetrieveLicenseFromSPSuccess, onRetrieveLicenseFromSPFailure);

        }

    };

 

    function onRetrieveLicenseFromSPSuccess() {

        var topLicense;

        var encodedTopLicense;

 

        if (licenseCollection.get_count() > 0) {

            topLicense = licenseCollection.get_item(0).get_rawXMLLicenseToken();

            encodedTopLicense = encodeURIComponent(topLicense);

        } else {

            Redirect(licenseSettings.licenseUrl);

        }

 

        var request = new SP.WebRequestInfo();

        request.set_url("https://verificationservice.officeapps.live.com/ova/verificationagent.svc/rest/verify?token=" + encodedTopLicense);

        request.set_method("GET");

        response = SP.WebProxy.invoke(licenseSettings.context, request);

        licenseSettings.context.executeQueryAsync(onVerificationCallSuccess, onVerificationCallFailure);

    }

 

    function onRetrieveLicenseFromSPFailure(sender, args) {

        Redirect(licenseSettings.licenseUrl);

    }

 

    function onVerificationCallSuccess() {

        var xmltoken = response.get_body();

        $.cookie(licenseSettings.productId, xmltoken, {

            expires: 180

        });

        checkToken(xmltoken);

    }

 

    function checkToken(xmltoken) {

        var token = $.xml2json(xmltoken);

        switch (token.EntitlementType.toLowerCase()) {

            case "free":

                break;

            case "paid":

                break;

            case "trial":

                if (token.IsEntitlementExpired.toLowerCase() === "true") Redirect(licenseSettings.expiredUrl); // Trial app has expired!

                break;

        }

    }

 

    function onVerificationCallFailure() {

        Redirect(licenseSettings.licenseUrl);

    }

 

    function Redirect(url) {

        window.location.href = url;

    }

    return this;

};

 

window.SF.License = new SF.LicenseConstructor(jQuery);

2. Landing pages

Include the SF.License.Check(…) in be beginning of you document onload after the SP libraries has loaded.

var settings = {

    context: SP.ClientContext.get_current(),

    licenseUrl: "http://domain/nolicense.html",

    expiredUrl: "http://domain/trialexpired.html",

    productId: "{[App ID guid]}"

};

SF.License.Check(settings);

 

Finally you need to specify the verificationservice endpoint in the AppManifest.xml for your app.

https://verificationservice.officeapps.live.com/ova/verificationagent.svc

image

3. Test

Now you need to test you licensing code. Do this by installing a test License key, so you are able to test your app. Further reading on the subject can be found on Licensing your apps for SharePoint.

Direct link to the license manager app: 4760.LicenseSPAppSample.zip

5 comments:

Stephen Davidson said...

Great post and exactly what i was looking for...nothing like it on the web for SharePoint Hosted apps.

1 question i have is does it matter where i reference the JS files (for cookies and json)? I had it after head section but will it matter?

tojonas said...

Unfortunately it's trivial to "hack" this since it's client side Javascript

http://www.disruptivei.com/Blogg/Inlägg/3/SharePoint-hosted-Apps-can%27t-be-safely-licensed-

Thanks,
Jonas

Tom said...

very nice, will try this out when I get to the phase of licensing!

Ben Steinhauser said...

I created a codeplex project that can create Test Licenses using a desktop Winforms application, instead of using the suggested autohosted sharepoint app. (Mostly because autohosted apps aren't supported anymore and I couldn't get it to install/activate in Office365 SharePoint Online). Get it here:
https://spapplicensecreator.codeplex.com

SharePointly said...

Hello, great post - this worked perfect for Office 365 - However when I test this with SharePoint 2013 on Premise - I am getting an error when installing from the App Store.

I get this error right before it installs "Sorry, we can't seem to connect to the SharePoint Store. Try again in a bit." When I check the error log shows: "The remote server returned an error: (400) Bad Request"

I am able to add other free apps but mine that uses this solution throws the above error.

Do you have any thoughts on this - it would seem that it might be related to the end points.