Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for the new Usage Billing APIs #1750

Merged
merged 14 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## Running an example

From the examples folder, run:
`php your_example.php`

## Adding a new example

1. Clone new_example.php
2. Implement your example
3. Run it (as per above)
4. 👍
53 changes: 53 additions & 0 deletions examples/meter_event_stream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

require 'vendor/autoload.php'; // Make sure to include Composer's autoload file

class meter_event_stream
{
private $apiKey;
private $meterEventSession;

public function __construct($apiKey)
{
$this->apiKey = $apiKey;
$this->meterEventSession = null;
}

private function refreshMeterEventSession()
{
// Check if session is null or expired
if (
null === $this->meterEventSession
|| $this->meterEventSession->expires_at <= time()
) {
// Create a new meter event session in case the existing session expired
$client = new \Stripe\StripeClient($this->apiKey);
$this->meterEventSession = $client->v2->billing->meterEventSession->create();
}
}

public function sendMeterEvent($meterEvent)
{
// Refresh the meter event session, if necessary
$this->refreshMeterEventSession();

// Create a meter event with the current session's authentication token
$client = new \Stripe\StripeClient($this->meterEventSession->authentication_token);
$client->v2->billing->meterEventStream->create([
'events' => [$meterEvent],
]);
}
}

// Usage
$apiKey = '{{API_KEY}}';
$customerId = '{{CUSTOMER_ID}}';

$manager = new MeterEventManager($apiKey);
$manager->sendMeterEvent([
'event_name' => 'alpaca_ai_tokens',
'payload' => [
'stripe_customer_id' => $customerId,
'value' => '26',
],
]);
26 changes: 26 additions & 0 deletions examples/new_example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

// require 'vendor/autoload.php'; // Make sure to include Composer's autoload file
require '../init.php';

class new_example
{
private $apiKey;

public function __construct($apiKey)
{
$this->apiKey = $apiKey;
}

public function doSomethingGreat()
{
echo "Hello World\n";
// $client = new \Stripe\StripeClient($this->apiKey);
}
}

// Usage
$apiKey = '{{API_KEY}}';

$example = new NewExample($apiKey);
$example->doSomethingGreat();
34 changes: 34 additions & 0 deletions examples/stripe_webhook_handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

require 'vendor/autoload.php';

$api_key = getenv('STRIPE_API_KEY');
$webhook_secret = getenv('WEBHOOK_SECRET');

$app = new \Slim\App();
$client = new \Stripe\StripeClient($api_key);

$app->post('/webhook', function ($request, $response) use ($client, $webhook_secret) {
$webhook_body = $request->getBody()->getContents();
$sig_header = $request->getHeaderLine('Stripe-Signature');

try {
$thin_event = $client->parseThinEvent($webhook_body, $sig_header, $webhook_secret);

// Fetch the event data to understand the failure
$event = $client->v2->core->events->retrieve($thin_event->id);
if ($event instanceof \Stripe\Events\V1BillingMeterErrorReportTriggeredEvent) {
$meter = $event->fetchRelatedObject();
$meter_id = $meter->id;

// Record the failures and alert your team
// Add your logic here
}

return $response->withStatus(200);
} catch (\Exception $e) {
return $response->withStatus(400)->withJson(['error' => $e->getMessage()]);
}
});

$app->run();
24 changes: 23 additions & 1 deletion init.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
require __DIR__ . '/lib/Util/RequestOptions.php';
require __DIR__ . '/lib/Util/Set.php';
require __DIR__ . '/lib/Util/Util.php';
require __DIR__ . '/lib/Util/EventTypes.php';
require __DIR__ . '/lib/Util/ObjectTypes.php';

// HttpClient
Expand Down Expand Up @@ -65,10 +66,15 @@
require __DIR__ . '/lib/ApiRequestor.php';
require __DIR__ . '/lib/ApiResource.php';
require __DIR__ . '/lib/SingletonApiResource.php';
require __DIR__ . '/lib/Service/ServiceNavigatorTrait.php';
require __DIR__ . '/lib/Service/AbstractService.php';
require __DIR__ . '/lib/Service/AbstractServiceFactory.php';

