Chrome Web Store支付扩展免费试用

5
我正在尝试将我在Chrome网上应用店发布的Google Chrome扩展程序转换为免费试用版,使用他们的新许可API。但是谷歌对此的文档对我来说非常令人困惑。请参见:https://developer.chrome.com/webstore/check_for_payment
此外,似乎OpenID 2.0已经被弃用?https://developers.google.com/accounts/docs/OpenID2 是否有某种现成的代码可以设置免费试用并检查用户是否符合许可API的条件?我有很多用户,不想搞砸并迫使他们遇到付款障碍-他们应该免费获得特权。我找不到其他人在线上做过这件事情,也没有他们的代码可供参考和理解。
理想情况下,我的扩展程序应该完全有效7天,然后过期并要求用户付款。
非常感谢您的帮助!
1个回答

7

我在 https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/one-time-payment 上发现了一个很棒的资源。

我对其进行了一些编辑,加入了更多的错误处理,然后将其移植到了我的应用程序中。然而,我很多次不得不去修改不同的 Google API 并进行编辑。如果您在使用此代码时遇到问题,我会尽力查找我所做的修改,并让您知道。您可以将此复制并粘贴到后台页面的控制台窗口中,并使用 getLicense 执行它。如果您将您的密钥复制到清单文件中,则可以使用本地扩展程序执行操作,而无需每次更改都需要等待一个小时。我强烈建议这样做。密钥是来自开发者仪表板的那个-有关更多信息请参见。

function getLicense() {
  var CWS_LICENSE_API_URL = 'https://www.googleapis.com/chromewebstore/v1.1/userlicenses/';
  xhrWithAuth('GET', CWS_LICENSE_API_URL + chrome.runtime.id, true, onLicenseFetched);
}

function onLicenseFetched(error, status, response) {
  function extensionIconSettings(badgeColorObject, badgeText, extensionTitle ){
    chrome.browserAction.setBadgeBackgroundColor(badgeColorObject);
    chrome.browserAction.setBadgeText({text:badgeText});
    chrome.browserAction.setTitle({ title: extensionTitle });
  }
  var licenseStatus = "";
  if (status === 200 && response) {
    response = JSON.parse(response);
    licenseStatus = parseLicense(response);
  } else {
    console.log("FAILED to get license. Free trial granted.");
    licenseStatus = "unknown";
  }
  if(licenseStatus){
    if(licenseStatus === "Full"){
      window.localStorage.setItem('ChromeGuardislicensed', 'true');
      extensionIconSettings({color:[0, 0, 0, 0]}, "", "appname is enabled.");
    }else if(licenseStatus === "None"){
      //chrome.browserAction.setIcon({path: icon}); to disabled - grayed out?
      extensionIconSettings({color:[255, 0, 0, 230]}, "?", "appnameis disabled.");
      //redirect to a page about paying as well?
    }else if(licenseStatus === "Free"){
      window.localStorage.setItem('appnameislicensed', 'true');
      extensionIconSettings({color:[255, 0, 0, 0]}, "", window.localStorage.getItem('daysLeftInappnameTrial') + " days left in free trial.");
    }else if(licenseStatus === "unknown"){
      //this does mean that if they don't approve the permissions,
      //it works free forever. This might not be ideal
      //however, if the licensing server isn't working, I would prefer it to work.
      window.localStorage.setItem('appnameislicensed', 'true');
      extensionIconSettings({color:[200, 200, 0, 100]}, "?", "appnameis enabled, but was unable to check license status.");
    }
  }
  window.localStorage.setItem('appnameLicenseCheckComplete', 'true');
}

/*****************************************************************************
* Parse the license and determine if the user should get a free trial
*  - if license.accessLevel == "FULL", they've paid for the app
*  - if license.accessLevel == "FREE_TRIAL" they haven't paid
*    - If they've used the app for less than TRIAL_PERIOD_DAYS days, free trial
*    - Otherwise, the free trial has expired 
*****************************************************************************/

function parseLicense(license) {
  var TRIAL_PERIOD_DAYS = 1;
  var licenseStatusText;
  var licenceStatus;
  if (license.result && license.accessLevel == "FULL") {
    console.log("Fully paid & properly licensed.");
    LicenseStatus = "Full";
  } else if (license.result && license.accessLevel == "FREE_TRIAL") {
    var daysAgoLicenseIssued = Date.now() - parseInt(license.createdTime, 10);
    daysAgoLicenseIssued = daysAgoLicenseIssued / 1000 / 60 / 60 / 24;
    if (daysAgoLicenseIssued <= TRIAL_PERIOD_DAYS) {
      window.localStorage.setItem('daysLeftInCGTrial', TRIAL_PERIOD_DAYS - daysAgoLicenseIssued);
      console.log("Free trial, still within trial period");
      LicenseStatus = "Free";
    } else {
      console.log("Free trial, trial period expired.");
      LicenseStatus = "None";
      //open a page telling them it is not working since they didn't pay?
    }
  } else {
    console.log("No license ever issued.");
    LicenseStatus = "None";
    //open a page telling them it is not working since they didn't pay?
  }
  return LicenseStatus;
}

/*****************************************************************************
* Helper method for making authenticated requests
*****************************************************************************/

// Helper Util for making authenticated XHRs
function xhrWithAuth(method, url, interactive, callback) {
  console.log(url);
  var retry = true;
  var access_token;
  getToken();

  function getToken() {
    console.log("Calling chrome.identity.getAuthToken", interactive);
    chrome.identity.getAuthToken({ interactive: interactive }, function(token) {
      if (chrome.runtime.lastError) {
        callback(chrome.runtime.lastError);
        return;
      }
      console.log("chrome.identity.getAuthToken returned a token", token);
      access_token = token;
      requestStart();
    });
  }

  function requestStart() {
    console.log("Starting authenticated XHR...");
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
    xhr.onreadystatechange = function (oEvent) { 
      if (xhr.readyState === 4) {  
        if (xhr.status === 401 && retry) {
          retry = false;
          chrome.identity.removeCachedAuthToken({ 'token': access_token },
                                                getToken);
        } else if(xhr.status === 200){
          console.log("Authenticated XHR completed.");
          callback(null, xhr.status, xhr.response);
        }
        }else{
          console.log("Error - " + xhr.statusText);  
        }
      }
    try {
      xhr.send();
    } catch(e) {
      console.log("Error in xhr - " + e);
    }
  }
}

Karl,太棒了 - 我今晚会再次深入研究并编辑此评论,让您知道我发现了什么。在查找错误时,找到您的客户端ID应该非常简单 - 请参见此帖子:https://dev59.com/vWAg5IYBdhLWcg3wOo79 - Catalyst
Karl - 看起来你可能遇到了一个问题,你没有指定一个名称- 在这里查看解决方案 https://dev59.com/Lnvaa4cB1Zd3GeqPFqKv - Catalyst
2
当调用chrome.identity.getAuthToken时,我一直收到“无法读取未定义的属性'getAuthToken'”错误---有什么想法吗? - Catalyst
1
卡尔,我只是好奇,你是如何为已经安装了你的应用程序的用户提供特权的?我正在尝试使用license.createdTime来找出最佳方法。 - Catalyst
1
当我尝试使用上述代码获取许可证时,出现错误[1]。我已经按照答案中提到的相同步骤进行了操作。这是否意味着Google许可证API在服务器端存在问题? [1]: https://i.stack.imgur.com/PtcyK.png - Sunil Kumar
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接