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

Support for APIs in the new API version 2024-09-30.acacia #1756

Merged
merged 10 commits into from
Oct 1, 2024
2 changes: 1 addition & 1 deletion OPENAPI_VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v1267
v1268
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,26 @@ If your beta feature requires a `Stripe-Version` header to be sent, set the `api
Stripe::addBetaVersion("feature_beta", "v3");
```

### Custom requests

If you would like to send a request to an undocumented API (for example you are in a private beta), or if you prefer to bypass the method definitions in the library and specify your request details directly, you can use the `rawRequest` method on the StripeClient.

```php
$stripe = new \Stripe\StripeClient('sk_test_xyz');
$response = $stripe->rawRequest('post', '/v1/beta_endpoint', [
"caveat": "emptor"
], [
"stripe_version" => "2022-11_15",
]);
// $response->body is a string, you can call $stripe->deserialize to get a \Stripe\StripeObject.
$obj = $stripe->deserialize($response->body);

// For GET requests, the params argument must be null, and you should write the query string explicitly.
$get_response = $stripe->rawRequest('get', '/v1/beta_endpoint?caveat=emptor', null, [
"stripe_version" => "2022-11_15",
]);
```

## Support

New features and bug fixes are released on the latest major version of the Stripe PHP library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.
Expand Down
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();
31 changes: 30 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 All @@ -94,6 +100,9 @@
require __DIR__ . '/lib/BankAccount.php';
require __DIR__ . '/lib/Billing/Alert.php';
require __DIR__ . '/lib/Billing/AlertTriggered.php';
require __DIR__ . '/lib/Billing/CreditBalanceSummary.php';
require __DIR__ . '/lib/Billing/CreditBalanceTransaction.php';
require __DIR__ . '/lib/Billing/CreditGrant.php';
require __DIR__ . '/lib/Billing/Meter.php';
require __DIR__ . '/lib/Billing/MeterEvent.php';
require __DIR__ . '/lib/Billing/MeterEventAdjustment.php';
Expand Down Expand Up @@ -125,6 +134,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 @@ -152,6 +166,7 @@
require __DIR__ . '/lib/LineItem.php';
require __DIR__ . '/lib/LoginLink.php';
require __DIR__ . '/lib/Mandate.php';
require __DIR__ . '/lib/Margin.php';
require __DIR__ . '/lib/PaymentIntent.php';
require __DIR__ . '/lib/PaymentLink.php';
require __DIR__ . '/lib/PaymentMethod.php';
Expand Down Expand Up @@ -184,6 +199,9 @@
require __DIR__ . '/lib/Service/BalanceTransactionService.php';
require __DIR__ . '/lib/Service/Billing/AlertService.php';
require __DIR__ . '/lib/Service/Billing/BillingServiceFactory.php';
require __DIR__ . '/lib/Service/Billing/CreditBalanceSummaryService.php';
require __DIR__ . '/lib/Service/Billing/CreditBalanceTransactionService.php';
require __DIR__ . '/lib/Service/Billing/CreditGrantService.php';
require __DIR__ . '/lib/Service/Billing/MeterEventAdjustmentService.php';
require __DIR__ . '/lib/Service/Billing/MeterEventService.php';
require __DIR__ . '/lib/Service/Billing/MeterService.php';
Expand Down Expand Up @@ -309,6 +327,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 +378,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')
prathmesh-stripe marked this conversation as resolved.
Show resolved Hide resolved
{
$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