require __DIR__ . '/lib/V2/Event.php';
require __DIR__ . '/lib/ThinEvent.php';
require __DIR__ . '/lib/Reason.php';
require __DIR__ . '/lib/RelatedObject.php';
require __DIR__ . '/lib/Collection.php';
require __DIR__ . '/lib/V2/Collection.php';
require __DIR__ . '/lib/SearchResult.php';
require __DIR__ . '/lib/ErrorObject.php';
require __DIR__ . '/lib/Issuing/CardDetails.php';
Expand Down Expand Up @@ -125,6 +131,11 @@
require __DIR__ . '/lib/Entitlements/Feature.php';
require __DIR__ . '/lib/EphemeralKey.php';
require __DIR__ . '/lib/Event.php';
require __DIR__ . '/lib/EventData/V1BillingMeterErrorReportTriggeredEventData.php';
require __DIR__ . '/lib/EventData/V1BillingMeterNoMeterFoundEventData.php';
require __DIR__ . '/lib/Events/V1BillingMeterErrorReportTriggeredEvent.php';
require __DIR__ . '/lib/Events/V1BillingMeterNoMeterFoundEvent.php';
require __DIR__ . '/lib/Exception/TemporarySessionExpiredException.php';
require __DIR__ . '/lib/ExchangeRate.php';
require __DIR__ . '/lib/File.php';
require __DIR__ . '/lib/FileLink.php';
Expand Down Expand Up @@ -309,6 +320,14 @@
require __DIR__ . '/lib/Service/Treasury/TransactionEntryService.php';
require __DIR__ . '/lib/Service/Treasury/TransactionService.php';
require __DIR__ . '/lib/Service/Treasury/TreasuryServiceFactory.php';
require __DIR__ . '/lib/Service/V2/Billing/BillingServiceFactory.php';
require __DIR__ . '/lib/Service/V2/Billing/MeterEventAdjustmentService.php';
require __DIR__ . '/lib/Service/V2/Billing/MeterEventService.php';
require __DIR__ . '/lib/Service/V2/Billing/MeterEventSessionService.php';
require __DIR__ . '/lib/Service/V2/Billing/MeterEventStreamService.php';
require __DIR__ . '/lib/Service/V2/Core/CoreServiceFactory.php';
require __DIR__ . '/lib/Service/V2/Core/EventService.php';
require __DIR__ . '/lib/Service/V2/V2ServiceFactory.php';
require __DIR__ . '/lib/Service/WebhookEndpointService.php';
require __DIR__ . '/lib/SetupAttempt.php';
require __DIR__ . '/lib/SetupIntent.php';
Expand Down Expand Up @@ -352,6 +371,9 @@
require __DIR__ . '/lib/Treasury/TransactionEntry.php';
require __DIR__ . '/lib/UsageRecord.php';
require __DIR__ . '/lib/UsageRecordSummary.php';
require __DIR__ . '/lib/V2/Billing/MeterEvent.php';
require __DIR__ . '/lib/V2/Billing/MeterEventAdjustment.php';
require __DIR__ . '/lib/V2/Billing/MeterEventSession.php';
require __DIR__ . '/lib/WebhookEndpoint.php';

// The end of the section generated from our OpenAPI spec
Expand Down
10 changes: 6 additions & 4 deletions lib/ApiOperations/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,16 @@ protected static function _validateParams($params = null)
* @param array $params list of parameters for the request
* @param null|array|string $options
* @param string[] $usage names of tracked behaviors associated with this request
* @param 'v1'|'v2' $apiMode
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return array tuple containing (the JSON response, $options)
*/
protected function _request($method, $url, $params = [], $options = null, $usage = [])
protected function _request($method, $url, $params = [], $options = null, $usage = [], $apiMode = 'v1')
{
$opts = $this->_opts->merge($options);
list($resp, $options) = static::_staticRequest($method, $url, $params, $opts, $usage);
list($resp, $options) = static::_staticRequest($method, $url, $params, $opts, $usage, $apiMode);
$this->setLastResponse($resp);

return [$resp->json, $options];
Expand Down Expand Up @@ -96,17 +97,18 @@ protected function _requestStream($method, $url, $readBodyChunk, $params = [], $
* @param array $params list of parameters for the request
* @param null|array|string $options
* @param string[] $usage names of tracked behaviors associated with this request
* @param 'v1'|'v2' $apiMode
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return array tuple containing (the JSON response, $options)
*/
protected static function _staticRequest($method, $url, $params, $options, $usage = [])
protected static function _staticRequest($method, $url, $params, $options, $usage = [], $apiMode = 'v1')
{
$opts = \Stripe\Util\RequestOptions::parse($options);
$baseUrl = isset($opts->apiBase) ? $opts->apiBase : static::baseUrl();
$requestor = new \Stripe\ApiRequestor($opts->apiKey, $baseUrl);
list($response, $opts->apiKey) = $requestor->request($method, $url, $params, $opts->headers, $usage);
list($response, $opts->apiKey) = $requestor->request($method, $url, $params, $opts->headers, $apiMode, $usage);
$opts->discardNonPersistentHeaders();

return [$response, $opts];
Expand Down
Loading
Loading