If you have created a token-based key, meaning a key that will stop working when a set amount of tokens (or uses, calls, checks, consumptions, etc) has happened, then you can use “consume” calls to adjust those tokens. Token keys are great for charging your customer on a per-use basis, such as assigning X tokens per prompt of an AI LLM.
Each token-based key is assigned a token limit, then certain actions in your app will make a consumption/top up call which removes/adds the amount of X tokes you specify in the call.
NOTE: Only use “consume” when you want to charge tokens. You should not send them during every key check, such as during activation or daily checks, unless you are purposefully consuming tokens to perform these actions.
Making A Token Consumption Call #
To consume a token simply include the “consume” header during a key check. Here’s an example in PHP:
$tokenCost = 4;
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'auth: ' . $authKey,
'key: ' . $licenseKey, // Set the authentication key in the request headers
'domain: ' . $_SERVER['HTTP_HOST'], // Set the domain in the request headers
'consume: ' . $tokenCost // Set the token's consume value
));
Notice how $tokenCost can be set to any number based on your needs, even a negative number. In this example, when a user takes the action making this API call it will cost the user 4 tokens. For more details, see our documentation on making an API call.
The response will be:
{ "valid" : "1" }
Once a key has hit it’s limit the response will be:
{ "valid" : "0" }
If a user tries to consume more tokens than they have left the response will also be a “valid” of “0”. They cannot over-consume tokens.
Topping Up Tokens #
If your user purchases more tokens from you, such as when a subscription renews at the beginning of the month, you can also use “consume” to refill tokens. To top up tokens, send a negative value via “consume”. That amount will now be available, up to the maximum amount you have set for that key.
Here’s an example scenario… your user purchases a subscription with 1000 token uses per month. During the month they will consume tokens until they hit the max. Once their subscription renews each month, send an automated API call with a negative token value of -1000 to reset their usage back to 0.
Token usage cannot go below 0 by design, so if a user does not use all their tokens in a month our example will still reset their consumed tokens back to 0 and give them access to 1000 tokens.
$tokenCost = -1000; // Restoring all tokens for the month
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'auth: ' . $authKey,
'key: ' . $licenseKey, // Set the authentication key in the request headers
'domain: ' . $_SERVER['HTTP_HOST'], // Set the domain in the request headers
'consume: ' . $tokenCost // Set the token's value
));
Stopping Your App Once Tokens Run Out #
To prevent an action from happening due to a lack of tokens, simply preform a key check as shown above and then look for the “valid” of “0”. Only proceed if the “valid” is “1” and fail to proceed if the “valid” is “0” (and perhaps show the user a simple message saying “You are out of tokens. Please purchase more.”
Detailed Code Example #
Here is a detailed example in PHP that:
- Gets the saved API data such as your API auth key from an environmental file.
- Get the saved license key from a hidden file.
- Creates a function to preform the check, with the amount of tokens to consume as an input.
- Calls that function using a dummy example function to represent your code.
- Returns a response based on the success or failure of the token consumption.
// Load and parse the .env file
$envPath = __DIR__ . '/.env';
if (file_exists($envPath)) {
$env = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($env as $line) {
list($name, $value) = explode('=', $line, 2);
$_ENV[$name] = $value;
}
} else {
echo "Error: .env file not found.";
exit;
}
// Define a function to consume tokens
function consumeTokens($tokenCost) {
$baseUrl = $_ENV['BASE_URL'];
$authKey = $_ENV['AUTH_KEY'];
$licenseKeyFile = __DIR__ . '/hidden/path/to/license-key.txt'; // Path to the license key file
if (!file_exists($licenseKeyFile)) {
return "Error: License key file not found.";
}
$licenseKey = trim(file_get_contents($licenseKeyFile)); // Read the license key from the file
// Initialize cURL session
$ch = curl_init($baseUrl);
// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string instead of outputting it
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // Enable SSL verification for security
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'auth: ' . $authKey,
'key: ' . $licenseKey,
'domain: ' . $_SERVER['HTTP_HOST'],
'consume: ' . $tokenCost // Sending the token cost to the API
));
// Execute cURL session
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
$result = 'cURL error: ' . curl_error($ch);
} else {
// Check HTTP response code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 200 && $httpCode < 300) {
// Success, store the response
$result = $response;
} else {
// Handle HTTP error
$result = "HTTP error: " . $httpCode;
}
}
// Close cURL session
curl_close($ch);
return $result;
}
// Assume this function is defined elsewhere in your application.
function performSpecialAnalysis($userData) {
// Placeholder function that performs some complex operation.
// Returns true on success, false on failure.
return true;
}
function requestAnalysis($userData) {
$tokensRequired = 20; // Define the number of tokens this operation costs
// Charge tokens and get response
$response = consumeTokens($tokensRequired);
if (strpos($response, '"valid": "1"') !== false) {
// Token consumption was successful, proceed with the analysis
$result = performSpecialAnalysis($userData);
if ($result) {
return "Analysis completed successfully.";
} else {
return "Analysis failed.";
}
} else {
// Token consumption failed (not enough tokens or invalid key)
return "Not enough tokens. Please purchase more tokens.";
}
}
// Example user data
$userData = [
'data' => 'User provided data for analysis',
// Other necessary data can be included
];
// Triggering the request
echo requestAnalysis($userData);
While this code covers a lot of various aspects of writing a token consumption script, your implementation doesn’t have to be this detailed or complicated.
As long as you can send “consume” via a header to the API when you preform a key check and can then handle the response of “1” or “0” you can preform a complete token consumption cycle.