Salesforce acquires m3ter to add consumption-based billing to Agentforce
Back to Tutorials
techTutorialbeginner

Salesforce acquires m3ter to add consumption-based billing to Agentforce

June 9, 202616 views4 min read

Learn how to build a basic consumption-based billing system using Python and Flask, demonstrating core concepts of usage-based pricing models.

Introduction

In this tutorial, you'll learn how to set up and use a basic consumption-based billing system using Python and a simple API framework. This mirrors the kind of technology that Salesforce is integrating with its acquisition of m3ter. You'll create a system that tracks usage and calculates billing based on consumption, which is essential for modern SaaS platforms offering usage-based pricing.

Prerequisites

  • Basic understanding of Python programming
  • Python 3.6 or higher installed on your system
  • Basic knowledge of REST APIs and HTTP requests
  • Installed Python packages: Flask, requests

Step-by-Step Instructions

Step 1: Set Up Your Development Environment

Install Required Packages

First, you need to install the necessary Python packages. Open your terminal or command prompt and run:

pip install flask requests

Why: Flask is a lightweight web framework for Python that allows us to create a simple API server. Requests will help us make HTTP calls to our API.

Step 2: Create the Billing System Structure

Create the Main Application File

Create a new file named billing_system.py and start by importing the required modules:

from flask import Flask, request, jsonify
import uuid
from datetime import datetime

Why: These modules will help us create a web server, handle JSON data, and manage unique identifiers and timestamps.

Step 3: Initialize the Flask Application

Set Up Flask App and Data Storage

Add the following code to your billing_system.py file:

app = Flask(__name__)

# In-memory storage for customers and usage records
customers = {}
usage_records = {}

@app.route('/customers', methods=['POST'])
def create_customer():
    data = request.get_json()
    customer_id = str(uuid.uuid4())
    customers[customer_id] = {
        'name': data['name'],
        'email': data['email'],
        'plan': data['plan'],
        'created_at': datetime.now().isoformat()
    }
    return jsonify({'customer_id': customer_id}), 201

@app.route('/usage', methods=['POST'])
def record_usage():
    data = request.get_json()
    usage_id = str(uuid.uuid4())
    usage_records[usage_id] = {
        'customer_id': data['customer_id'],
        'resource': data['resource'],
        'amount': data['amount'],
        'timestamp': datetime.now().isoformat()
    }
    return jsonify({'usage_id': usage_id}), 201

Why: This sets up the basic structure for our application with endpoints to create customers and record usage. We're using in-memory storage for simplicity.

Step 4: Add Billing Calculation Logic

Implement the Billing Calculation Function

Now, add a function to calculate bills based on usage records:

@app.route('/bill/', methods=['GET'])
def calculate_bill(customer_id):
    if customer_id not in customers:
        return jsonify({'error': 'Customer not found'}), 404
    
    customer = customers[customer_id]
    plan = customer['plan']
    
    # Simple pricing model
    pricing = {
        'basic': {'rate': 0.01},  # $0.01 per unit
        'premium': {'rate': 0.05},  # $0.05 per unit
        'enterprise': {'rate': 0.10}  # $0.10 per unit
    }
    
    if plan not in pricing:
        return jsonify({'error': 'Invalid plan'}), 400
    
    rate = pricing[plan]['rate']
    total_usage = 0
    
    for usage_id, usage in usage_records.items():
        if usage['customer_id'] == customer_id:
            total_usage += usage['amount']
    
    total_bill = total_usage * rate
    
    return jsonify({
        'customer_id': customer_id,
        'customer_name': customer['name'],
        'plan': plan,
        'total_usage': total_usage,
        'total_bill': round(total_bill, 2)
    })

Why: This function calculates the bill based on a customer's usage and their pricing plan. It demonstrates how consumption-based billing works by multiplying usage by a rate.

Step 5: Run Your Billing System

Start the Flask Server

At the bottom of your billing_system.py file, add:

if __name__ == '__main__':
    app.run(debug=True)

Why: This starts the Flask web server, making your billing system accessible via HTTP requests.

Step 6: Test Your System

Use curl Commands to Test Endpoints

Open your terminal and run these commands to test your system:

# Create a customer
 curl -X POST http://localhost:5000/customers \
   -H "Content-Type: application/json" \
   -d '{"name": "John Doe", "email": "[email protected]", "plan": "premium"}'

# Record some usage
 curl -X POST http://localhost:5000/usage \
   -H "Content-Type: application/json" \
   -d '{"customer_id": "YOUR_CUSTOMER_ID", "resource": "API Calls", "amount": 1000}'

# Calculate bill
 curl -X GET http://localhost:5000/bill/YOUR_CUSTOMER_ID

Why: These commands simulate how a real system would interact with your billing API, testing each endpoint.

Step 7: Enhance Your System

Add More Features

For a more advanced system, consider adding:

  • Database integration (like SQLite or PostgreSQL) for persistent storage
  • More complex pricing models with tiers
  • Usage-based billing reports
  • Automated billing cycles

Why: These enhancements would make your system more realistic and closer to what Salesforce's m3ter integration provides.

Summary

In this tutorial, you've created a basic consumption-based billing system using Python and Flask. You learned how to:

  • Set up a simple web server with Flask
  • Create customers and record usage data
  • Calculate bills based on usage and pricing plans
  • Test your system using HTTP requests

This simple system demonstrates core concepts of how Salesforce's acquisition of m3ter enables customers to launch and manage usage-based pricing models directly within their platform. While this example is basic, it shows the fundamental architecture that underlies more complex systems used in enterprise billing.

Source: TNW Neural

Related Articles