Skip to content

Instantly share code, notes, and snippets.

@jarek-foksa
Created July 9, 2015 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarek-foksa/7ac6b7c4f7e338ec6ee6 to your computer and use it in GitHub Desktop.
Save jarek-foksa/7ac6b7c4f7e338ec6ee6 to your computer and use it in GitHub Desktop.
// @src
// https://github.com/GoogleChrome/chrome-app-samples/tree/master/one-time-payment
// @output
// "FULL" - Fully paid & properly licensed
// "FREE_TRIAL" - Free trial, still within trial period
// "FREE_TRIAL_EXPIRED" - Free trial, trial period expired
// "NONE" - No license ever issued
var getLicense = function(callback) {
var retry = true;
var access_token = null
var requestStart = function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/chromewebstore/v1.1/userlicenses/" + chrome.runtime.id);
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhr.onload = requestComplete;
// If either Google server is down or user has no internet connection then assume trial mode
xhr.onerror = function(error) {
callback("FREE_TRIAL");
};
xhr.send();
};
var requestComplete = function() {
if (this.status == 401 && retry) {
retry = false;
chrome.identity.removeCachedAuthToken({ token: access_token }, getToken);
}
else {
handleResponse(null, this.status, this.response);
}
};
var getToken = function() {
chrome.identity.getAuthToken({ interactive: true }, function(token) {
if (chrome.runtime.lastError) {
handleResponse(chrome.runtime.lastError);
}
else {
access_token = token;
requestStart();
}
});
};
var handleResponse = function(error, status, responseJSON) {
var response = JSON.parse(responseJSON);
var license;
if (response.accessLevel === "FULL") {
license = "FULL";
}
else if (response.accessLevel === "FREE_TRIAL") {
var startedSellingTime = 1382871600000; // 2013-10-27 12:00
var currentTime = Date.now();
var firstInstallTime = parseInt(response.createdTime, 10);
var daysSinceFirstInstall = (currentTime - firstInstallTime) / 1000 / 60 / 60 / 24;
// Grant trial license to users who first installed the app less than 2 days ago
if (daysSinceFirstInstall <= 2) {
license = "FREE_TRIAL";
}
// Grant full license to users that first installed the app when it was still free
else if (firstInstallTime < startedSellingTime) {
license = "FULL";
}
else {
license = "FREE_TRIAL_EXPIRED";
}
}
else {
license = "NONE";
}
callback(license);
};
getToken();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment