Salesforce License Information with APEX

If you want to get certain Salesforce user license information from within your org via APEX, such as TotalLicenses, you will have to either screen scrape the information from your org or sign up for Salesforces user license pilot program.

Signing up for the pilot program is a much better idea.  If you try to screen scrape, then the page layout you’re scraping from might change and you will need to keep up with page changes.

When you signup for the pilot program, the Salesforce documentation says it is only available through the SOAP API and this poses it’s own set of issues.  If you use the SOAP API, you will need to use the login method or add your current login session Id into the SOAP header.  If you need to use it in a scheduled job, you won’t have access to the current session Id.  I have a quick solution so you won’t have to deal with the complexity of using the API and storing login/passwords/tokens.

You can use Database.query

List<sObject> sobjList = Database.query('SELECT MasterLabel, Status, TotalLicenses, UsedLicenses FROM UserLicense');

for (sObject o : sobjList) {
    String sMasterLabel = (String) o.get('MasterLabel');
    String sStatus = (String) o.get('Status');
    Integer nTotalLicenses = (Integer) o.get('TotalLicenses');
    Integer nUsedLicenses = (Integer) o.get('UsedLicenses');
}

Thats it! You can avoid using the API (only if you signed up for the UserLicense pilot program).