Skip to content

Python – Get General Billing Report

This script uses Python3 to retrieve the General Billing Report from Cloudmore. It will store the JSON result in a file.

Edit the variables under “Define variables” and run the script with Python3.

Please see the billing integration guide for more details on the returned data.

import requests
import json
import base64
import time
# Define constants
RESELLER_ID = '11111111-2222-3333-4444-555555555555' # Replace with you Broker ID
CLIENT_ID = 'ro.customer.client'
API_SECRET = 'MySecret' # Replace with your API Secret
USERNAME = 'username@broker.com' # Replace with your username
PASSWORD = 'MyPassword' # Replace with your password
START_DATE = '2023-01-01' # Replace with the start date you want
END_DATE = '2023-01-31' # Replace with the end date you want
SAVE_TO_FILE = f'BillingReport_{START_DATE}_{END_DATE}_json.txt'
# Base64 encode the API secret
client_decoded = f'{CLIENT_ID}:{API_SECRET}'
b64_secret = base64.b64encode(client_decoded.encode()).decode()
# Get Access Token
token_url = 'https://api.cloudmore.com/connect/token'
token_headers = {'Authorization': f'Basic {b64_secret}'}
token_data = {
    'client_id': 'ro.customer.client',
    'grant_type': 'password',
    'username': USERNAME,
    'password': PASSWORD,
    'scope': 'api'
}
token_response = requests.post(token_url, headers=token_headers, data=token_data)
token = token_response.json().get("access_token")
print('Access Token received:', token)
# Start generating Billing Report
billing_url = f'https://api.cloudmore.com/api/resellers/{RESELLER_ID}/billing/reports/MonthlyBillingPerOrganizationAsync'
billing_headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {token}'
}
billing_data = json.dumps({'startDate': START_DATE, 'endDate': END_DATE})
billing_response = requests.post(billing_url, headers=billing_headers, data=billing_data)
location = billing_response.headers['location']
print('Billing Report generation started')
print('Endpoint to retrieve billing report:', location)
# Get billing report (try until status 5)
def get_billing_report():
    while True:
        response = requests.get(location, headers=billing_headers)
        report_status = response.json()['status']
        if report_status != 5:
            print('Billing Report not ready... waiting 5 seconds.')
            time.sleep(5)
        else:
            print('Billing Report Done!')
            return response
billing_response = get_billing_report()
# Write JSON to file
with open(SAVE_TO_FILE, 'w') as file:
    json.dump(billing_response.json(), file)